歡迎來到 AmebaD (RTL8722DM) SDK 綫上文檔
Arduino SDK
Ameba RTL8722DM
歡迎來到 Ameba RTL8722DM/CSM Arduino 綫上文檔
Getting Started
Ameba ARDUINO: Getting Started with RTL8722
Required Environment
AmebaD RTL8722DM board currently supports Windows OS 32-bits and 64-bits (WIN7/8/10), Linux OS (Ubuntu 18 LTS/20 LTS/latest) and macOS operating systems. Please use the latest OS version to have the best experiences. In this documentation, please use the latest version Arduino IDE (at least version 1.8.12).
Introduction to AmebaD RTL8722CSM/RTL8722DM
Ameba is an easy-to-program platform for developing all kind of IoT applications. AmebaD is equipped with various peripheral interfaces, including WiFi, GPIO INT, I2C, UART, SPI, PWM, ADC. Through these interfaces, AmebaD can connect with electronic components such as LED, switches, manometer, hygrometer, PM2.5 dust sensors, …etc.
The collected data can be uploaded via WiFi and be utilized by applications on smart devices to realize IoT implementation.
# |
PIN name |
GPIO |
ADC |
PWM |
UART |
SPI |
I2C |
---|---|---|---|---|---|---|---|
D00 |
GPIOB_2 |
✓ |
ADC5 |
UART3_RX(b) |
|||
D01 |
GPIOB_1 |
✓ |
ADC4 |
UART3_TX(b) |
|||
D02 |
GPIOB_3 |
✓ |
ADC6 |
||||
D03 |
GPIOB_31 |
✓ |
|||||
D04 |
GPIOB_30 |
✓ |
|||||
D05 |
GPIOB_28 |
✓ |
|||||
D06 |
GPIOB_29 |
✓ |
|||||
D07 |
NC |
||||||
D08 |
GPIOB_22 |
✓ |
PWM14 |
||||
D09 |
GPIOB_23 |
✓ |
PWM15 |
||||
D10 |
GPIOB_21 |
✓ |
PWM13 |
UART0_RTS(b) |
SPI0_CS |
||
D11 |
GPIOB_18 |
✓ |
PWM10 |
UART0_RX(b) |
SPI0_MOSI |
||
D12 |
GPIOB_19 |
✓ |
PWM11 |
UART0_TX(b) |
SPI0_MISO |
||
D13 |
GPIOB_20 |
✓ |
PWM12 |
UART0_CTS(b) |
SPI0_CLK |
||
D14 |
GPIOA_7 |
✓ |
UART2_TX(log) |
||||
D15 |
GPIOA_8 |
✓ |
UART2_RX(log) |
||||
D16 |
GPIOA_25 |
✓ |
PWM4 |
UART3_RX(a) |
I2C0_SCL |
||
D17 |
GPIOA_26 |
✓ |
PWM5 |
UART3_TX(a) |
I2C0_SDA |
||
D18 |
GPIOB_7 |
✓ |
ADC3 |
PWM17 |
SPI1_CS |
||
D19 |
GPIOB_6 |
✓ |
ADC2 |
SPI1_CLK |
|||
D20 |
GPIOB_5 |
✓ |
ADC1 |
PWM9 |
SPI1_MISO |
||
D21 |
GPIOB_4 |
✓ |
ADC0 |
PWM8 |
SPI1_MOSI |
||
D22 |
GPIOA_28 |
✓ |
|||||
D23 |
GPIOA_24 |
✓ |
PWM3 |
UART0_CTS(a) |
I2C1_SDA |
||
D24 |
GPIOA_23 |
✓ |
PWM2 |
UART0_RTS(a) |
I2C1_SCL |
||
D25 |
GPIOA_22 |
✓ |
UART0_RX(a) |
||||
D26 |
GPIOA_21 |
✓ |
UART0_TX(a) |
||||
D27 |
GPIOA_20 |
✓ |
|||||
D28 |
GPIOA_19 |
✓ |
Setting up Development Environment
Step 1. Installing the Driver
First, connect RTL8722DM to the computer via Micro USB:
Step 2. Set up Arduino IDE
From version 1.6.5, Arduino IDE supports third-party hardware. Therefore, we can use Arduino IDE to develop applications on RTL8722DM, and the examples of Arduino can run on RTL8722DM too. Arduino IDE can be downloaded in the Arduino website.
When the installation is finished, open Arduino IDE. To set up RTL8722DM correctly in Arduino IDE, go to “File” -> “Preferences”.
And paste the following URL into “Additional Boards Manager URLs” field:
https://github.com/ambiot/ambd_arduino/raw/master/Arduino_package/package_realtek.com_amebad_index.json
Next, go to “Tools” -> “Board” -> “Boards Manager”:
The “Boards Manager” requires about 10~20 seconds to refresh all hardware files (if the network is in bad condition, it may take longer). Every time the new hardware is connected, we need to reopen the Board Manager. So, we close the “Boards Manager”, and then open it again. Find “Realtek AmebaD Boards (32-bits ARM Cortex-M4 @200MHz)” in the list, click “Install”, then the Arduino IDE starts to download required files for RTL8722DM.
“AmebaD_Arduino_patch1_SDK”, please select at least 1 of the SDKs. There are 5 latest released SDK options.
“AmebaD_Arduino_patch2_Tools”, please select according to your operation system. There are Windows, Linux and MacOS.
“AmebaD_Arduino_Source_Code”, this section is optional download only wants to refer the latest source code.
Download the files selected, then unzip (patch1 and patch2 are compulsory). There are “Install.doc”/“Install.pdf” for you to refer installation steps. According to your system, please run the installation tool in the “Offline_SDK_installation_tool” folder.
After the installation tool running successfully, you may open Arduino IDE and proceed to “Tools” -> “Board“ -> “Boards Manager…”. Try to find “Realtek AmebaD Boards (32-bits ARM Cortex-M4 @200MHz)”` in the list, click “Install”, then the Arduino IDE starts to download required files for RTL8722DM.
Finally, we select RTL8722DM as current connected board in “Tools” -> “Board” -> “Ameba ARM (32-bits) Boards” ->” RTL8722DM”:
Try the First Example
Step 1. Compile & Upload
Arduino IDE opens a new window with the complete sample code.
Next, we compile the sample code directly; click “Sketch” -> “Verify/Compile”
Arduino IDE prints the compiling messages in the bottom area of the IDE window. When the compilation is finished, you will get the message similar to the following figure:
To enter the upload mode, first press and hold the UART_DOWNLOAD button, then press the RESET button. If success, you should see the LED flashing on the DEV board.
It is optional for users to check if the board entered the upload mode. Open serial monitor/terminal and look for “#Flash Download Start”. Note, it is normal that some serial terminals may show unknown characters as following picture.
Again, during the uploading procedure the IDE prints messages. Uploading procedure takes considerably longer time (about 30 seconds to 1 minute). When upload completed, the “Done uploading” message is printed.
Step 2.Run the Blink example
D08
). Then we connect the LED and resistance
as the following figure:D08
, and
connect the shorter pin to GND
. In addition, please use a resister
with suitable resistance in series between LED and GND to protect LED)(End)
備註
If you face any issue, please refer to the FAQ and Trouble shooting sections on 支援 page.
Download
Release History
Version 3.1.1 - 2021/12/25
Feature:
Add BLE HID and examples
BLEHIDGamepad, BLEHIDKeyboard, and BLEHIDMouse
Update PowerSave examples
Support RTL8722DM MINI and RTL8720DN/BW16
Enable LwIP hostname edit
API Updates:
Update API for PowerSave
Update ameba_d_tools 1.0.7 for all 3 platforms
Support RTL8720DN/BW16 and RTL8722DM MINI
Add more Aon wake up pins
Update API for IR
Removed requirement to define both IR TX and RX pins in IRDevice::begin
Removed previous limit on number of time durations IRDevice::send can accept
Update GPIO Int
Enable INPUT_IRQ_CHANGE
Add definition inside wiring_constants.h and wiring_digital.c, also complete the TODO part for attachInterrupt() as well
Update UART, for RTL8720DN/BW16 not showing log issue
Fix wrong attribute permissions for characteristic CCCD descriptor. Remove unused variable warnings
Update GTimer, for the internal timer ID validation test
Updated SPI connection for RTL8720DN/BW16
Update Google_Cloud_IoT example with new Google TLS cert
Update Analog Pin remove A0 and A1
Update Platform.txt for Windows OS with User Name having a space in between
Update all libs
Misc:
Update AmebaEink.zip, SPI connection for RTL8720DN/BW16
Add Autoflash_patch folder
Update the Fritzing of RTL8720DN/BW16, remove A0 and A1
Version 3.1.0 - 2021/11/05
Feature:
Support board RTL8720DN(BW16)
Add WiFiControlCar example
Add Arduboy zip library
Add WPA3 support
Add Amebad_HMI_MQTT zip library
Add support for IPV6 wiht 4 examples
WLAN lib update
Minor bug fix
API Updates:
Support Microsoft Azure IoT cloud
Enable “strnlen” from rom
Add “#define yield” for compilation
Update PubSubClient lib
Update APIs for RTL8720DN(BW16) (SPI, I2C, Fatfs, Audiocodec and UART
Update jtag enable functions
Update wifi security option
Remove the unused libs lib_wifi_fw.a lib_wifi_ucps_fw.a
Update watchdog
Update AudioCodec
Pin mapping updates
Remove unused marcos
RTL8720DN(BW16) related naming update for all examples
Update PowerSave
Misc
Add RTL8720DN_BW16 frizting folder
Move RTL8720DN_BW16 frizting files to correct folder
Rename folder name to short the length of path
Add Offline_SDK_installation_tool (Windows, Linux and MacOS)
Update linux tools for compatibility issue
Update RTL8722DM MINI and RTL8720DN(BW16) Fritzing and Pinmux
Update ameba_d_tools V1.0.6
Add Image_Releated folder
Correct the core from Cortex-M4 to Cortex-M33
Version 3.0.11 - 2021/10/26
Feature:
Add example, FatfsSDIO - Read and open HTML file from SD card
API Updates:
RTL8720DN/BW16 related compatibility update for all examples
Misc
Update RTL8722DM MINI and RTL8720DN Fritzing and Pinmux
Version 3.0.10 - 2021/09/22
Feature:
Add AudioCodec wav examples
API Updates:
Pin mapping updates for RTL8722DM MINI
Remove unused marcos
Update platform.txt for bin files process
rollback for “wifi.h” update
Minor bug fix patch
Version 3.0.9 - 2021/09/13
API Updates:
Pin mapping updates
Remove unused marcos
“wifi.h” related files change to “Amebawifi.h”
Version 3.0.8 - 2021/05/06
Feature:
Add RTL8722DM_mini board
Add fatfs for SD card
Add AudioCodec
Add TensorFlow lite support with examples
Add zip libraries for TensorFlow lite support
Update SDK for supporting Arduino IDE 2.0
Update wlan lib
API Updates:
Update zip libraries of Eink
ADC updates, Change calculation method to use EFUSE calibration parameters and SDK formula to improve accuracy
writing_analog updates, minor bug fix and support for mini board
SPI updates, minor bug fix and support for mini board
I2S updates, minor bug fix and support for mini board
IRDevice updates, minor bug fix
Version 3.0.7 - 2020/11/19
Feature:
Add AmebaIRDevice example IRSendSONY
Update Ameba Arduino IRDevice API
Update Ameba Arduino SSL related API
Update Ameba Arduino Wlan API to support static IP function
Version 3.0.6 - 2020/10/28
Feature:
Add Ameba RTC support
Add AmebaRTC example RTC and RTCAlarm
Add Ameba Watchdog support
Add AmebaWatchdog example WatchdogTimer
Update Ameba BLE support
Add AmebaBLE example BLEUartService, DHT_over_BLEUart
Update Ameba Wlan library
Update Ameba Wlan SDK structure, add AP mode hidden SSID support
Version 3.0.5 - 2020/09/09
Feature:
Build in tool updates V1.0.4
Add zip lib AmebaEink
Add AmebaEink example EinkDisplayImage, EinkDisplayQR, and EinkDisplayText
Add google cloud examples
Update Amazon AWS related examples
Add power save support
Add AmebaPowerSave example TicklessMode, DeepSleepMode, DeepSleep_DHT_LCD_Example, and DeepSleep_DHT_Eink_Example
Version 3.0.4 - 2020/07/27
Feature:
Update BLE library. Add example BLEBatteryClient and BLEWIfiConfig
Update from polarssl to mbedtls 2.4.0
Version 3.0.3 - 2020/07/03
Feature:
Build in Image tool updates V1.0.3
Upload log clean up
Version 3.0.2 - 2020/06/30
Feature:
Windows, Linux and macOS X support
Build in Image tool updates
Version 3.0.1 - 2020/05/15
Feature:
Official release of AmebaD Arduino SDK
warning cleaning
I2C lib updates
Version 3.0.0 - 2020/05/01
Feature:
Support Boards Manager and Arduino IDE development
WiFi scan AP, connect to AP, TCP Server/Client, including 5G
Bluetooth, BLE
GPIO digital in/out and interrupt
ADC analog in/out (0 ~ 3.3V)
PWM getting analog results with digital means
SPI master and slave mode
UART 1 for log, 2 for customize usage
I2C master mode
Peripherals & Examples
Basic Examples
Ameba ARDUINO: [RTL8722CSM][RTL8722DM] Supported ARDUINO built-in example list
There are many built-in examples in Arduino. In the table below, we list all examples that are compatible with Ameba.
Category |
Name |
Comment |
---|---|---|
01.Basics |
AnalogReadSerial |
Connect potentiometer to 3.3V |
BareMinimum |
||
Blink |
Connect LED to pin 8 |
|
DigitalReadSerial |
||
Fade |
||
ReadAnalogVoltage |
ADC can read a maximum of 3.3V. |
|
02.Digital |
BlinkWithoutDelay |
Connect LED to pin 8 |
Button |
Connect LED to pin 13 |
|
Debounce |
Connect LED to pin 13 |
|
DigitalInputPullup |
Connect LED to pin 13 |
|
StateChangeDetection |
Connect LED to pin 13 |
|
toneKeyboard |
||
toneMelody |
||
toneMultiple |
||
tonePitchFollower |
||
03.Analog |
AnalogInOutSerial |
|
AnalogInput |
Connect LED to pin 13 |
|
Analog Write Mega |
||
Calibration |
Connect another LED to pin 13 |
|
Fading |
||
Smoothing |
||
04.Communication |
ASCIITable |
|
Dimmer |
Use serial baud rate 115200 |
|
Graph |
Use serial baud rate 115200, Connect potentiometer to 3.3V |
|
Midi |
Please use Serial1 and pin 26, or use Serial2 and pin 17 |
|
MultiSerial |
||
PhysicalPixel |
Use serial baud rate 115200 |
|
ReadASCIIString |
||
SerialCallResponse |
Use serial baud rate 115200 |
|
Serial CallResponseASCII |
Use serial baud rate 115200 |
|
SerialEvent |
||
SerialPassthrough |
||
VirtualColorMixer |
Use serial baud rate 115200 |
|
05.Control |
Arrays |
Use pins 1, 2, 3, 4, 5, 6 |
ForLoopIteration |
Use pins 1, 2, 3, 4, 5, 6 |
|
IfStatementConditional |
||
switchCase |
||
switchCase2 |
||
While StatementConditional |
Connect another LED to pin 13 |
|
06.Display |
barGraph |
Use another pin to replace pin 7 |
RowColumnScanning |
||
07.Strings |
CharacterAnalysis |
|
String AdditionOperator |
||
StringAppendOperator |
||
StringCaseChanges |
||
StringCharacters |
||
String ComparisonOperators |
||
StringIndexOf |
||
StringLength |
||
StringLengthTrim |
||
StringReplace |
||
String StartsWithEndsWith |
||
StringSubstring |
||
StringToInt |
Network Examples
Connect to WiFi
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Procedure
There three common encryption type in WiFi connection. The first one is “OPEN”, which means there is no password needed to connect to this network. The second type of encryption is WPA, which requires the correct password to access. The third type is WEP, which requires a hexadecimal password and a keyindex.
In the following, we will give a brief introduction on how to establish WiFi connection with these three types of encryption on Ameba.
First, make sure the correct Ameba development board is selected in “Tools” -> “Board”.
Open (WiFi connection without password)
Open the “ConnectNoEncryption” example in
“File” -> “Examples” -> “AmebaWiFi” -> “ConnectWithWiFi” -> “ConnectNoEncryption”
![]()
In the sample code, modify “ssid” to be the same as the WiFi SSID to be connected to.
Next, upload the sample code, and press the reset button on Ameba. Then you will see a message “You’re connected to the networkSSID: XXXXX”, and the information of this WiFi connection is printed in the serial monitor every 10 seconds.
![]()
WiFi connection with WPA encryption
Open the “ConnectWithWPA” example in
“File” -> “Examples” -> “AmebaWiFi” -> “ConnectWithWiFi” -> “ConnectWithWPA”
In the sample code, modify “ssid” to the WiFi SSID to be connected to and “pass” to the network password.
Next, upload the sample code, and press the reset button on Ameba. Then you will see a message “You’re connected to the networkSSID: XXXXX”, and the information of this WiFi connection is printed in the serial monitor every 10 seconds.
WiFi connection with WEP encryption
Open the “ConnectWithWEP” example in
“File” -> “Examples” -> “AmebaWiFi” -> “ConnectWithWiFi” -> “ConnectWithWEP”
In the sample code, modify “ssid” to the SSID to be connected, “key” to the hexadecimal password, “keyIndex” to your key index number.
Next, upload the sample code, and press the reset button on Ameba. Then you will see a message “You’re connected to the networkSSID: XXXXX”, and the information of this WiFi connection is printed in the IDE every 10 seconds.
Code Reference
WiFi.SSID()
to get SSID of the current connected network.WiFi.RSSI()
to get the signal strength of the connection.WiFi.encryptionType()
to get the encryption type of the WiFi
connection.WiFi.BSSID()
to get the MAC address of the router you are
connected to.WiFi.macAddress()
to get the MAC address of Ameba.WiFi.localIP()
to get the IP address of Ameba.WiFi.subnetMask()
to get the subnet mask.WiFi.gatewayIP()
to get the WiFi shield’s gateway IP address.Comparison with Arduino
#include
to
use SPI to communicate with WiFi module.#include
is not needed.Use Ameba as Server to communicate with Client
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Laptop(Make sure it is connected to the same network domain as Ameba, and tcp tools are installed.)
Example
In this example, we first connect Ameba to WiFi, then we use Ameba as server to communicate with client.
First, we make sure the correct Ameba development board is set in “Tools” -> “Board”
Then, open the Simple WiFi Server example in “File” -> “Examples” ->
“AmebaWiFi” -> “SimpleServerWiFi”
In the sample code, modify the highlighted parameters and enter the ssid and password for your WiFi connection.
Next, upload the code, then press the reset button on Ameba. At this moment, you will see the connection information is displayed in the console.
Next, we use the socket tool in the laptop to be the client and connect to the IP address of the Ameba board shown in the connection information at port 5000. (Note: The socket tool we used in this example is “sokit”)
Click on the “Client” tab to choose the client mode, specify the IP and port of the server, then click “TCP Connect”.
If the connection is established successfully, the server shows a message: “A client connected to this Server”, and the IP and port of the connected client.
In this example, when the client and server are connected and the client sends a string to Ameba server, the Ameba server returns the identical string back to the client.
The string sent to server is returned and showed at the client side.
Code Reference
WiFi.begin()
to establish WiFi connection;WiFi.SSID()
to get SSID of the current connected network.WiFi.RSSI()
to get the signal strength of the connection.WiFi.localIP()
to get the Ameba WiFi shield’s IP address.Server(port)
to create a server that listens on the specified
port.server.begin()
to tell the server to begin listening for incoming
connections.server.available()
to get a client that is connected to the server
and has data available for reading.client.read()
to read the next byte received from the server.client.write()
to write data to the server.client.stop()
to disconnect from the server.Use Ameba to retrieve HTTP websites from the internet
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaHttp” -> “SimpleHttpExample”
Code Reference
WiFi.begin()
to establish WiFi connection:WiFi.SSID()
to get SSID of the current connected network.WiFi.RSSI()
to get the signal strength of the connection.WiFi.localIP()
to get the IP address of Ameba.Use http.get()
to send a GET request to the website.
Use Ameba to retrieve information from the Internet
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaWiFi” -> “WiFiWebClient”
In the sample code, modify the highlighted snippet and enter the required information (ssid, password, key index) required to connect to your WiFi network.
Upload the code and press the reset button on Ameba. Then you can see the information retrieved from Google is shown in the Arduino serial monitor.
Code Reference
WiFi.SSID()
to get
SSID of the current connected network.WiFi.RSSI()
to get the signal strength of the connection.WiFi.localIP()
to get the IP address of Ameba.WiFiClient()
to create a client.client.connect()
to connect to the IP address and port specified.client.println()
to print data followed by a carriage return and
newline.client.available()
to return the number of bytes available for
reading.client.read()
to read the next byte received from the server the
client is connected to.client.stop()
to disconnect from the server the client is
connected to.Use Ameba as Server to control LED
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Breadboard x 1
LED x 1
1KΩ Resistor x 1
Procedure
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
“File” -> “Examples” -> “AmebaWiFi” -> “SimpleWebServerWiFi”
Upload the code and press the reset button on Ameba. When the connection is established, you will see the message:
“To see this page in action, open a browser to http://xxx.xxx.xxx.xxx”
in the Arduino IDE as shown in the figure:
Next, open the browser of a computer or a cell phone under the same WiFi domain, enter the address in the message.
In the webpage, you can turn on/off the LED.
Code Reference
WiFi.begin()
to establish WiFi connection.WiFi.SSID()
to get SSID of the current connected network.WiFi.localIP()
to get the IP address of Ameba.WiFiServer server()
to create a server that listens on the
specified port.server.begin()
to tell the server to begin listening for incoming
connections.server.available()
to get a client that is connected to the server
and has data available for reading.client.connected()
to get whether or not the client is connected.client.println()
to print data followed by a carriage return and
newline.client.print()
to print data to the server that a client is
connected to.client.available()
to return the number of bytes available for
reading.client.read()
to read the next byte received from the server the
client is connected to.client.stop()
to disconnect from the server the client is
connected to.Use Ameba as Server to send Ameba status
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaWiFi” -> “WiFiWebServer”
Code Reference
WiFi.begin()
to establish WiFi connection.WiFi.SSID()
to get SSID of the current connected network.WiFi.RSSI()
to get the signal strength of the connection.WiFi.localIP()
to get the IP address of Ameba.WiFiServer server()
to create a server that listens on the
specified port.server.begin()
to tell the server to begin listening for incoming
connections.server.available()
to get a client that is connected to the server
and has data available for reading.client.connected()
to check whether or not the client is connected.client.println()
to print data followed by a carriage return and
newline.client.print()
to print data to the server that a client is
connected to.client.available()
to return the number of bytes available for
reading.client.read()
to read the next byte received from the server the
client is connected to.client.stop()
to disconnect from the server the client is
connected to.Use Ameba as UDP server
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaWiFi”
-> “WiFiUdpSendReceiveString”
Compile the code and upload it to Ameba. After pressing the Reset button, Ameba connects to WiFi and starts the UDP server with port 2390. After the UDP server starts service, Ameba prints the “Starting connection to server” message and waits for client connection.
Code Reference
begin()
to open an UDP port on Ameba.parsePacket()
to wait for data from client.remoteIP()
and remotePort()
to
get the IP and port of the client.read()
to read the data sent by client.beginPacket()
, write()
, end()
.Retrieve Universal Time (UTC) By Ameba
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaWiFi” -> “WiFiUdpNtpClient”
Use MQTT To Upload And Listen To Data
Intro to MQTT
MQTT (Message Queuing Telemetry Transport) is a protocol proposed by IBM and Eurotech. The introduction in MQTT Official Website: MQTT is a machine-to-machine (M2M)/”Internet of Things” connectivity protocol. It was designed as an extremely lightweight publish/subscribe messaging transport. We can say MQTT is a protocol designed for IoT. MQTT is based on TCP/IP and transmits/receives data via publish/subscribe. Please refer to the figure below:
In the operation of MQTT, there are several roles:
Publisher: Usually publishers are the devices equipped with sensors (ex. Ameba). Publishers uploads the data of the sensors to MQTT-Broker, which serves as a database with MQTT service.
Subscriber: Subscribers are referred to the devices which receive and observe messages, such as a laptop or a mobile phone.
Topic: Topic is used to categorized the messages, for example the topic of a message can be “PM2.5” or “Temperature”. Subscribers can choose messages of which topics they want to receive.
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaMQTTClient” ->
“MQTT_Basic”
The “mqttServer” refers to the MQTT-Broker, we use the free MQTT sandbox “test.mosquitto.org” for testing.
“clientId” is an identifier for MQTT-Broker to identify the connected device.
“publishTopic” is the topic of the published message, we use “outTopic” in the example. The devices subscribe to “outTopic” will receive the message.
“publishPayload” is the content to be published.
“subscribeTopic” is to tell MQTT-broker which topic we want to subscribe to.
Install and open the MQTTLens, click “+” next to “Connection” on the left, and fill in the required information
Connection Name: Used to identify the connection, you can choose a name you like.
Hostname: The MQTT-Broker server, here we use “iot.eclipse.org”
Client ID: We use the default randomly generated ID.
Use Amazon AWS IoT Shadow Service
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
REST API endpoint: In the value “https://a1a7oo4baosgyy.iot.us-east-1.amazonaws.com/things/ameba/shadow”, the part “a1a7oo4baosgyy.iot.us-east-1.amazonaws.com” is the MQTT Broker server address.
MQTT topic:The value “$aws/things/ameba/shadow/update” represents the MQTT topic we will use in the AWS IoT Shadow service (if we use MQTT only, without AWS IoT Shadow service, then we can specify other topic name). It is recommended to use “$aws/things/ameba/shadow/update” here.
Ameba setting
“File” -> “Examples” -> “AmebaMQTTClient” -> “Amazon_AWS_IoT_Basic”
Compile and run
Alternatives
Ameba can also retrieve the current LED status variable from the AWS shadow. This is done by sending a message to the “shadow/get” topic. Refer to the Amazon_AWS_IoT_with_ACK example code for more information.
Code Reference
pinMode(led_pin, OUTPUT);
digitalWrite(led_pin, led_state);
WiFiSSLClient wifiClient;
wifiClient.setRootCA((unsigned char*)rootCABuff);
wifiClient.setClientCertificate((unsigned char*)certificateBuff,(unsigned char*)privateKeyBuff);
client.setServer(mqttServer, 8883);
client.setCallback(callback);
loop()
, call reconnect()
function and try to connect to MQTT Broker
server and do the certificate verification.while (!client.connected()) {
for (int i=0; i<5; i++) {
client.subscribe(subscribeTopic[i]);
}
sprintf(publishPayload,
"{\"state\":{\"reported\":{\"led\":%d}},\"clientToken\":\"%s\"}",
led_state, clientId);
client.publish(publishTopic, publishPayload);
if (strstr(topic, "/shadow/get/accepted") != NULL) {
If there is, the message is from the control side. If the attribute state in the message is different from current state, publish the new state.
updateLedState(desired_led_state);
Use MQTT over TLS
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” ->
“AmebaMQTTClient” -> “MQTT_TLS”
Upload PM2.5 Data to LASS System
Intro to LASS
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
PlanTower PMS3003 or PMS5003 x1
Example
In this example, we use applications mentioned at our website, including:
MQTT: a MQTT-Broker to connect to LASS. The Client is “FT1_0XXXX”, the XXXX are the four last digits of Ameba’s Wi-Fi MAC, and the outTopic is “LASS/Test/Pm25Ameba/clientID“, where clientID is the actual Ameba’s MQTT client ID.
NTP: uploaded data must have time notation
PM2.5: uploaded data includes PM2.5 information
“File” -> “Examples” -> “AmebaMQTTClient” ->
“lass_basic”
gps_lat
and gps_lon
.Ameba AP Mode
In AP mode, Ameba can accept at most 3 station connections, and can be set to open mode or WPA2 mode.
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaWiFi” ->
“WiFiAPMode”
In the highlighted code snippet, fill in your SSID, PASSWORD and CHANNEL.
The code highlighted in green is the API we used to turn on the AP mode in security mode.
If you want to turn on the AP mode in open mode, please modify the code to
status = WiFi.apbegin(ssid, channel);
Then upload the sample code and press reset, and you can see related information shown in serial monitor.
In the figure below, we show the messages shown in serial monitor when two stations connect to Ameba AP in open mode:
In the figure below, we show the messages shown in serial monitor when a station connects to Ameba AP in security mode:
Use mDNS To Let Arduino IDE Find Ameba
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
mDNS (Multicast DNS) is a protocol used in the local area network. It delivers the network information like IP address and provided services to others. mDNS is based on the UDP protocol, and it sends packets to 224.0.0.251 with port 5353 under IPv4 address. The naming style for the service follows the format: {Instance Name}.{Protocol Name}.{Domain}
Instance Name: used to identify the name of the service
Protocol Name: Divided into two parts, the front end is in regard to the name of the service, and it adds baseline as a prefix. The rear end is in regard to the transport protocol name it used, and it also adds baseline as a prefix
Domain: Local area network in normal cases
“File” -> “Examples” -> “AmebaMDNS” -> “mdns_on_arduino_ide”
Next, go to (“Tools” ->
“Port”), and you can find out at least one Serial Port. This port is
simulated by Ameba board via USB. Choose this port and upload the
compiled code to Ameba.After uploading the code, press the reset
button on Ameba and waiting for Ameba to connect with AP and activate
the mDNS service after a while. You can see the Log at the bottom of the
Serial Monitor.
Then you can find out the added item “Network
Ports” “MyAmeba at 192.168.1.167 (Ameba RTL8722DM/RTL8722CSM)”,
“MyAmeba” is the device name we set up, and “IP” is the IP address that
AP assigned to Ameba, the IP address should be the same with the IP
shown in the Serial Monitor. Last, “Ameba RTL8722DM/RTL8722CSM” is the
type name of the board, and it means that Ameba can let Arduino IDE
identify the mDNS service successfully.(We still can not use the
Internet to upload the code, and we will explain this part in the OTA
example.)
Does your computer in the same local area network with the Ameba?
Restart the Arduino IDE, and it will find the mDNS service again
Check the Log in Serial Monitor if the Ameba connects to the AP and activate mDNS service successfully
Code Reference
The program set up the mDNS service in the beginning, the first parameter is Instance Name, and it is changeable in this example. The second parameter is the protocol that the service used, and it would be “_arduino._tcp” for Arduino IDE. The third parameter is Domain, and it would be “local” in common. The fourth parameter is the port number for the service, it is 5000 here and we doesn’t use it in the example.
MDNSService service("MyAmeba", "_arduino._tcp", "local", 5000);
After connected to the network, we set up some text fields for the service. For the following example, “board” is the name of the field, “ameba_rtl8721d” is the value of the field. “board” is used to let Arduino IDE check installed SDK to see if it exists known device or not. We will use the name of the device if there is known device, users can change “ameba_rtl8721d” to “yun” or other names to find out what’s the difference if interested.
service.addTxtRecord("board", strlen("ameba_rtl8721d"),"ameba_rtl8721d");
Then we add three text fields “auth_upload”, “tcp_check”, and “ssh_upload”, this example does not activate these services.
service.addTxtRecord("auth_upload", strlen("no"), "no");
service.addTxtRecord("tcp_check", strlen("no"), "no");
service.addTxtRecord("ssh_upload", strlen("no"), "no");
Next we activate MDNS
MDNS.begin();
and register to the mDNS service.
MDNS.registerService(service);
Use Firebase To Push Messaging Services
Preparation
Ameba x 1
Android Studio
Smart phone with Google Play Service x 1
Example
In the era of the popularity of smart phones, people often receive reminders from specific apps. In this example, we will teach how to use Google Firebase to send messages from the Ameba Client to mobile phones.
First, we use Firebase Cloud Messaging (FCM) as a cross-platform messaging solution that lets you deliver messages for free and reliably.
With FCM, you can notify your client application (App) to sync emails or other data. You can send a message to drive user engagement. For instant messaging content, a message can transfer up to 4KB of payload to the client application.

The FCM implementation includes two main parts for sending and receiving:
You can use Admin SDK or HTTP&XMPP API to send messages.To test or send marketing or engagement messages with powerful built-in targeting and analytics, you can also useNotifications composer
We know that Ameba can send messages to specific apps as long as it implements the http client function.
First of all, we must first set up an environment for developing Android apps. Please download Android Studio first on Android official website.
https://developer.android.com/studio/install
Then we can use the Android example provided by Firebase to download Firebase Quickstart Samples.
https://github.com/firebase/quickstart-android
Open Android Studio and click on Import Project, select the messaging project in Firebase Quickstart Samples. Since we won’t use other functions, we can only choose the messaging project.
Android Studio will need to install the SDK and Google repository for the first time to start the messaging project. You can refer to the following page for update.
https://developer.android.com/studio/intro/update
Wait until the required components for compiling the app are installed, you can open the messaging project, and Android Studio comes with the Firebase registration function.

As shown above, open the toolbar and click Tools->Select Firebase.

Open Firebase Assisant in the right pane, then see Cloud Messaging, select Set up Firebase Cloud Messaging to start the registration process.

Click Connect to Firebase

Then bring out the page, and click on Firebase on the left and log in to the Gmail account. Once you log in, you will be taken to the Firebase homepage.

Let’s keep the homepage first, we need to go to the Firebase Console and go back to Android Studio.

We can see that when the webpage is successfully logged in, Android Studio also brings up the login information dialog box, click connect to Firebase


As shown above, the messaging app is installed and executed successfully on the phone. Click LOG TOKEN at this time.

There will be a Token ID, which is the Access Token required to send the message, representing the ID of the FCM service APP installed on a particular phone. This ID is unique and will be reassigned when the app is removed and re-installed. It means that the message can be sent to a specific phone. The FCM service can also push messages to a NEWS (Topic). This section can be found in Firebase topic-messaging:
https://firebase.google.com/docs/cloud-messaging/android/topic-messaging
Therefore, we need to save this Access Token, return to Android Studio as shown below, select Debug at the log level of the Logcat. When you press the LOG TOKEN button on the App, Logcat will print out the Access Token ID. We will save the code after the InstanceID Token: in the Log message.

Then we have to go back to the page that was brought when we first logged into Firebase.

Click in the upper right corner to go to the console

At this point, You can see that Android Studio has just built the messaging project for us in the operation.

Click to enter the messaging project with settings page, as shown above.

Select Set up

“File” -> “Examples” -> “AmebaWiFi” -> “Firebase.ino”

As shown above, ACCESS_TOKEN and SERVER_KEY are defined in the reverse white part, that is, the ACCESS token ID that we just saved from the APP and the Server Key saved in the Firebase console page. We fill in the two sets of IDs, compile and upload them to Ameba. Press the Reset button and open the terminal.

Connect to FCM Server after connecting to AP

After showing Connect to Server successful, it means that the FCM connection is successful and the message will be sent. During the process, HTTP/1.1 200 OK will be received to indicate that the message is successfully pushed. At this time, the mobile phone screen is opened and the App receives the message from Ameba.

Code Reference
https://firebase.google.com/docs/cloud-messaging/send-message
The main payload format in the program is as follows. The user can freely change the Title and Body of the message. Body represents the content of the message.
char const* payload = "{" \
"\"to\": \"" ACCESS_TOKEN "\"," \
"\"notification\": {" \
"\"body\": \"Hello World!\"," \
"\"title\" : \"From Realtek Ameba\" " \
"} }" ;
setup() {
if (client.connect(server, 80)) {
Serial.println("connected to server");
// Make a HTTP request:
sprintf(message,"%s%s%s%s%s%d%s%s%s","POST /fcm/send HTTP/1.1\nContent-Type: application/json\nAuthorization: key=",SERVER_KEY,"\nHost: ",HOST_NAME,"\nContent-Length: ",strlen(payload),"\n\n",payload,"\n");
printf("\nRequest:\n%s \n",message);
client.println(message);
client.println();
}
}
The sprintf part puts the payload into the HTTP POST content and sends the message out after connecting to the FCM Server.
loop(){
while (client.available()) {
char c = client.read();
Serial.write(c);
}
}
Waiting for the response from Server and printing out the response.
Access IFTTT Via Ameba
Introduction to IFTTT
IFTTT, known as If This Then That, is a website and mobile app and free web-based service to create the applets, or the chains of simple conditional statements. The applet is triggered by changes that occur within other web services such as Gmail, Facebook, Telegram, Instagram, Pinterest etc.
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
An account from https://ifttt.com/ , in order to access IFTTT service*
備註
Upon log in, there are several cloud and online services that are integrated with IFTTT platforms.
Example
Generate Applet from IFTTT
In this example, we obtain an example of IFTTT Applet to send email to specified recipient.
To run the example, HTTP POST feature of the Ameba is used to post a simple webhook service that is received by IFTTT platform and in turn be used to trigger a response (sending an email).
After logging in https://ifttt.com/, click Create from the top bar.
Click “Add” to add the trigger.
Choose Webhooks service as shown below. Alternatively, search the service by typing into the search bar.
After that, the available triggers will appear. Choose Receive a Web request.
Next, an Event Name is required to identify the trigger successfully. In this example, set the Event name as “test_event”.
Next, click Add in Then That field to create the action service taken in response to the last trigger.
Choose Email as the action service.
Click on Send me an email.
Under the template of Send me an Email, the contents of the email, such as subject and body is editable. Click Create Action to complete the action. Take note that Email service is offered to the email address registered under IFTTT account.
Post the Trigger via Ameba
“File” -> “Examples” -> “AmebaWiFi” -> “HTTP_IFTTT_Post”
The WiFi credentials to connect to the Wi-Fi hotspot or access point of desirable choice.
Under the Host name field, enter the host name of the IFTTT service “maker.ifttt.com”.
Under the Path name field, enter the Event name and key field “/trigger/Event name/with/key/Key Field”
Event name: The event name should be the same as the one specified in the IFTTT applet. In this example, the event name is “test_event”.
Key Field: Available under webhook service in individual IFTTT account. See the next step for the steps to obtain the Key Field.
To obtain a key from documentation tab of the Webhooks, find the webhook service in the Explore tab.
On the Webhooks service page, click on the Documentation tab.
The key can be found in the documentation page. Also, information on how HTTP request can be used.
Thereafter an email is sent to recipient email account registered at IFTTT Applet and email notification will be received.
Use Ameba To Securely Retrieve Information From The Internet
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
This example uses Ameba to securely retrieve information from the internet using SSL. SSL is an acronym for Secure Sockets Layer. It is a cryptographic protocol designed to provide communications security over a computer network, by encrypting the messages passed between server and client.
Open the “WiFiSSLClient” example in “File” -> “Examples” -> “AmebaWiFi”
-> “WiFiSSLClient”
.
In the sample code, modify the highlighted snippet to reflect your WiFi network settings.
Upload the code and press the reset button on Ameba once the upload is finished.
Open the serial monitor in the Arduino IDE and observe as Ameba retrieves a text file from os.mbed.com.
Code Reference
Use “WiFiSSLClient client;” to create a client that uses SSL. After creation, the client can be used in the same way as a regular client.
BLE – BLE Battery Service
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Android / iOS mobile phone
Example
Introduction
BLE connections use a server client model. The server contains the data of interest, while the client connects to the server to read the data. Commonly, a Bluetooth peripheral device acts as a server, while a Bluetooth central device acts as a client. Servers can contain many services, with each service containing a some set of data. Clients can send requests to read or write some data and can also subscribe to notifications so that the server can send data updates to a client.
In this example, a basic battery service is set up on the Ameba Bluetooth stack. A mobile phone is used to connect to the Ameba peripheral device and read the battery data.
Procedure
Ensure that the following Bluetooth apps are installed on your mobile phone. These apps will show you the raw data sent by Ameba and allow you to interact with the data.
The recommended application is nRF connect, and is available at the links below:
LightBlue is an alternative application that can also be used, but has less features:
Open the example, “Files” -> “Examples” -> “AmebaBLE” ->
“BLEBatteryService”
Connect to the Ameba Bluetooth device, and a list of available services should appear. Click on the battery service to expand it, and you can see the battery level data value. The arrows highlighted in the box on the right are used to read data and subscribe to notifications. Click on the single arrow to read the battery level value, and a 90% value will appear.
Click on the triple arrow to subscribe to updates on the battery level value, and the battery value will start updating by itself.
The serial monitor will show the sketch increasing the battery level every second. When you click on either of the arrows, the sketch running on the Ameba will be notified, and will print out the action taken.
Code Reference
BLEService and BLECharacteristic classes are used to create and define the battery service to run on the Bluetooth device.
BLE.configAdvert()->setAdvType(GAP_ADTYPE_ADV_IND)
is used to set the
advertisement type to a general undirected advertisement that allows for
connections.
setReadCallback()
and setCCCDCallback()
is used to register functions
that will be called when the battery level data is read, or notification
is enabled by the user.
BLE.configServer(1)
is used to tell the Bluetooth stack that there will
be one service running.
addService()
registers the battery service to the Bluetooth stack.
BLE – BLE Beacon
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Android / iOS mobile phone
Example
Introduction
A BLE beacon broadcasts its identity to nearby Bluetooth devices, to enable the other devices to determine their location relative to the beacon, and to perform actions based on information broadcasted by the beacon.
Example applications of beacons include indoor positioning system, location-based advertising and more.
From the definition of its purpose as a broadcast device, a BLE beacon thus cannot be connected to, and can only send information in its Bluetooth advertisement packets.
There are several BLE beacon protocols. The Ameba BLEBeacon library supports the iBeacon and AltBeacon protocols.
Procedure
LightBlue is an alternative application that can also be used, but has less features:
Open the example, “Files” -> “Examples” -> “AmebaBLE” -> “BLEBeacon”
Upload the code and press the reset button on Ameba once the upload is finished.
On your mobile phone, open the Bluetooth app and scan for the beacon signal broadcast by Ameba.
If you happen to be in an environment with multiple BLE beacons, you can tap the entries to expand them, and verify that the beacon data is identical to the data in the sketch.
Code Reference
setRssi()
is used to set the received signal strength indicator (rssi)
data field for a beacon. The specification states that this should be
the received signal strength from the beacon at a 1 meter distance. With
no method to measure this, it is set to -65dBm as an estimate.
setMajor()
and setMinor()
are used to set the two data fields. The
purpose of these data are left for the manufacturer of the beacon to
define, and can be used in any way.
setUUID()
is used to give the beacon a universally unique identifier
(UUID). This is a 128-bit number usually expressed as a hexadecimal
string. It is used to identify each unique beacon, and can be randomly
generated for free online.
The BLEBeacon library includes both iBeacon and AltBeacon classes, replace line 6 iBeacon with altBeacon to create an AltBeacon instead. The data fields are mostly the same, with only minor changes, please look at the header files for more details.
BLE.init()
is used to allocate memory and prepare Ameba for starting the
Bluetooth stack.
BLE.configAdvert()
is used to configure the Bluetooth advertisement
settings, to which we pass the beacon data and set the device as
non-connectable.
BLE.beginPeripheral()
starts Ameba in Bluetooth peripheral mode, after
which it will begin to advertise with the beacon data provided.
BLE – BLE Scan
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Android / iOS mobile phone
Example
Introduction
This example configures the Ameba as a Bluetooth central device, uses the scan functionality to scan for other Bluetooth devices, and prints out the results to the serial monitor.
Procedure
Open the example, “Files” -> “Examples” -> “AmebaBLE” -> “BLEScan”
If you have the Bluetooth app nRF Connect installed, you can also use it to send out Bluetooth advertisements for the Ameba to pick up.
Code Reference
setScanMode(GAP_SCAN_MODE_ACTIVE)
is used to set the scan mode. Active
scanning will request for an additional scan response data packet from a
device when it is found. Passive scanning will only look at the
advertisement data, and not request for additional data.
setScanInterval()
and setScanWindow()
are used to set the frequency and
duration of scans in milliseconds. A scan will start every interval
duration, and each scan will last for the scan window duration. The scan
window duration should be lesser or equal to the scan interval. Set a
short interval to discover devices rapidly, set a long interval to
conserve power.
setScanCallback(scanFunction)
is used to register a function to be
called when scan results are received. This can be used to set a user
function for additional processing of scan data, such as looking for a
specific device. If no function is registered, the scan results are
formatted and printed to the serial monitor by default.
beginCentral(0)
is used to start the Bluetooth stack in Central mode.
The argument 0 is used to indicate that no clients will be operating in
central mode.
startScan(5000)
is used to start the scanning process for a specified
duration of 5000 milliseconds. The scan will repeat according to the set
scan interval and scan window values. After 5000 milliseconds, the scan
process will stop, and will be ready to be started again.
BLE – Battery Client
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
Introduction
BLE connections use a server client model. The server contains the data of interest, while the client connects to the server to read the data. Commonly, a Bluetooth peripheral device acts as a server, while a Bluetooth central device acts as a client. Servers can contain many services, with each service containing a some set of data. Clients can send requests to read or write some data and can also subscribe to notifications so that the server can send data updates to a client.
In this example, a basic battery client is set up on the Ameba Bluetooth stack. The client connects to another Ameba board running the corresponding BLE battery service to read the battery level data.
Procedure
On the first Ameba board, upload the BLEBatteryService example code and let it run.
For the second Ameba board, open the example “Files” -> “Examples” ->
“AmebaBLE” -> “BLEBatteryClient”
.
Upload the code and press the reset button on Ameba once the upload is finished.
Open the serial monitor and observe the log messages as the Ameba board with the battery client scans, connects, and reads data from the Ameba board with the battery service.
Highlighted in yellow, the Ameba board with the battery client first scans for advertising BLE devices with the advertised device name “AMEBA_BLE_DEV” and the advertised service UUID of 0x180F representing the battery service.
After finding the target device, the Ameba board with the battery client forms a BLE connection and searches for a battery service on the connected device, highlighted in blue.
With the client connected to the service, the battery client begins to read data using both regular data reads and notifications, highlighted in green.
Code Reference
BLEClient is used to create a client object to discover services and characteristics on the connected device.
setNotifyCallback()
is used to register a function that will be called when a battery level notification is received.
BLE.configClient()
is used to configure the Bluetooth stack for client operation.
addClient(connID)
creates a new BLEClient object that corresponds to the connected device.
BLE – WiFi Configuration Service
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Android / iOS mobile phone
Example
Introduction
In this example, a WiFi configuration service is set up on the Ameba Bluetooth stack. A mobile phone with the configuration app connects to the Ameba device using BLE and configures the Ameba to connect to the correct WiFi access point.
Procedure
Ensure that the Realtek WiFi configuration app is installed on your mobile phone, it is available at:
Open the example, “Files” -> “Examples” -> “AmebaBLE” ->
“BLEWifiConfigService”
.
Upload the code and press the reset button on Ameba once the upload is finished.
On your mobile phone, open the Realtek WiFiConfig app and tap the round button to scan for Ameba boards.
Select the correct Ameba board from the scan results. The app will connect to the Ameba board and ask the board to scan for WiFi networks and send the scan results back to the app using BLE.
If your phone is currently connected to a WiFi network, the app will ask for the WiFi password to connect the Ameba board to the same WiFi network. Tap “Select AP” to choose another WiFi network, or enter the password and tap continue to connect Ameba to the selected WiFi network.
After the Ameba board connects to the WiFi network, the following message will be shown. Tap “Try another AP” to connect to another WiFi network or tap “Confirm” to keep the current WiFi network and disconnect BLE from the Ameba board.
Code Reference
BLEWifiConfigService is used to create an instance of the WiFi configuration service to run on the Bluetooth device.
BLE.configAdvert()->setAdvType(configService.advData())
is used to set
the correct advertisement data necessary for the phone app to find the
Ameba Bluetooth device.
BLE – BLE UART Client
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 2
Example
Introduction
In this example, two RTL8722 boards are connected using BLE. One board runs a BLE UART service, while the other connects to the service using a client and both boards are able to communicate with text messages over the UART service.
Procedure
On the first board, upload the BLE UART service example code. Refer to the example guide for detailed instructions.
For the second board, open the example, “Files” -> “Examples” ->
“AmebaBLE” -> “BLEUartClient”
.
Code Reference
The BLEClient class is used to discover the services that exist on a connected BLE device. The discovery process will create BLERemoteService, BLERemoteCharacteristic and BLERemoteDescriptor objects corresponding to the services, characteristics and descriptors that exist on the connected device. These objects can then be used to read and write data to the connected device.
BLE – BLE UART Service
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Android / iOS smartphone
Example
Introduction
Procedure
Open the example, “Files” -> “Examples” -> “AmebaBLE” ->
“BLEUartService”
.




Code Reference
set__Property()
methods, and callback
functions are registered using the set__Callback()
methods. The
required buffer size is also set for each characteristic so that it
has enough memory to store a complete string.notify()
method is used to
inform the connected device of the new data.BLE – DHT over BLE UART
Materials
AmebaD [RTL8722DM/ RTL8722CSM/ RTL8722DM MINI] x 1
DHT11 or DHT22 or DHT21
Android / iOS smartphone
Example
Introduction
In this example, the data obtained from a DHT temperature and humidity sensor are transmitted over a BLE UART service to a smartphone. Refer to the other examples for detailed explanations of using the DHT sensor and the BLE UART service.
Procedure
Connect the DHT sensor to the Ameba board following the diagram.
RTL8722DM / RTL8722CSM:
RTL8722DM MINI:
Open the example, “Files” -> “Examples” -> “AmebaBLE” ->
“DHT_over_BLEUart”
.
BLE – PWM over BLE UART
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
RGB LED
Android / iOS smartphone
Example
Introduction
In this example, a smartphone app is used to transmit commands over BLE UART to control the PWM outputs and change the color of a RGB LED. Refer to the other example guides for detailed explanations of the BLE UART service.
Procedure
Connect the RGB LED to the RTL8722 board following the diagram, the common LED pin may need to connect to 3.3V or GND depending on the type of LED (common anode / common cathode).
RTL8722DM / RTL8722CSM:
RTL8722DM MINI:
Open the example, “Files” -> “Examples” -> “AmebaBLE” ->
“PWM_over_BLEUart”
.
Upload the code and press the reset button on Ameba once the upload is finished.
Using the color selection wheel, saturation, and brightness sliders, choose a desired color and click select to send the RGB values to the board. You should see the RGB LED change to the matching color.
Code Reference
The RGB values are sent as three consecutive bytes prefixed by “!C” characters. The “!” exclamation mark is used to indicate that the following data is a command, and the “C” character is used to indicate that the data is RGB values. The received UART message is checked in the callback function for “!C” first, otherwise it is treated as a regular message and printed to the serial terminal.
BLE - HID Gamepad
Materials
AmebaD [RTL8722DM/RTL8722CSM/RTL8722DM MINI] x 1
BLE capable host device [Windows / Linux / MacOS / Android
Example
Introduction
In this example, the RTL8722 board emulates a HID gamepad connected using BLE.
Procedure
Open the example, “Files” -> “Examples” -> “AmebaBLE” -> BLEHIDGamepad
.
Code Reference
By default, the board emulates a gamepad with an 8-direction hat switch (d-pad), 6 analog axes and 16 buttons. How the inputs are interpreted is dependent on the host device, and the button ordering may differ between devices. Also, some axes or buttons may be disabled or missing on certain host devices.
BLE - HID Keyboard
Materials
AmebaD [RTL8722DM/RTL8722CSM/RTL8722DM MINI] x 1
BLE capable host device [Windows / Linux / MacOS / Android
Example
Introduction
In this example, the RTL8722 board emulates a HID keyboard connected using BLE.
Procedure
Open the example, “Files” -> “Examples” -> “AmebaBLE” -> BLEHIDKeyboard
.
BLE - HID Mouse
Materials
AmebaD [RTL8722DM/RTL8722CSM/RTL8722DM MINI] x 1
BLE capable host device [Windows / Linux / MacOS / Android
Example
Introduction
In this example, the RTL8722 board emulates a HID mouse connected using BLE.
Procedure
Open the example, “Files” -> “Examples” -> “AmebaBLE” -> “BLEHIDMouse”
.
Code Reference
How the mouse input is interpreted is dependent on the host system. Some systems, such as mobile operating systems, may not support all mouse button input functions.
Approximate UDP Receive Delay
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Windows computer connected to same network
Example
This example uses Ameba to receive UDP packets from a computer and calculates the UDP receive delay.
Ameba Preparation
Open the “CalculateUdpReceiveDelay” example in
“File” -> “Examples” -> “AmebaWiFi” -> “UDP_Calculation” -> “CalculateUdpReceiveDelay”
.
In the sample code, modify the highlighted section to enter the information required (ssid, password, key index) to connect to your WiFi network.
Upload the code and press the reset button on Ameba once the upload is finished. Open the serial monitor in Arduino IDE and take note of the IP address assigned to Ameba.
Computer Preparation
On the computer, Cygwin will be required to compile the code to send the UDP packets. Cygwin can be downloaded from https://www.cygwin.com/
Follow the instructions there to install it. Next, from the “CalculateUdpReceiveDelay” Arduino example, copy the code from the bottom between “#if 0” and “#endif”, into a new text file, change the hostname to the IP address assigned to Ameba, and rename the file to “UdpReceiveDelay.cpp”.
Next, open a Cygwin terminal, change the working directory to the location of “UdpReceiveDelay.cpp”, and use the command “g++ UdpReceiveDelay.cpp -o UdpDelay” to compile the code. A file named “UdpDelay.exe” will be created in the same directory.
Running the Example
Reset the Ameba, wait for the WiFi to connect, and check that the IP address remains the same. On the computer, run the UdpDelay.exe file, and the computer will begin to send packets to Ameba. Once 10000 packets have been received, Ameba will calculate the average delay and print out the result to the serial monitor. It may take up to a few minutes for 10000 packets to be sent.
Approximate UDP Receive Timeout
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Windows computer connected to same network
Example
This example uses Ameba to receive UDP packets from a computer and calculates the allowed UDP receive timeout setting.
Ameba Preparation
Open the “CalculateUdpReceiveTimeout” example in
“File” -> “Examples” -> “AmebaWiFi” -> ” UDP_Calculation ” -> “CalculateUdpReceiveTimeout”
.
In the sample code, modify the highlighted section to enter the information required (ssid, password, key index) to connect to your WiFi network.
Upload the code and press the reset button on Ameba once the upload is finished.
Open the serial monitor in Arduino IDE and take note of the IP address assigned to Ameba.
Computer Preparation
On the computer, Cygwin will be required to compile the code to send the UDP packets. Cygwin can be downloaded from https://www.cygwin.com/
Follow the instructions there to install it. Next, from the “CalculateUdpReceiveTimeout” Arduino example, copy the code from the bottom between “#if 0” and “#endif”, into a new text file, change the hostname to the IP address assigned to Ameba, and rename the file to “UdpReceiveTimeout.cpp”.
Next, open a Cygwin terminal, change the working directory to the location of “UdpReceiveTimeout.cpp”, and use the command “g++ UdpReceiveTimeout.cpp -o UdpTimeout” to compile the code. A file named “UdpTimeout.exe” will be created in the same directory.
Running the Example
Reset the Ameba, wait for the WiFi to connect, and check that the IP address remains the same. On the computer, run the UdpTimeout.exe file, and the computer will begin to send packets continuously to Ameba.
The timeout value is set to 1000ms initially. For each packet received successfully, Ameba decreases the timeout value. The next packet must be received within the timeout period, otherwise Ameba registers a failed packet and increases the timeout value. Open the serial monitor and observe the timeout value converge to a minimum value.
Approximate UDP Sending Delay
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Windows computer connected to same network
Example
This example uses Ameba to send UDP packets to a computer and calculates the UDP sending delay.
Ameba Preparation
Open the “CalculateUdpSendDelay” example in “File” -> “Examples” ->
“AmebaWiFi” -> ” UDP_Calculation ” -> “CalculateUdpSendDelay”
.
In the sample code, modify the highlighted section to enter the information required (ssid, password, key index) to connect to your WiFi network.
The server variable also needs to be changed to match the IP address of your computer. You can find the IP address using the “ipconfig” command in a terminal window.
Computer Preparation
On the computer, Cygwin will be required to compile the code to send the UDP packets. Cygwin can be downloaded from https://www.cygwin.com/
Follow the instructions there to install it. Next, from the “CalculateUdpSendDelay” Arduino example, copy the code from the bottom between “#if 0” and “#endif”, into a new text file and rename the file to “UdpSendDelay.cpp”.
Next, open a Cygwin terminal, change the working directory to the location of “UdpSendDelay.cpp”, and use the command “g++ UdpSendDelay.cpp -o UdpDelay” to compile the code. A file named “UdpDelay.exe” will be created in the same directory.
Running the Example
First, on the computer, run the UdpDelay.exe file, and the computer will begin to listen for packets from Ameba.
Next, compile and upload the code from the Arduino IDE to Ameba and press the reset button when the upload is complete.
The Ameba will begin to send UDP packets to the computer. Once 10000 packets have been received, the computer will calculate the average delay and print out the result.
It will take some time for 10000 packets to be sent.
Google Cloud IoT
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Google Cloud IoT Configuration
1. Select or create a Cloud Platform project In the Google Cloud Console, select an existing project or create a new project. You will need a Project ID to use with Ameba.
If creating a new project, enter a project name, and take note of the Project ID generated.
2. Enable billing for your project Billing needs to be enabled for your project to use Google Cloud Platform features. Follow the guide in Google cloud documentation to enable billing. https://cloud.google.com/billing/docs/how-to/modify-project 3. Enable the Cloud IoT Core API In Google Cloud console, click on the top left menu button and search for IoT Core.
Click enable to activate Google Cloud IoT API for your project.
4. Create a Cloud Pub/Sub topic In Google Cloud console, click on the top left menu button and search for Pub/Sub.
Create a new topic for your project and give it a suitable topic ID.
After the topic is created, go to the permissions tab of the info panel, and add “cloud-iot@system.gserviceaccount.com” with the role of “Pub/Sub Publisher”.
5.Create a device registry Go back to the IoT Core settings page and create a new registry.
Choose a suitable Registry ID and in which to store data. Remember the **Registry ID and Regionfor use with Ameba later. For the Pub/Sub topic, select the topic created in the previous step.
6. Create a public/private key pair Using Openssl in a terminal in Windows/Linux/MacOs, run the following commands to generate a private and public key pair. Two files will be created by these commands, “ec_private.pem” containing the private key, and “ec_public.pem” containing the public key.
$ openssl ecparam -genkey -name prime256v1 -noout -out ec_private.pem
$ openssl ec -in ec_private.pem -pubout -out ec_public.pem
Run the next command to extract out the private key, and remember the highlighted string of hexadecimal numbers for use with Ameba later.
$ openssl ec -in ec_private.pem -noout -text
7. Create a device Go back to the IoT Core settings page and create a new device.
Give the device a suitable Device ID and remember it for use with Ameba later.
In the authentication section of the additional options, upload the previously generated “ec_public.pem” public key.
8. Create a Cloud Pub/Sub subscription To observe messages sent by Ameba, create a subscription in Pub/Sub.
Choose a suitable subscription ID and select the previously created topic.
Example
“File” -> “Examples” -> “AmebaMQTTClient” ->
“Google_Cloud_IoT”
.Code Reference
In setup()
, we set up RootCA which is required to form a TLS connection
with Google’s servers.
wifiClient.setRootCA((unsigned char*)rootCABuff);
In loop()
, each loop checks the Internet status and re-connect to it
when the environment has a problem.
if (WiFi.status() != WL_CONNECTED) {
while (WiFi.begin(ssid, pass) != WL_CONNECTED)
{
delay(1000);
}
Serial.println("Connected to wifi");
}
To publish messages, mqtt_id , clientPass and pub_topic are required. mqtt_id is generated by printing the project ID, server location, registry ID and device ID in the required format:
mqtt_id = (char *)malloc(strlen("projects/") + strlen(project_id) + strlen("/locations/us-central1/registries/") + strlen(registry_id) + strlen("/devices/") + strlen(device_id) + 1);
sprintf(mqtt_id, "projects/%s/locations/us-central1/registries/%s/devices/%s", project_id, registry_id, device_id);
clientPass
is generated using a JSON web token (JWT) generator function,
which requires the project ID and current time, and signs it with the
private key:
clientPass = CreateJwt(project_id, timeClient.getEpochTime(), priv_key);
pub_topic
is generated by printing the project ID and topic in the
required format:
pub_topic = (char *)malloc(strlen("/devices/") + strlen(device_id) + strlen("/events") + 1);
sprintf(pub_topic, "/devices/%s/events", device_id);
MQTT Server setting:
client.setServer(GOOGLE_MQTT_SERVER, GOOGLE_MQTT_PORT);
client.setPublishQos(MQTTQOS1);
client.waitForAck(true);
Connect to google cloud and publish messages:
if (client.connect(mqtt_id, clientUser, clientPass.c_str())){
// ...
for(int i = 0; i < count; i++){
// ...
sprintf(payload, "This is Ameba's %d message!!", i);
ret = client.publish(pub_topic, payload);
// ...
}
// ...
client.disconnect();
}
free(mqtt_id);
free(pub_topic);
IPv6 – Ameba as IPv6 Server/Client over TCP
Materials
AmebaD [RTL8722DM/RTL8722CSM/RTL8722DM MINI] / [RTL8720DN(BW16)] x 2
Example
Introduction
This example shows how Ameba can communicate on the local network using Internet Protocol version 6 over TCP. Note that this example only works after you have set up the server and then configure the client accordingly.
Procedure
Step 1. IPv6TCPServer
Open the example, “Files” -> “Examples” -> “AmebaWiFi” -> “IPv6TCPServer”
.
In the sample code, modify the highlighted section to enter the information required (ssid, password) to connect to your WiFi network.
Next, upload the code and press the reset button on Ameba once the upload is finished. Open Serial Monitor and copy the IPv6 address of the Server (the highlighted area) for later use,
Step 2. IPv6TCPClient
Now take the second Ameba D and open another example, “Files” -> “Examples” -> “AmebaWiFi” -> “IPv6TCPClient”
.
In the sample code, modify the highlighted section to enter the information required (ssid, password) to connect to your WiFi network.
From the previous step, we have obtained the Server’s IPv6 address, now we copy the server’s IPv6 address to “IPv6TCPClient” example in the highlighted area below,
IPv6 – Ameba as IPv6 Server/Client over UDP
Materials
AmebaD [RTL8722DM/RTL8722CSM/RTL8722DM MINI] / [RTL8720DN(BW16)] x 2
Example
Introduction
This example shows how Ameba can communicate on the local network using Internet Protocol version 6 over UDP. Note that this example only works after you have set up the server and then configure the client accordingly.
In the sample code, modify the highlighted section to enter the information required (ssid, password) to connect to your WiFi network.
Next, upload the code and press the reset button on Ameba once the upload is finished. Open Serial Monitor and copy the IPv6 address of the Server (the highlighted area) for later use,
Step 2. IPv6UDPClient
Now take the second Ameba D and open another example, “Files” -> “Examples” -> “AmebaWiFi” -> “IPv6UDPClient”
.
In the sample code, modify the highlighted section to enter the information required (ssid, password) to connect to your WiFi network.
From the previous step, we have obtained the Server’s IPv6 address, now we copy the server’s IPv6 address to “IPv6UDPClient” example in the highlighted area below,
使用元件
溫濕度傳感器
|
距離測量的功能
|
使用 SPI 接口的 TFT LCD 顯示屏
|
|
QVGA TFT LCD 顯示器模組
|
高質量 GPS 定位模組
|
高輸出功率的伺服電機
|
Peripheral Examples
GPIO - Measure The Distance By Ultrasound Module
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
HC-SR04 Ultrasonic x 1
Dropping resistor or Level converter
Example
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Next, open the sample code in “File” -> “Examples” -> “AmebaGPIO” -> “HCSR04_Ultrasonic”
Compile and upload to Ameba, then press the reset button. Open the Serial Monitor, the calculated result is output to serial monitor every 2 seconds.
Note that the HCSR04 module uses the reflection of sound wave to calculate the distance, thus the result can be affected by the surface material of the object (e.g., harsh surface tends to cause scattering of sound wave, and soft surface may cause the sound wave to be absorbed).
Code Reference
Before the measurement starts, we need to pull high the TRIG pin for 10us and then pull low. By doing this, we are telling the HC-SR04 that we are about to start the measurement:
digitalWrite(trigger_pin, HIGH);
delayMicroseconds(10);
digitalWrite(trigger_pin, LOW);
Next, use pulseIn to measure the time when the ECHO pin is pulled high.
duration = pulseIn (echo_pin, HIGH);
Finally, use the formula to calculate the distance.
distance = duration / 58;
GPIO - Measuring The Temperature And Humidity
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
DHT11 or DHT22 or DHT21
Example
Since one of the 4 pins has no function, there are temperature/humidity sensors with only 3 pins on the market:
DHT is normally in the sleeping mode. To get the temperature/humidity data, please follow the steps:
Awake DHT: Ameba toggles low its DATA pin of GPIO. Now the DATA pin of GPIO serves as digital out to Ameba.
DHT response: DHT also toggle low its DATA pin of GPIO. Now the DATA pin of GPIO serves as digital in for Ameba.
DHT sends data: DHT sends out the temperature/humidity data (which has size 5 bytes) in a bit by bit manner. To represent each bit, DHT first pull low the DATA GPIO pin for a while and then pull high. If the duration of high is smaller than low, it stands for bit 0. Otherwise it stands for bit 1.
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Open the sample code in “Files” -> “Examples” -> “AmebaGPIO” ->
“DHT_Tester”
. Compile and upload to Ameba, then press the reset button.
The result would be shown on the Serial Monitor.
Code Reference
Use dht.readHumidity()
read the humidity value, and
use dht.readTemperature()
to read the temperature value.
Every time we read the temperature/humidity data, Ameba uses the buffered temperature/humidity data unless it found the data has expired (i.e., has not been updated for over 2 seconds). If the data is expired, Ameba issues a request to DHT to read the latest data.
GPIO - Use GPIO Interrupt To Control LED
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
LED x 1
Button x 1
Example
In this example, we use a button to trigger interrupt and control the LED. When we press and release the button, the LED dims, press and release the button again, and the LED lights.Note that in the Arduino example “Button and LED”, LED only lights when the button is pressed and hold, when we release the button, the LED dims.
Open the example, “Files” -> “Examples” -> “AmebaGPIO” ->
“LED_InterruptCtrl”
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Code Reference
In
setup()
we set Pin 12 to
INPUT_IRQ_RISE
, this means that an interrupt occurs when the voltage of this pin changes from GND to 3V3. Therefore, we connect the other side of the button to 3V3, so as to trigger interrupt event when the button is pressed.
pinMode(button, INPUT_IRQ_RISE);
On the other hand, we can set pin 12 to
INPUT_IRQ_FALL
, this means that an interrupt occurs when the voltage of this pin changes from 3V3 to GND. In this case, the other side of the button is connected to GND.Next, we need to specify the funtion to be execute to handle the interrupt:
digitalSetIrqHandler(button, button_handler);
The second parameter is a function pointer, with prototype:
void button_handler(uint32_t id, uint32_t event)
In this handler, every time we press and release the button, we trigger an interrupt, and change the status of the LED.
PWM – Play Music
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Buzzer x 1
Example
A sound is composed of volume, tone and timbre. Volume is determined by the amplitude of the sound wave. Tone is determined by the frequency of the sound wave. Timbre is determined by the waveform of the sound wave.
In this example, we use PWM to control the buzzer to emit sound with desired tone. As PWM outputs square wave, if we wish to emit tone C4 (frequency=262Hz), we have to make PWM to output square wave with wavelength 1/262 = 3.8ms:
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
“Examples” -> “AmebaAnalog” -> “TonePlayMelody”
Code Reference
In the sample code, we initiate a melody array, which stores the tones to make. Another array, noteDurations, contains the length of each tone, 4 represents quarter note (equals to 3000ms/4 = 750ms, and plus an extra 30% time pause), 8 represents eighth note.
PWM – Using A Servo
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Servo x 1 (Ex. Tower Pro SG90)
Example
A typical servo has 3 wires, the red wire is for power, black or brown one should be connected to GND, and the other one is for signal data. We use PWM signal to control the rotation angle of the axis of the servo. The frequency of the signal is 50Hz, that is length 20ms. Each servo defines its pulse bandwidth, which is usually 1ms~2ms.
To control the rotation angle, for example if 1ms-length pulse rotates the axis to degree 0, then 1.5 ms pulse rotates the axis to 90 degrees, and 2 ms pulse rotates the axis to 180 degrees. Furthermore, a servo defines the “dead bandwidth”, which stands for the required minimum difference of the length of two consecutive pulse for the servo to work.
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
“File” -> “Examples” -> “AmebaAnalog” ->
“ServoSweep”
Code Reference
The Servo API of Ameba is similar to the API of Arduino. To distinguish from the original API of Arduino, we name the header file “AmebaServo.h” and the Class “AmebaServo”, the usage is identical to the Arduino API.
The default pulse bandwidth of Arduino Servo is 0.5ms~2.4ms, which is the same as Tower Pro SG90. Therefore, we set the attached pin directly:
myservo.attach(9);
Next, rotate the axis to desired position:
myservo.write(pos);
I2C - Communicate with Arduino UNO via I2C
Introduction of I2C
There are two roles in the operation of I2C, one is “master”, the other is “slave”. Only one master is allowed and can be connected to many slaves. Each slave has its unique address, which is used in the communication between master and the slave. I2C uses two pins, one is for data transmission (SDA), the other is for the clock (SCL). Master uses the SCL to inform slave of the upcoming data transmission, and the data is transmitted through SDA. The I2C example was named “Wire” in the Arduino example.
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Arduino UNO x 1
Example
Setting up Arduino Uno to be I2C Slave
“Tools” -> “Board” -> “Arduino Uno”
“Examples” -> “Wire” -> “slave_receiver”
:Then click “Sketch” -> “Upload”
to compile and upload the example to Arduino Uno.
Setting up Ameba to be I2C Master
“Tools” -> “Board”
“File” -> “Examples” ->
“AmebaWire” -> “MasterWriter”
Wiring
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Code Reference
I2C - Display Data On LCD Screen
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
I2C 2×16 LCD
Example
“File” -> “Examples” -> “AmebaWire” -> “LCD_HelloWorld”
.After 8 seconds, you can input to the Serial Monitor the string you would like to display on the LCD.
For example, we enter “123456789” and press “Send”:
Code Reference
The required settings of each model of LCD might be different, the constructor we use in this example is:
LiquidCrystal_I2C(uint8_t lcd_Addr, uint8_t En, uint8_t Rw, uint8_t Rs,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7,
uint8_t backlighPin, t_backlighPol pol);
And the setting parameters are as follows:
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address
The first parameter 0x27 is the address of I2C. Each of the following 8 parameters represents the meaning of each bit in a byte, i.e., En is bit 2, Rw is bit 1, Rs is bit 0, d4 is bit 4, and so forth.
backlight()
to light the screen,setCursor(0, 0)
to set the position of the cursor.lcd.print()
to output string on the screen.I2C - Use I2C to receive data from Arduino UNO
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Arduino UNO x 1
Example
Setting up Arduino Uno to be I2C Slave
“Tools” -> “Board” ->
“Arduino Uno”
:“Examples” -> “Wire” -> “slave_sender”
Then click “Sketch” -> “Upload” to compile and upload the example to Arduino Uno.
Setting up Ameba to be I2C Master
“File” -> “Examples” -> “AmebaWire” -> “MasterReader”
Wiring
Code Reference
Wire.begin()
/ Wire.begin(address)
to join the I2C bus as a
master or slave, in the Master case the address is not required.Wire.requestFrom()
to specify from which Slave
to request data.UART - Communicate with the computer via UART
Introduction of UART
UART uses two wire, one for transmitting and the other one for receiving, so the data transmission is bidirectional. The communication uses a predefined frequency (baud rate) to transmit data. In Arduino, UART is called “Serial”. There is only one hardware UART on Arduino Uno and it is primarily used to read the log and messages printed by Arduino (so it is also called “Log UART”). If we use the hardware UART for other purposes, the Log UART does not have resources to function. To provide more UART connections, it is possible to use a GPIO pin to simulate the behavior of UART with a software approach, this is called Software Serial. Ameba is equipped with several hardware UART ports, but it is also compatible with the Software Serial library.
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
USB to TTL Adapter x 1
Example
Install USB to TTL Adapter
Executing the Example
“File” -> “Examples” ->
“AmebaSoftwareSerial” -> “SoftwareSerial_Basic”
:Next, open a serial port terminal, such as Putty or Tera Term. (Putty is used in this example). Open the Putty window, choose “Serial” in connection type, and specify the port number of the USB to TTL adapter (e.g. COM8). In the speed field, fill in the baud rate of this connection. Note that both sides of the connection should use the same baud rate. In this example we set baud rate 4800.
Next, select “Serial” on the left side. Set data bits to 8, stop bits to 1, parity to none, and flow control to none.
Then click Open and press the reset button on Ameba. You can see the “Hello, world?” message appears in Putty. If characters are typed into Putty, the input characters would be sent to Serial RX of Ameba by TX of USB to TTL Adapter, and returned by Serial TX of Ameba. Finally, RX of USB to TTL Adapter receives the returned characters and prints them in Putty. Therefore, if you insert “I am fine”, you will get something like this:
Code Reference
SoftwareSerial:begin(speed)
to set the baud rate for the
serial communication:write()
to send data, and use SoftwareSerial:available()
to get the
number of bytes available for reading from a software serial port:UART - Retrieve GPS Position
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Adafruit Ultimate GPS Breakout x 1 (Refer to official document)
Example
In this example, we use Adafruit Ultimate GPS Breakout. Its data format
is pure text, so we can connect it to USB to TTL Adapter and observe the
output.
It follows the NMEA sentence format (refer to http://aprs.gids.nl/nmea/)
The GPS signal is weak in indoor environment.
The status that the GPS signal is not received is called “not fix”.
Bring the GPS module outdoors, when the GPS signal is “fix”,
you would get message similar to the figure below.
First field is the GMT time (Greenwich Mean Time), that is 032122.000 in this example. The time format is HH:MM:SS.SSS, i.e., 03:21:22.000. Note that the time zone and the daylight-saving time adjustment should be handled on your own.
Second field represents the status code
V: Void (Invalid)
A: Active, meaning the GPS signal is fix.
The third to sixth fields represent the geolocation
In this example, 2446.8181,N represents 24 degrees 46.8181 minutes north latitude, and 12059.7251,E represents 120 degrees 59.7251 minutes east longitude.
We can search +24 46.8181’, +120 59.7251’ in Google map
to check whether the position is correct.
The seventh field is relative speed(knot). 1 knot = 1.852km/hr, in this example the relative speed is 0.39 knot.
The eighth field is the moving angle, which is calculated by its moving orbit.
The ninth field is the date with format ddMMyy. In this example, “270116” stands for day 27, January, year 2016.
The last field is checksum. In the example we have *53 as checksum.
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Open the example in “Files” -> “Examples” ->
“AmebaSoftwareSerial” -> “Adafruit_GPS_parsing”
.
UART – Set Callback Function For UART Communications
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
USB to TTL Adapter x 1
Example
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Open the example in “File” -> “Examples” -> “AmebaSoftwareSerial” ->
“SoftwareSerial_Irq_Callback”
Once the serial port is open, type in the terminal and press the enter key, and you will see the corresponding output.
Code Reference
mySerial.setAvailableCallback(mySerialCallback);
is used to set the
function mySerialCallback as a callback function for software serial.
When a new character is received, the callback function checks if the
character corresponds to the enter key, and releases the semaphore if it
is true, which in turn allows the main loop to print out all the
previously received characters.
PM2.5 Concentration in The Air
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
PlanTower PMS3003 or PMS5003 x 1
Example
PMS3003 (or PMS5003) is a sensor of air quality, it can detect the concentration of those 0.3 to 10 micrometer particulate matters in the air. The sensor output its data via UART.
The PMS3003 (or PMS5003) sensor detects the concentration value of PM 1.0, PM 2.5, PM 10. Take PM 2.5 for example, it stands for the fine particles with a diameter of 2.5 micrometers or less.
Open the example in “File” -> “Examples” -> “AmebaSoftwareSerial” -> “PMS3003_AirQuality”
There are 8 pins in PMS3003:
PMS3003 requires 5V power, but the working voltage of its IC is 3.3C. Therefore, the working voltage of Reset, TX, RX, Set are 3.3 as well. If the “Set” pin is pulled to high, the PMS3003 is put to operating mode. If the “Set” pin is pulled low, the PMS3003 is put to standby mode.
TX/RX pins are for UART connection. Under operating mode, PMS3003 output the data it reads continuously. Each data is of 32 byte, please refer to the following article for detailed data format information:
https://www.dfrobot.com/wiki/index.php?title=PM2.5_laser_dust_sensor_SKU:SEN0177 RTL8722
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
In this example, we do not use the “Set” and “Reset” pins.
Compile the code and upload it to Ameba. After pressing the Reset button, Ameba starts to output the PM 2.5 data to serial monitor.
Flash Memory - Store data in FlashEEProm
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
Code Reference
By default, the Flash Memory API uses address 0xFF000~0xFFFFF to store data.
There is limitation when writing to flash memory. That is, you can not directly write data to the same address you used in last write. To do that correctly, you need erase the sector first. The Flash API of Ameba uses a 4K SRAM to record the user modification and do the erase/write task together.
FlashMemory.read()
to read from Flash memory.FlashMemory.buf[0] = 0x00;
to manipulate the 4K buf.FlashMemory.update();
to update the data in buf to Flash Memory.Flash Memory - Use Flash Memory Larger Than 4K
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” ->
“AmebaFlashMemory” -> “ReadWriteOneWord”
Code Reference
We can use the flash api we used in previous flash memory example, but
we need to use begin()
function to specify the desired starting address
and memory size.
FlashMemory.begin(0xFC000, 0x4000);
Use readWord()
to read the value stored in a memory address. In the
example, we read the value stored in memory offset 0x3F00, that is
0xFC000 + 0x3F00 = 0xFFF00. readWord()
function reads a 32-bit value and
returns it.
value = FlashMemory.readWord(0x3F00);
Use writeWord()
to write to a memory address. The first argument is the
memory offset, the second argument is the value to write to memory.
FlashMemory.writeWord(0x3F0C, value);
SPI – Print Image And Text On LCD Screen
If you are not familiar with SPI, please read Introduction to SPI first.
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
ILI9341 TFT LCD with SPI interface x 1
Example
We have tested the following two models of ILI9341 TFT LCD with SPI interface:
Adafruit 2.8″ TFT LCD (with touch screen)
QVGA 2.2″ TFT LCD
Common pins in ILI9341 TFT LCD with SPI interface:
MOSI: Standard SPI Pin
MISO: Standard SPI Pin
SLK: Standard SPI Pin
CS: Standard SPI Pin
RESET: Used to reboot LCD.
D/C: Data/Command. When it is at Low, the signal transmitted are commands, otherwise the data transmitted are data.
LED (or BL): Adapt the screen backlight. Can be controlled by PWM or connected to VCC for 100% backlight.
VCC: Connected to 3V or 5V, depends on its spec.
GND: Connected to GND.
RTL8722DM / RTL8722CSM and QVGA TFT LCD Wiring Diagram:
RTL8722DM MINI and QVGA TFT LCD Wiring Diagram:
RTL8722DM / RTL8722CSM and Adafruit 2.8』』 TFT LCD touch shield Wiring Diagram:
RTL8722DM MINI and Adafruit 2.8』』 TFT LCD touch shield Wiring Diagram:
Open the example, “Files” -> “Examples” -> “AmebaSPI” -> “ILI9341_TFT_LCD_basic”
Code Reference
RGB 16-bit
ILI9341 uses RGB 16-bit to display colors. Different from RGB 24-bit, it uses 5 bits for red, 6 bits for green, 5 bits for blue. For example, the RGB 24-bit representation of sky blue is 0x87CEFF, that is in binary:
Red: 0x87 = B10000111
Green: 0xCE = B11001110
Blue: 0xFF = B11111111
and converted to RGB 16-bit:
Red: B10000
Green: B110011
Blue: B11111
Then concatenate them, which forms B1000011001111111 = 0x867F
Drawing of ILI9341
First you must specify the range of the rectangle to draw, then pass the 2-byte RGB 16-bit color to ILI9341 corresponding to each pixel one by one, in this way ILI9341 fills each color to each pixel.
You still must specify the drawing range even though the range covers only one pixel.
From the rules we mentioned above, we can conclude that drawing vertical or horizontal lines are faster than diagonal lines.
Printing text on ILI9341
In our API, each character is 5×7 but each character is printed to size 6×8 (its right side and below are left blank), so as to separate from next character. For example, the character “A”:
The font size represents the dot size. For example, if the font size is 2, each dot in the character is a 2×2 rectangle
Screen rotation
ILI9341 provides 0, 90, 180, 270 degrees screen rotation.
If the original width is 240 and original height is 320, when the screen rotates 90 degrees, the width becomes 320 and the height becomes 240.
SPI – Show PM2.5 Concentration On ILI9341 TFT LCD
If you are not familiar with SPI, please read Introduction to SPI first.
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
ILI9341 TFT LCD with SPI interface x 1
Plantower PMS3003 or PMS5003 x 1
Example
Open the example, “Files” -> “Examples” -> “AmebaSPI” -> “PM25_on_ILI9341_TFT_LCD”
Compile and upload to Ameba, then press the reset button.
Then you can see the concentration value of PM1.0, PM2.5 and PM10 on the LCD.
Code Reference
In this example, first rotate the screen by 90 degrees, and draw the static components such as the circles, the measuring scale, and the title text. After the concentration value is detected, it is printed inside the circle.
Timer - Using The Periodic GTimer
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] / [RTL8720DN(BW16)] x 1
Example
“File” -> “Examples” -> “AmebaGTimer” -> “TimerPeriodical”
. Compile and upload to Ameba, and press reset.Code Reference
GTimer.begin(0, 1 * 1000 * 1000, myhandler);
The GTimer is periodic by default, therefore “myhandler” function is
called every second. When we want to stop the GTimer, use stop()
:
GTimer.stop(0);
Timer - Using The Single-Use GTimer
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] / [RTL8720DN(BW16)] x 1
Example
In this example, we will use 4 One-Time GTimer, and pass user data to each timer.
Open the example “File” -> “Examples” -> “AmebaGTimer” -> “TimerOneshot”
.
Compile and upload to Ameba, and press reset.
Then you can see the 4 timer log printed to the serial monitor in series.
Code Reference
The first argument of begin() is the Timer ID (0~3). The second argument is the value of the timer (in microseconds). In the example, we fill in 1000000us = 1s. The third argument specifies the function to call when the time is up. The fourth argument is to set whether this timer is a periodic timer, we use “false” here to begin a single-use timer. The fifth argument is the user data, we give 0 here to represent that this is timer 0.
GTimer.begin(0, 1 * 1000 * 1000, myhandler, false, 0);
Next, we set up the second timer, which has timer value 2 seconds, and user data 1. And other timers are set similarly.
GTimer.begin(1, 2 * 1000 * 1000, myhandler, false, 1);
In myhandler function, we print the user data to serial monitor. Since the 4 timers are separately set to count for 1, 2, 3, 4 seconds, from 1 second to 4 second, the user data of each timer are printed on the serial monitor in order. After 4 second, no log will be printed.
Power Save Deep Sleep Mode
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
Introduction
Ameba-D supports two low power modes which are deepsleep mode and sleep mode. Deepsleep mode turns off more power domain than sleep mode. The power consumptions of DeepSleep Mode is around 7uA to 8uA compare to normal state around 22mA. This example describes how to enter deepsleep mode and configure wakeup source.
“File” -> “Examples” -> “AmebaPowerSave” -> “DeepSleepMode”
DS_WAKEUP_SOURCE
is used to set the wake-up source, user can chose 3
wake up sources now,AON timer (SET_DS_AON_TIMER_WAKEUP);
AON pins (SET_DS_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON timer can be set from 0 to 32760000 range (unit ms) by
AON_TIMER_SLEEP_DURATION
There are 4 pins can be set as AON pins and active high for wake-up,
D16, D17, D26 and D27. The AON pin can be set by
SET_DS_AON_WAKEPIN_WAKEUPPIN
RTC timer wake-up system by set alarm. The alarm has 4 values, day,
hour, min and sec. All 4 values can be set by DS_RTC_ALARM_DAY
,
DS_RTC_ALARM_HOUR
, DS_RTC_ALARM_MIN
, and DS_RTC_ALARM_SEC
When finished the condition values setting, system will run and switch between normal and deepsleep mode controlled by wakeup source. Serial Monitor displays the switching log.
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
Power Save Deep Sleep DHT Eink
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
DHT11 or DHT22 or DHT21 x 1
LCD I2C screen x 1
Example
“File” -> “Examples” -> “AmebaPowerSave” ->
“DeepSleep_DHT_Eink_Example”
DS_WAKEUP_SOURCE
is used to set the wake-up source, user can chose 3
wake up sources now,AON timer (SET_DS_AON_TIMER_WAKEUP);
AON pins (SET_DS_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON timer can be set from 0 to 32760000 range (unit ms) by
AON_TIMER_SLEEP_DURATION
There are 4 pins can be set as AON pins and active high for wake-up,
D16, D17, D26 and D27. The AON pin can be set by
SET_DS_AON_WAKEPIN_WAKEUPPIN
RTC timer wake-up system by set alarm. The alarm has 4 values, day,
hour, min and sec. All 4 values can be set by DS_RTC_ALARM_DAY
,
DS_RTC_ALARM_HOUR
, DS_RTC_ALARM_MIN
, and DS_RTC_ALARM_SEC
DHTPIN
is used to set DHT sensor data pin. User can choose any GPIO
pins.DHTTYPE
is used to set DHT sensor type. (DHT11, DHT22 and DHT33)When finished the condition values setting, system will run and switch between normal working mode and deepsleep mode controlled by wakeup source. Eink screen will display the temperature and humidity data measured from DHT sensor when system is awake.
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
Power Save Deep Sleep DHT LCD
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
DHT11 or DHT22 or DHT21 x 1
LCD I2C screen x 1
Example
Introduction
Ameba-D supports low power modes which are deepsleep mode. Deepsleep mode turns off most of the system power domain. The power consumptions of core module in DeepSleep Mode is around 7uA to 8uA compare to normal state around 22mA. This example gives demo of system switch between “working” and “sleep”(power save).Using DHT sensor to read data and display on LCD screen when system is awake. After 5 seconds system auto enter DeepSleep Mode for power save. System will wake up by wakeup source.( Aon timer, Aon Pins or RTC timer).
“File” -> “Examples” -> “AmebaPowerSave” ->
“DeepSleep_DHT_LCD_Example”
DS_WAKEUP_SOURCE
is used to set the wake-up source, user can chose 3
wake up sources now,AON timer (SET_DS_AON_TIMER_WAKEUP);
AON pins (SET_DS_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON timer can be set from 0 to 32760000 range (unit ms) by
AON_TIMER_SLEEP_DURATION
There are 4 pins can be set as AON pins and active high for wake-up,
D16, D17, D26 and D27. The AON pin can be set by
SET_DS_AON_WAKEPIN_WAKEUPPIN
RTC timer wake-up system by set alarm. The alarm has 4 values, day,
hour, min and sec. All 4 values can be set by DS_RTC_ALARM_DAY
,
DS_RTC_ALARM_HOUR
, DS_RTC_ALARM_MIN
, and DS_RTC_ALARM_SEC
DHTPIN
is used to set DHT sensor data pin. User can choose any GPIO
pins.DHTTYPE
is used to set DHT sensor type. (DHT11, DHT22 and DHT33)When finished the condition values setting, system will run and switch between normal working mode and deepsleep mode controlled by wakeup source. LCD screen will display the temperature and humidity data measured from DHT sensor when system is awake.
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
Power Save Tickless Mode
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
Introduction
Ameba-D supports two low power modes which are deepsleep mode and sleep mode. The power consumptions of Tickless Sleep Mode is around 28uA to 30uA compare to normal state around 15mA. This example describes how to use freertos tickless with uart interruptable interface.
“File” -> “Examples” -> “AmebaPowerSave” -> “TicklessMode”
DS_WAKEUP_SOURCE
is used to set the wake-up source, user can chose 3
wake up sources now,AON timer (SET_DS_AON_TIMER_WAKEUP);
AON pins (SET_DS_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON timer can be set from 0 to 32760000 range (unit ms) by
AON_TIMER_SLEEP_DURATION
There are 4 pins can be set as AON pins and active high for wake-up,
D16, D17, D26 and D27. The AON pin can be set by
SET_DS_AON_WAKEPIN_WAKEUPPIN
RTC timer wake-up system by set alarm. The alarm has 4 values, day,
hour, min and sec. All 4 values can be set by DS_RTC_ALARM_DAY
,
DS_RTC_ALARM_HOUR
, DS_RTC_ALARM_MIN
, and DS_RTC_ALARM_SEC
There are 4 pins can be set as AON pins and active high for wake-up,
D16, D17, D26 and D27. The AON pin can be set by
SET_TL_AON_WAKEPIN_WAKEUP
TL_SYSACTIVE_TIME
is for setting time duration of the system to keep
alive. (unit ms)
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
Use NTPClient Library To Obtain Local Time
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
In this example, we use an NTP client to sync with NTP
servers using UDP and keep track of time locally.
Open the example.
“File” -> “Examples”-> “NTPClient” -> “Advanced”
Code Reference
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000);
begin()
function, which causes the client to sync with the NTP
server and get the UTC time.WiFiUDP ntpUDP;
timeClient.begin();
getFormattedTime()
is used to format the received UTC
time into the local time zone. update()
is called every loop so that the
NTPClient will sync with the NTP server once every update interval.timeClient.update();
timeClient.getFormattedTime();
Transmit IR NEC Raw Data And Decode
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 2
Grove – Infrared Emitter x1 (Figure 1)
Grove – Infrared Receiver x1 (Figure 2)
Example
In this example, we use two Ameba RTL8722 modules that connecting with an infrared (IR) Emitter and an IR Receiver separately to transmit and receive IR NEC Raw data.
For more details, please refer to SB-Projects’ topic of IR Remote Control Theory to learn the theory of IR remote controls operation and a collection of IR protocol descriptions. In this example, we are going to use NEC (Now Renesas, also known as Japanese Format) as the transmission protocol.
8-bit address and 8-bit command length.
Extended mode available, doubling the address size.
Address and command are transmitted twice for reliability.
Pulse distance modulation.
The carrier frequency of 38kHz.
Bit time of 1.125ms or 2.25ms.
Since a total number of 32-bit data together with the header and the end-bit will be transferred (Figure 5). If we separate the data in the time-frame (in us), there will be ( 2 + 32 ) x 2 + 1 = 69 “marks” / “spaces” to be transmitted (Figure 6), which forms the raw NEC data we would like to transmit in our Arduino “*.ino” file. This part of the code can be modified by users. Details of how to obtain raw data code for your remote devices, you may refer to Ken Shirriff’s blog, where it provides multiple libraries provided online.
Figure 7 and 8 shows the pin configuration of IR Emitter and Receiver with Ameba RTL8722 board.
Figure 9 and Figure 10 shows the pin configuration of IR Emitter and Receiver with Ameba RTL8722DM MINI.
After the connection is being set up correctly, we will move to the coding part for this example. First, make sure the correct Ameba development board is selected in Arduino IDE: “Tools” -> “Board”.
Open the “IRSendRAW” example in “File” -> “Examples” -> “AmebaIRDevice”
-> “IRSendRAW”
(Figure 11) and upload to 1st board connected with IR
Emitter:
After successfully upload the sample code for IRSendRaw, you might need
to upload the IRRecvNEC example for the 2nd board connected with IR
Receiver from “File” -> “Examples” -> “AmebaIRDevice” -> “IRRecvNEC”
.
After opening the serial monitor on the IR Receiver side and press the reset buttons on two boards, the data “48” will be received every 3 seconds (due to the delays () function, not compulsory to wait). After decoding the signal from the receiving Pin D8 and transmitting Pin D9 with Logic Analyser and Pulse View (Figure 10), the result is also shown as “48” after decoding the receiving data with IR NEC Protocol.
Code Reference
E-Paper - Display Images
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
Front view of the e-Paper Module:
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
RTL8720DN(BW16) Wiring Diagram:
Firstly, you need to prepare a picture/photo in the format of 296×128 pixels. We can easily find a photo resizing tool online, for example, the Online Image Resizer.
Following the instructions on the website, then download the generated image in JPG format.
Secondly, we use the Image2LCD tool to transfer the downloaded 296×128 image into hexadecimal codes. You can visit this YouTube link to get detailed instructions.
“File” → “Examples” → “AmebaEink” → “EinkDisplayImage”
:Code Reference
E-Paper - Display Text
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
Front view of the e-Paper Module:
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
RTL8720DN(BW16) Wiring Diagram:
“File” -> “Examples” -> “AmebaEink” -> “EinkDisplayText”
:Upload the code to the board and press the Reset button after the uploading is done. You will find these texts displayed on the board:
Code Reference
[1] We use Good Display GDEH029A1 2.9 Inch / 296×128 Resolution / Partial Refresh Arduino Sample Code to get the e-Paper successfully Display: http://www.good-display.com/product/201.html
E-Paper - Display User-generated QR Code
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
Front view of the e-Paper Module:
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
RTL8720DN(BW16) Wiring Diagram:
Modify the URL in the loop() section as your wish, after that, verify and upload the code to the Ameba board. Upon successfully upload the sample code and press the reset button, a QR code generated based on the URL of your input will be shown on the E-Paper module. The QR code showing below leads to our Ameba IoT official website: Ameba ARDUINO
Code Reference
A Simple RTC Example
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
This example demonstrates how to use the RTC library methods. This function describes how to use the RTC API. The RTC function is implemented by an independent BCD timer/counter.
"File" -> "Examples" -> "AmebaRTC" -> "RTC"
:Upon successfully upload the sample code and press the reset button, this example will print out time information since the user initialized time every second in the Serial Monitor.
Code Reference
A Simple RTC Alarm
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
This example demonstrates how to use the RTC library methods to create a RTC Alarm, so that to do some tasks when an alarm is matched. In particular, the RTC time is set at 16:00:00 and an alarm at 16:00:10. When the time matches, “Alarm Match” information will be printed on the serial monitor.
First, select the correct Ameba development board from the Arduino IDE: “Tools” -> “Board”.
Then open the 「RTCAlarm」 example from:
“File” -> “Examples” -> “RTC” -> “RTCAlarm”
:
In the example, the RTC time is set at 16:00:00 and an alarm is set at 16:00:10. Upon successfully upload the sample code and press the reset button. When the alarm time (10 seconds) is reached the attached interrupt function will print the following information: “Alarm Matched!” showing in this figure below.
Watchdog Timer Simple Example
Preparation
AmebaD RTL8722CSM/RTL8722DM/RTL8722DM MINI Board x 1
Example
In this example, we will use this simple watchdog timer example runs on the Ameba RTL8722 module to illustrate how to use the watchdog API. Before we get into the details of the example, let’s briefly go through the definition of Watchdog as well as it’s working principles.
Watchdog
Watchdog Timer (WDT) is a hardware timer that is used to detect the occurrence of a software fault, then automatically generates a system reset or a watchdog interrupt on the expiry of a programmed period.
In layman terms, imagine in the situation while your micro-controller is confused in an infinity loop, or any case like the micro-controller hang while performing some tasks. The normal troubleshooting method would be to press the reset button and jump out of the infinity loop. However, is it practically impossible to do press on the button all time, therefore, the watchdog timer that embedded inside the micro-controller would help with this situation.
Feed the Dog
“Tools” -> “Board” -> “RTL8722CSM/RTL8722DM” (or “RTL8722DM MINI”)
.
Then open the “Watchdog Timer” example in “File” -> “Examples” -> “AmebaWatchdog” ->
“Watchdog Timer”
:Audio Codec – Basic Input Output
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Potentiometer x 1
Analog microphone x 1 (e.g., Adafruit 1063 / 1064)
3.5mm TRS/TRRS breakout x 1 (e.g., Adafruit 2791 / Sparkfun 11570)
Example
Open the example, "Files" -> "Examples" -> “AmebaAudioCodec” ->
“BasicInputOutput”
.
Upload the code and press the reset button on Ameba once the upload is finished.
Connect a pair of wired headphones to the 3.5mm audio jack, blow at the microphone, and you should hear the sounds picked-up by the microphone replayed in the headphones. Adjust the potentiometer and the output volume will change as well. Note: if you are using a microphone with an amplifier included, such as Adafruit 1063, the amplifier can lead to the microphone picking up more noise.
Audio Codec - FFT
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
"Files" -> "Examples" -> “AmebaAudioCodec” -> “FFT”
.Audio Codec - Input FFT
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Analog microphone x 1 (e.g., Adafruit 1063 / 1064)
Example
Next, open the example, "Files" -> "Examples" -> “AmebaAudioCodec” ->
“InputFFT”
.
Audio Codec – Output Sine Wave
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
3.5mm TRS/TRRS breakout x 1 (e.g., Adafruit 2791 / Sparkfun 11570)
Example
Procedure
Open the example, "Files" -> "Examples" -> “AmebaAudioCodec” ->
“OutputSineWave”
.
TensorFlow Lite - Hello World
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
LED x 1
Example
Procedure
Download the Ameba customized version of TensorFlow Lite for Microcontrollers library at https://github.com/ambiot/ambd_arduino/tree/master/Arduino_zip_libraries. Follow the instructions at https://www.arduino.cc/en/guide/libraries to install it. Ensure that the patch files found at https://github.com/ambiot/ambd_arduino/tree/master/Ameba_misc/ are also installed.
Open the example, "Files" -> "Examples" -> “TensorFlowLite_Ameba” ->
“hello_world”
.
Code Reference
More information on TensorFlow Lite for Microcontrollers can be found at: https://www.tensorflow.org/lite/microcontrollers
TensorFlow Lite - Magic Wand
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Adafruit LSM9DS1 accelerometer
LED x 2
Example
Procedure
"Files" -> "Examples" -> “TensorFlowLite_Ameba” ->
“magic_wand”
.Code Reference
More information on TensorFlow Lite for Microcontrollers can be found at: https://www.tensorflow.org/lite/microcontrollers
TensorFlow Lite - Micro Speech
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Adafruit PDM MEMS microphone
LED x 4
Example
Procedure
"Files" -> "Examples" -> “TensorFlowLite_Ameba” ->
“micro_speech”
.If you are having trouble in getting the words recognized, here are some tips:
Ensure that your surroundings are quiet with minimal noise.
Experiment with varying the distance of the microphone, starting with it at an arm’s length.
Experiment with different tones and volume when saying the words.
Depending on how you pronounce the words, the characteristics of the microphone used, getting one keyword recognized may be easier than the other.
Code Reference
More information on TensorFlow Lite for Microcontrollers can be found at: https://www.tensorflow.org/lite/microcontrollers
TensorFlow Lite - Person Detection
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Arducam Mini 2MP Plus OV2640 SPI Camera Module x 1
LED x 3
Example
Procedure
Arduino/libraries/JPEGDecoder/src/User_Config.h
#define LOAD_SD_LIBRARY
and #define
LOAD_SDFAT_LIBRARY
are commented out, as shown in this excerpt from the
file://#define LOAD_SD_LIBRARY // Default SD Card library
//#define LOAD_SDFAT_LIBRARY // Use SdFat library instead, so SD Card SPI can be bit bashed
Open the example, "Files" -> "Examples" -> “TensorFlowLite_Ameba” ->
“person_detection”
.
Code Reference
More information on TensorFlow Lite for Microcontrollers can be found at: https://www.tensorflow.org/lite/microcontrollers
AmebaMotors - Use Ameba as Server to Control Motors
Introduction to AmebaMotors
AmebaMotors is a library which provides API related to controlling motors. Please download the library: AmebaMotors And add the library to Ameba: https://www.arduino.cc/en/Guide/Libraries#toc4
Materials
Ameba D [RTL8722DM / RTL8722CSM ] x 1
L298N H-Bridge x 1
4-wheel motorcar or 2-wheel motorcar+Universal wheel
Example
Procedure
“Files” -> “Examples” -> “AmebaWiFi” -> “WiFiControlCar”
.
ENA
IN1
IN2
IN3
IN4
ENB
8
9
10
11
12
13
備註
We connect Ameba 5V to L298N +12V to supply power. However, not every L298N accepts 5V power supply, if this does not work, please connect L298N +12V to other power supply (e.g., +12V) and use L298N +5V to supply power to Ameba.
The correct wiring of the motor depends on each model (may be opposite). Please run the test program first, make sure it runs correctly before assembling the motorcar.
For convenience purposes, it’s recommended to use Dupont line to organize the wiring of motors and L298N.
Demo Video
Code Reference
Use WiFi.begin()
to establish WiFi connection.
https://www.arduino.cc/en/Reference/WiFiBegin
To get the information of a WiFi connection:
Use WiFi.SSID()
to get SSID of the current connected network.
https://www.arduino.cc/en/Reference/WiFiSSID
Use WiFi.RSSI()
to get the signal strength of the connection.
https://www.arduino.cc/en/Reference/WiFiRSSI
Use WiFi.localIP()
to get the IP address of Ameba.
https://www.arduino.cc/en/Reference/WiFiLocalIP
Use WiFiServer server()
to create a server that listens on the specified port.
https://www.arduino.cc/en/Reference/WiFiServer
Use server.begin()
to tell the server to begin listening for incoming connections.
https://www.arduino.cc/en/Reference/WiFiServerBegin
Use server.available()
to get a client that is connected to the server and has data available for reading.
https://www.arduino.cc/en/Reference/WiFiServerAvailable
Use client.connected()
to get whether or not the client is connected.
https://www.arduino.cc/en/Reference/WiFiClientConnected
Use client.println()
to print data followed by a carriage return and newline.
https://www.arduino.cc/en/Reference/WiFiClientPrintln
Use client.print()
to print data to the server that a client is connected to.
https://www.arduino.cc/en/Reference/WiFiClientPrint
Use client.available()
to return the number of bytes available for reading.
https://www.arduino.cc/en/Reference/WiFiClientAvailable
Use client.read()
to read the next byte received from the server the client is connected to.
https://www.arduino.cc/en/Reference/WiFiClientRead
Use client.stop()
to disconnect from the server the client is connected to.
https://www.arduino.cc/en/Reference/WiFIClientStop
Board HDK
EVB
RTL8722DM Module
API Documents
RTL8722DM ARDUINO Online API Documents
Analog
Class AmebaServo
Description
Defines a class of manipulating servo motors connected to Arduino pins.
Syntax
class AmebaServo
Members
Public Constructors |
|
---|---|
AmebaServo::AmebaServo |
Constructs an AmebaServo object. |
Public Methods |
|
AmebaServo::attach |
Attach the given pin to the next free channel. |
AmebaServo::detach |
Detach the servo. |
AmebaServo::write |
Write value, if the value is < 200 it’s treated as an angle, otherwise as pulse-width in microseconds. |
AmebaServo::writeMicroseconds |
Write pulse width in microseconds. |
AmebaServo::read |
Output current pulse width as an angle between 0 and 180 degrees. |
AmebaServo::readMicroseconds |
Output current pulse width in microseconds for this servo. |
AmebaServo::attached |
Check if the servo is attached. |
Description
Attach the given pin to the next free channel, sets pinMode (including minimum and maximum values for writes), returns channel number, or 0 if failure.
Syntax
uint8_t attach(int pin);
uint8_t attach(int pin, int min, int max);
Parameters
pin: The Arduino pin number to be attached.
min: Minimum values for writes.
max: Maximum values for writes.
Returns
The function returns channel number or 0
Example Code
Example: ServoSweep
The code demos servo motor sweeping from 0 degrees to 180 degrees then sweep back to 0 degrees in the step of 1 degree.
1 /* Sweep
2 by BARRAGAN < http://barraganstudio.com >
3 This example code is in the public domain.
4 modified 8 Nov 2013
5 by Scott Fitzgerald
6 http://www.arduino.cc/en/Tutorial/Sweep
7 refined 2016/03/18 by Realtek
8 */
9
10 #include "AmebaServo.h"
11
12 // create servo object to control a servo
13 // 4 servo objects can be created correspond to PWM pins
14
15 AmebaServo myservo;
16
17 // variable to store the servo position
18 int pos = 0;
19
20 void setup() {
21 #if defined(BOARD_RTL8195A)
22 // attaches the servo on pin 9 to the servo object
23 myservo.attach(9);
24 #elif defined(BOARD_RTL8710)
25 // attaches the servo on pin 13 to the servo object
26 myservo.attach(13);
27 #elif defined(BOARD_RTL8721D)
28 // attaches the servo on pin 8 to the servo object
29 myservo.attach(8);
30 #else
31 // attaches the servo on pin 9 to the servo object
32 myservo.attach(9);
33 #endif
34 }
35
36 void loop() {
37 // goes from 0 degrees to 180 degrees in steps of 1 degree
38 for (pos = 0; pos <= 180; pos += 1) {
39 // tell servo to go to position in variable 'pos'
40 myservo.write(pos);
41 // waits 15ms for the servo to reach the position
42 delay(15);
43 }
44 // goes from 180 degrees to 0 degrees
45 for (pos = 180; pos >= 0; pos -= 1) {
46 // tell servo to go to position in variable 'pos'
47 myservo.write(pos);
48 // waits 15ms for the servo to reach the position
49 delay(15);
50 }
51 }
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
Description
Detach the servo.
Syntax
void AmebaServo::detach(void);
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AmebaServo::write
Description
Write an integer value to the function, if the value is < 200, it’s being treated as an angle, otherwise as pulse-width in microseconds.
Syntax
void AmebaServo::write(int value);
Parameters
value: The value < 200 its treated as an angle; otherwise as pulse width in microseconds.
Returns
The function returns nothing.
Example Code
Example: ServoSweep
The code demos servo motor sweeping from 0 degrees to 180 degrees then sweep back to 0 degrees in the step of 1 degree. Please refer to code in “AmebaServo:: attach” section.
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AmebaServo::writeMicroseconds
Description
Write pulse width to the servo in microseconds.
Syntax
void AmebaServo::writeMicroseconds(int value);
Parameters
value: Write value the pulse width in microseconds.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AmebaServo::read
Description
The function reads current pulse width and returns as an angle between 0 and 180 degrees.
Syntax
int AmebaServo::read(void);
Parameters
The function requires no input parameter.
Returns
The pulse width as an angle between 0 ~ 180 degrees.
Example Code
NA
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AmebaServo::readMicroseconds
Description
The function returns a Boolean value “true” if this servo is attached, otherwise returns “false”.
Syntax
int AmebaServo::readMicroseconds(void);
Parameters
The function requires no input parameter.
Returns
The function returns current servo pulse width in microseconds.
Example Code
NA
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AmebaServo::attached
Description
It returns true if this servo is attached, otherwise false.
Syntax
bool AmebaServo::attached(void);
Parameters
The function requires no input parameter.
Returns
The function returns a Boolean value as true or false.
Example Code
Example: ServoSweep
The code demos servo motor sweeping from 0 degrees to 180 degrees then sweep back to 0 degrees in the step of 1 degree. Please refer to code in “AmebaServo:: attach” section.
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AudioCodec
Class AudioCodec
Description
A class used for general control and management of the hardware audio codec functions.
Syntax
class AudioCodec
Members
Public Constructors
The public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named Codec.
Public Methods
AudioCodec::begin |
Configure and start the audio codec for transmit and receive operation |
---|---|
AudioCodec::end |
Stop all audio codec operation |
AudioCodec::getBufferPageSize |
Get the byte size of a single page of the audio codec buffer |
AudioCodec::setSampleRate |
Configure the audio codec transmit and receive sampling rate |
AudioCodec::setBitDepth |
Configure the audio codec transmit and receive bit depth (bits per sample) |
AudioCodec::setChannelCount |
Configure the audio codec transmit and receive channel count |
AudioCodec::setInputMicType |
Configure for analog or digital input microphone type |
AudioCodec::setInputLRMux |
Configure input left right channel multiplexing |
AudioCodec::setDMicBoost |
Configure boost gain for digital microphone input |
AudioCodec::setAMicBoost |
Configure boost gain for analog microphone input |
AudioCodec::setADCGain |
Configure gain of ADC used to acquire analog input |
AudioCodec::muteInput |
Mute input audio data stream |
AudioCodec::setOutputVolume |
Configure output audio volume |
AudioCodec::muteOutput |
Mute output audio |
AudioCodec::writeAvaliable |
Check for free buffer page available for data write |
AudioCodec::writeDataPage |
Write audio data to an available buffer page |
AudioCodec::readAvaliable |
Check for buffer page with new data available for read |
AudioCodec::readDataPage |
Read audio data from a ready buffer page |
AudioCodec::setWriteCallback |
Set a callback function to be notified when a free buffer page is available for write |
AudioCodec::setReadCallback |
Set a callback function to be notified when a buffer page with new data is available for read |
AudioCodec::begin
Description
Configure and start the audio codec for transmit and receive operation.
Syntax
void begin(bool input, bool output);
Parameters
input: enable audio codec data input
output: enable audio codec data output
Returns
The function returns nothing.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::end
Description
Stop all audio codec operation.
Syntax
void end();
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
AudioCodec::getBufferPageSize
Description
Get the byte size of a single page of the audio codec buffer.
Syntax
uint32_t getBufferPageSize();
Parameters
The function requires no input parameter.
Returns
The size of a audio codec buffer page, in number of bytes.
Example Code
NA
Notes and Warnings
The AudioCodec class includes a transmit and receive buffer to store audio sample data while transferring to and from the DAC output and ADC input. The buffer is divided into pages of fixed size, and audio data can be read and written one page at a time. Depending on the configured bit depth (bits per audio sample) and channel count, a buffer page may contain a different number of audio samples.
AudioCodec::setSampleRate
Description
Configure the audio codec transmit and receive sampling rate.
Syntax
void setSampleRate(uint32_t sampleRate);
Parameters
sampleRate: desired audio codec sampling rate in Hz. Default value of 48000. Supported values: 8000, 16000, 32000, 44100, 48000, 88200, 96000.
Returns
The function returns nothing.
Example Code
Example: BasicInputOutput
Notes and Warnings
High sample rates above 48000Hz will require frequent buffer reads and writes to keep up with the large amount of data input and output. If there is insufficient processing time dedicated to this task, audio quality will be degraded.
AudioCodec::setBitDepth
Description
Configure the audio codec transmit and receive bit depth (bits per sample).
Syntax
void setBitDepth(uint8_t bitDepth);
Parameters
bitDepth: desired number of bits per sample. Default value of 16. Supported values: 8, 16, 24.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Setting a bit depth of 24 bits per sample will require 32 bits (4 bytes) of buffer space for storing each sample, with the most significant byte ignored.
AudioCodec::setChannelCount
Description
Configure the audio codec transmit and receive channel count.
Syntax
void setChannelCount(uint8_t monoStereo);
Parameters
monoStereo: number of channels. Default value of 1. Supported values: 1, 2.
Returns
The function returns nothing.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::setInputMicType
Description
Configure for analog or digital input microphone type.
Syntax
Void setInputMicType(Mic_Type micType);
Parameters
micType: Input microphone type. Default value ANALOGMIC. Valid values:
ANALOGMIC – microphone with an analog output
PDMMIC – digital microphone with a PDM output
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
For analog single-ended output, connect to PA_4 for the left channel and PA_2 for the right channel.
For digital PDM output, connect the PDM clock to PB_1 and PDM data to PB_2.
AudioCodec::setInputLRMux
Description
Configure input left right channel multiplexing.
Syntax
void setInputLRMux(uint32_t mux);
Parameters
mux: desired left right audio channel multiplexing setting. Default value RX_CH_LR. Valid values:
RX_CH_LR
RX_CH_RL
RX_CH_LL
RX_CH_RR
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
In mono channel mode, both RX_CH_LR and RX_CH_LL will result in the audio codec sampling input data from the left channel microphone. Similarly, both RX_CH_RL and RX_CH_RR will result in the audio codec sampling input data from the right channel microphone.
In stereo channel mode, RX_CH_RL will switch the positions of input data sampled from the microphones. RX_CH_RR and RX_CH_LL will result in duplicated samples from the right and left microphones respectively.** **
AudioCodec::setDMicBoost
Description
Configure boost gain for digital microphone input.
Syntax
void setDMicBoost(uint32_t leftBoost, uint32_t rightBoost);
Parameters
leftBoost: boost gain for left channel digital microphone input
rightBoost: boost gain for right channel digital microphone input
Valid boost gain values:
0 : 0dB
1 : 12dB
2 : 24dB
3 : 36dB
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
AudioCodec::setAMicBoost
Description
Configure boost gain for analog microphone input.
Syntax
void setAMicBoost(uint32_t leftBoost, uint32_t rightBoost);
Parameters
leftBoost: boost gain for left channel analog microphone input
rightBoost: boost gain for right channel analog microphone input
Valid boost gain values:
0 : 0dB
1 : 20dB
2 : 30dB
3 : 40dB
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Only use this function if additional gain is required after using setADCGain function.
AudioCodec::setADCGain
Description
Configure gain of ADC used to acquire analog input.
Syntax
void setADCGain(uint32_t leftGain, uint32_t rightGain);
Parameters
leftGain: Gain for left channel ADC
rightGain: Gain for right channel ADC
Valid value range is from 0x00 to 0x7f. Gain increases by 0.375dB for every increment in value:
0x00 : -17.625dB
0x01 : -17.25dB
0x2f : 0dB
0x30 : 0.375dB
0x7f : 30dB
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
AudioCodec::muteInput
Description
Mute input audio data stream.
Syntax
void muteInput(uint8_t leftMute, uint8_t rightMute);
Parameters
leftMute: 1 to mute left channel input, 0 to unmute
rightMute: 1 to mute right channel input, 0 to unmute
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
AudioCodec::setOutputVolume
Description
Configure output audio volume.
Syntax
void setOutputVolume(uint8_t leftVol, uint8_t rightVol);
Parameters
leftVol: left channel output volume
rightVol: right channel output volume
Valid value ranges from 0 to 100, corresponding to a volume of -65.625dB to 0dB.
Returns
The function returns nothing.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::muteOutput
Description
Mute output audio.
Syntax
void muteOutput(uint8_t leftMute, uint8_t rightMute);
Parameters
leftMute: 1 to mute left channel output, 0 to unmute
rightMute: 1 to mute right channel output, 0 to unmute
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
AudioCodec::writeAvaliable
Description
Check for free buffer page available for data write.
Syntax
bool writeAvaliable();
Parameters
The function requires no input parameter.
Returns
Returns true if there is a buffer page that is available for writing data into. Returns false if all buffer pages are full.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::writeDataPage
Description
Write audio data to an available buffer page.
Syntax
uint32_t writeDataPage(int8_t* src, uint32_t len);
uint32_t writeDataPage(int16_t* src, uint32_t len);
Parameters
src: pointer to array containing audio samples to write to audio codec.
len: number of audio samples in array.
Returns
The function returns the number of audio samples written to the audio codec.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::readAvaliable
Description
Check for buffer page with new data available for read.
Syntax
bool readAvaliable();
Parameters
The function requires no input parameter.
Returns
Returns true if there is a buffer page with new data that is ready for reading data from. Returns false if all buffer pages are empty.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::readDataPage
Description
Read audio data from a ready buffer page.
Syntax
uint32_t readDataPage(int8_t* dst, uint32_t len);
uint32_t readDataPage(int16_t* dst, uint32_t len);
Parameters
dst: pointer to array to contain audio samples read from audio codec.
len: number of audio samples to read.
Returns
The function returns the number of audio samples read from the audio codec.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::setWriteCallback
Description
Set a callback function to be notified when a free buffer page is available for write.
Syntax
void setWriteCallback(void (writeCB)(**void*));
Parameters
writeCB: function to be called when a buffer page becomes available for data write. Takes no arguments and returns nothing
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
After starting the audio codec with AudioCodec::begin(), the callback function will be called each time the audio codec finishes outputting the data in a buffer page.
AudioCodec::setReadCallback
Description
Set a callback function to be notified when a buffer page with new data is available for read.
Syntax
void setReadCallback(void (readCB)(**void*));
Parameters
readCB: function to be called when a buffer page with new data becomes available for data read. Takes no arguments and returns nothing
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
After starting the audio codec with AudioCodec::begin(), the callback function will be called each time the audio codec fills up a buffer page with newly acquired audio samples.
Class FFT
Description
A class used for performing FFT calculations with real-number inputs and outputs.
Syntax
class FFT
Members
Public Constructors
FFT::FFT |
Create an instance of the FFT class |
Public Methods
FFT::setWindow |
Configure the window function used in FFT calculations |
---|---|
FFT::calculate |
Calculate FFT for an input array of values |
FFT::getFrequencyBins |
Get the FFT output frequency bins |
FFT::getFFTSize |
Get the size of FFT output for a given input size |
FFT::FFT
Description
Create a FFT class object.
Syntax
void FFT();
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
Example: FFT
Notes and Warnings
FFT::setWindow
Description
Configure the window function used in FFT calculations.
Syntax
void setWindow(FFTWindow_t window, uint16_t sampleCount);
Parameters
window: The window function to be used in FFT calculations. Valid values: None, Hann, Hamming.
sampleCount: Number of sample datapoints in the input.
Returns
The function returns nothing.
Example Code
Example: FFT
Notes and Warnings
The window function is used to reduce the effects of discontinuities that occur when the input signal has frequencies that do not fit an integer number of periods in the sample datapoints.
More information on FFTs and window functions can be seen at:
https://download.ni.com/evaluation/pxi/Understanding%20FFTs%20and%20Windowing.pdf
https://en.wikipedia.org/wiki/Window_function
FFT::Calculate
Description
Calculate FFT for an input array of values.
Syntax
void calculate(float* inputBuf, float* outputBuf, uint16_t sampleCount);
void calculate(int16_t* inputBuf, float* outputBuf, uint16_t sampleCount);
Parameters
inputBuf: pointer to an array of sampleCount size, containing input sample datapoints, in float or uint16_t format.
outputBuf: pointer to a float array of sampleCount/2 size, for containing FFT output.
sampleCount: number of sample datapoints in the input array, valid values: 16, 32, 64, 128, 256, 512, 1024, 2048.
Returns
The function returns nothing.
Example Code
Example:FFT
Notes and Warnings
Large sample counts will require a longer time for FFT calculations, but will also return a result with higher frequency resolution.
FFT::getFrequencyBins
Description
Get the FFT output frequency bins.
Syntax
void getFrequencyBins(uint16_t* outputBuf, uint16_t sampleCount, uint32_t sampleRate);
Parameters
outputBuf: pointer to a uint16_t array of sampleCount/2 size, for containing the calculated center frequency of each FFT output element.
Returns
The function returns nothing.
Example Code
Example: FFT
Notes and Warnings NA
—
FFT::getFFTSize
Description
Get the size of FFT output for a given input size.
Syntax
uint16_t getFFTSize(uint16_t sampleCount);
Parameters
sampleCount: number of input sample datapoints.
Returns
The function returns the FFT output size for the given sampleCount, which is sampleCount/2.
Example Code
NA
Notes and Warnings NA
Class PlaybackWav
Description
A class used for control and playback of .wav file format audio data.
Syntax
class PlaybackWav
Members
Public Constructors
PlaybackWav::PlaybackWav |
Create an instance of the PlaybackWav class |
Public Methods
PlaybackWav::openFile |
Open a .wav file for playback |
PlaybackWav::closeFile |
Close a previously opened file |
PlaybackWav::fileOpened |
Check if a .wav file is already opened |
PlaybackWav::getSampleRate |
Get the sample rate of the .wav file |
PlaybackWav::getChannelCount |
Get the number of audio channels in the .wav file |
PlaybackWav::getBitDepth |
Get the bit depth of each sample in the .wav file |
PlaybackWav::getLengthMillis |
Get the playback length of the .wav file in milliseconds |
PlaybackWav::getPositionMillis |
Get the current playback position in milliseconds |
PlaybackWav::setPositionMillis |
Set the current playback position in milliseconds |
PlaybackWav::millisToBytes |
Convert a playback duration to equivalent number of bytes |
PlaybackWav::bytesToMillis |
Convert number of bytes to an equivalent playback duration |
PlaybackWav::readAudioData |
Read audio data from the .wav file |
PlaybackWav::PlaybackWav
Description
Create a PlaybackWav class object.
Syntax
void PlaybackWav(void);
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
PlaybackWav::fileOpened
Description
Check if a .wav file is already opened.
Syntax
bool fileOpened(void);
Parameters
The function requires no input parameter.
Returns
The function returns true if a .wav file is already open, false otherwise.
Example Code
Example: RecordPlaybackWav
Notes and Warnings
NA
PlaybackWav::getSampleRate
Description
Get the sample rate of the .wav file.
Syntax
uint32_t getSampleRate(void);
Parameters
The function requires no input parameter.
Returns
The function returns sampling rate encoded in the .wav file header.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
PlaybackWav::getChannelCount
Description
Get the number of audio channels in the .wav file.
Syntax
uint16_t getChannelCount(void);
Parameters
The function requires no input parameter.
Returns
The function returns channel count encoded in the .wav file header.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
PlaybackWav::getBitDepth
Description
Get the bit depth of each sample in the .wav file.
Syntax
uint16_t getBitDepth(void);
Parameters
The function requires no input parameter.
Returns
The function returns bit depth encoded in the .wav file header.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
PlaybackWav::getLengthMillis
Description
Get the playback length of the .wav file in milliseconds.
Syntax
uint32_t getLengthMillis(void);
Parameters
The function requires no input parameter.
Returns
The function returns the total playback length of the currently open .wav file in milliseconds.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
PlaybackWav::getPositionMillis
Description
Get the current playback position in milliseconds.
Syntax
uint32_t getPositionMillis(void);
Parameters
The function requires no input parameter.
Returns
The function returns the current playback position of the currently open .wav file in milliseconds.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
PlaybackWav::setPositionMillis
Description
Set the current playback position in milliseconds.
Syntax
void setPositionMillis(uint32_t pos);
Parameters
pos: The desired playback position expressed in milliseconds.
Returns
The function returns nothing.
Example Code
Example: PlaybackWavFile
Notes and Warnings
Any changes to playback position will only take effect on the next call to PlaybackWav::readAudioData. If the desired playback position is beyond the total playback length of the file, the playback position will be set to the end of file, and no audio data will be output on subsequent data reads.
PlaybackWav::millisToBytes
Description
Convert a playback duration to equivalent number of bytes.
Syntax
uint32_t millisToBytes(uint32_t ms);
Parameters
ms: playback duration in milliseconds.
Returns
The function returns the number of bytes that is equivalent to the input playback duration, converted using the current sample rate, number of channels and bit depth.
Example Code
NA
Notes and Warnings
NA
PlaybackWav::bytesToMillis
Description
Convert number of bytes to an equivalent playback duration.
Syntax
uint32_t bytesToMillis(uint32_t bytes);
Parameters
bytes: playback duration in number of bytes.
Returns
The function returns the time duration in milliseconds that is equivalent to the input number of bytes, converted using the current sample rate, number of channels and bit depth.
Example Code
NA
Notes and Warnings
NA
PlaybackWav::readAudioData
Description
Read audio data from the .wav file.
Syntax
uint32_t readAudioData(int8_t* dst, uint32_t len);
uint32_t readAudioData(int16_t* dst, uint32_t len);
Parameters
dst
: pointer to array to store data read from .wav file.
len
: number of audio samples to read from .wav file.
Returns
The function returns number of audio samples read.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
Class RecordWav
Description
A class used for control and recording of .wav file format audio data.
Syntax
class RecordWav
Members
Public Constructors
RecordWav:: RecordWav |
Create an instance of the RecordWav class |
Public Methods
RecordWav::openFile |
Open a .wav file for playback |
RecordWav::closeFile |
Close a previously opened file |
RecordWav::fileOpened |
Check if a .wav file is already opened |
RecordWav::setSampleRate |
Get the sample rate of the .wav file |
RecordWav::setChannelCount |
Set the number of audio channels in the .wav file |
RecordWav::setBitDepth |
Set the bit depth of each sample in the .wav file |
RecordWav::getLengthMillis |
Get the current record length of the .wav file in milliseconds |
RecordWav::millisToBytes |
Convert a playback duration to equivalent number of bytes |
RecordWav::bytesToMillis |
Convert number of bytes to an equivalent playback duration |
RecordWav::writeAudioData |
Write audio data to the .wav file |
RecordWav::RecordWav
Description
Create a RecordWav class object.
Syntax
void RecordWav(void);
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
Example: RecordWavFile
Notes and Warnings
NA
RecordWav::openFile
Description
Open a .wav file for recording.
Syntax
void openFile(const char* absFilepath);
Parameters
absFilepath: the filepath of the .wav file to open.
Returns
The function returns nothing.
Example Code
Example: RecordWavFile
Notes and Warnings
NA
RecordWav::closeFile
Description
Close a previously opened file.
Syntax
void closeFile(void);
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
Example: RecordWavFile
Notes and Warnings
Any open .wav files should be closed after recording is complete, otherwise, loss of recorded audio data may occur.
RecordWav::fileOpened
Description
Check if a .wav file is already opened.
Syntax
bool fileOpened(void);
Parameters
The function requires no input parameter.
Returns
The function returns true if a .wav file is already open, false otherwise.
Example Code
Example: RecordWavFile
Notes and Warnings
NA
RecordWav::setSampleRate
Description
Set the recording sample rate of the .wav file.
Syntax
void setSampleRate(uint32_t sampleRate);
Parameters
sampleRate: The desired recording sample rate.
Returns
The function returns nothing.
Example Code
Example: RecordWavFile
Notes and Warnings
NA
RecordWav::setChannelCount
Description
Set the number of recording audio channels in the .wav file.
Syntax
void setChannelCount(uint16_t channelCount);
Parameters
channelCount: number of recording audio channels.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
RecordWav::setBitDepth
Description
Set the recording bit depth of each sample in the .wav file.
Syntax
void setBitDepth(uint16_t bitDepth);
Parameters
bitDepth: number of bits per sample.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
RecordWav::getLengthMillis
Description
Get the current recorded length of the .wav file in milliseconds.
Syntax
uint32_t getLengthMillis(void);
Parameters
The function requires no input parameter.
Returns
The function returns the current recorded length of the currently open .wav file in milliseconds.
Example Code
NA
Notes and Warnings
NA
RecordWav::millisToBytes
Description
Convert a playback duration to equivalent number of bytes.
Syntax
uint32_t millisToBytes(uint32_t ms);
Parameters
ms: playback duration in milliseconds.
Returns
The function returns the number of bytes that is equivalent to the input playback duration, converted using the current sample rate, number of channels and bit depth.
Example Code
NA
Notes and Warnings
NA
RecordWav::bytesToMillis
Description
Convert number of bytes to an equivalent playback duration.
Syntax
uint32_t bytesToMillis(uint32_t bytes);
Parameters
bytes: playback duration in number of bytes.
Returns
The function returns the time duration in milliseconds that is equivalent to the input number of bytes, converted using the current sample rate, number of channels and bit depth.
Example Code
NA
Notes and Warnings
NA
RecordWav::writeAudioData
Description
Write audio data to the .wav file.
Syntax
uint32_t writeAudioData(int8_t* src, uint32_t len); uint32_t writeAudioData(int16_t* src, uint32_t len);
Parameters
src: pointer to array containing data to write to .wav file. len: number of audio samples to write to .wav file.
Returns
The function returns number of audio samples written.
Example Code
Example: RecordWavFile
Notes and Warnings
NA
BLE
Class BLEAddr
BLEAddr Class
Description
A class used for managing Bluetooth addresses.
Members
Public Constructors |
|
---|---|
BLEAddr::BLEAddr |
Constructs a BLEAddr object |
Public Methods |
|
BLEAddr::str |
Get the Bluetooth address represented as a formatted string |
BLEAddr::data |
Get the Bluetooth address represented as an integer array |
BLEAddr::BLEAddr
BLEAddr::str
BLEAddr::data
Class BLEAdvert
BLEAdvert Class
Members
Public Constructors |
---|
No public constructor is available as this class is intended to be a singleton class. You can get a pointer to this class using BLEDevice::configAdvert(). |
Public Methods |
|
---|---|
BLEAdvert::updateAdvertParams |
Update the current BLE advertisement settings to the lower Bluetooth stack |
BLEAdvert::startAdv |
Start BLE advertising |
BLEAdvert::stopAdv |
Stop BLE advertising |
BLEAdvert::setAdvType |
Set the BLE advertising type |
BLEAdvert::setMinInterval |
Set the BLE advertising minimum interval |
BLEAdvert::setMaxInterval |
Set the BLE advertising maximum interval |
BLEAdvert::setAdvData |
Set BLE advertising data |
BLEAdvert::setScanRspData |
Set BLE scan response data |
BLEAdvert::updateAdvertParams
BLEAdvert::startAdv
BLEAdvert::stopAdv
BLEAdvert::setAdvType
BLEAdvert::setMinInterval
BLEAdvert::setMaxInterval
BLEAdvert::setAdvData
BLEAdvert::setScanRspData
Class BLEAdvertData
BLEAdvertData Class
Members
Public Constructors |
|
---|---|
BLEAdvertData::BLEAdvertData |
Constructs a BLEAdvertData object |
Public Methods |
|
---|---|
BLEAdvertData::clear |
Clear all advertising data |
BLEAdvertData::addData |
Add binary advertising data |
BLEAdvertData::addFlags |
Add flags to advertising data |
B LEAdvertData::addPartialServices |
Add partial services to advertising data |
BL EAdvertData::addCompleteServices |
Add complete services to advertising data |
BLEAdvertData::addAppearance |
Add device appearance to advertising data |
BLEAdvertData::addShortName |
Add short device name to advertising data |
BLEAdvertData::addCompleteName |
Add complete device name to advertising data |
BLEAdvertData::parseScanInfo |
Parse advertising data received from a scan |
BLEAdvertData::hasFlags |
Check if received data includes advertising flags |
BLEAdvertData::hasUUID |
Check if received data includes UUIDs |
BLEAdvertData::hasName |
Check if received data includes device name |
BLEAdvertData::hasManufacturer |
Check if received data includes manufacturer data |
BLEAdvertData::getAdvType |
Get advertising type of received data |
BLEAdvertData::getAddrType |
Get Bluetooth address type of received data |
BLEAdvertData::getAddr |
Get Bluetooth address of received data |
BLEAdvertData::getRSSI |
Get RSSI of received data |
BLEAdvertData::getFlags |
Get advertising flags of received data |
BLEAdvertData::getServiceCount |
Get number of advertised services in received data |
BLEAdvertData::getServiceList |
Get array of advertised services in received data |
BLEAdvertData::getName |
Get advertised device name in received data |
BLEAdvertData::getTxPower |
Get advertised transmission power in received data |
BLEAdvertData::getAppearance |
Get advertised device appearance in received data |
BLEAdvertData::getManufacturer |
Get advertised manufacturer in received data |
BLEAdver tData::getManufacturerDataLength |
Get length of manufacturer data in received data |
BL EAdvertData::getManufacturerData |
Get advertised manufacturer data in received data |
BLEAdvertData::BLEAdvertData
BLEAdvertData::clear
BLEAdvertData::addData
BLEAdvertData::addFlags
BLEAdvertData::addPartialServices
BLEAdvertData::addCompleteServices
BLEAdvertData::addAppearance
BLEAdvertData::addShortName
BLEAdvertData::addCompleteName
BLEAdvertData::parseScanInfo
BLEAdvertData::hasFlags
BLEAdvertData::hasUUID
BLEAdvertData::hasName
BLEAdvertData::hasManufacturer
BLEAdvertData::getAdvType
BLEAdvertData::getAddrType
BLEAdvertData::getRSSI
BLEAdvertData::getFlags
BLEAdvertData::getServiceCount
BLEAdvertData::getServiceList
BLEAdvertData::getName
BLEAdvertData::getTxPower
BLEAdvertData::getAppearance
BLEAdvertData::getManufacturer
BLEAdvertData::getManufacturerDataLength
BLEAdvertData::getManufacturerData
Class BLEBeacon
iBeacon Class
Members
Public Constructors |
|
---|---|
iBeacon::iBeacon |
Create an instance of iBeacon advertising data |
Public Methods |
|
iBeacon::getManufacturerId |
Get current manufacturer ID value |
iBeacon::getUUID |
Get current UUID value |
iBeacon::getMajor |
Get current Major value |
iBeacon::getMinor |
Get current Minor value |
iBeacon::getRSSI |
Get current RSSI value |
iBeacon::setManufacturerId |
Set manufacturer ID value |
iBeacon::setUUID |
Set UUID value |
iBeacon::setMajor |
Set Major value |
iBeacon::setMinor |
Set Minor value |
iBeacon::setRSSI |
Set RSSI value |
iBeacon::getAdvData |
Get current advertising data |
iBeacon::getScanRsp |
Get current scan response data |
altBeacon Class
Members
Public Constructors |
|
---|---|
altBeacon::altBeacon |
Create an instance of altBeacon advertising data |
Public Methods |
|
altBeacon::getManufacturerId |
Get current manufacturer ID value |
altBeacon::getUUID |
Get current UUID value |
altBeacon::getMajor |
Get current Major value |
altBeacon::getMinor |
Get current Minor value |
altBeacon::getRSSI |
Get current RSSI value |
altBeacon::getRSVD |
Get current Reserved value |
altBeacon::setManufacturerId |
Set manufacturer ID value |
altBeacon::setUUID |
Set UUID value |
altBeacon::setMajor |
Set Major value |
altBeacon::setMinor |
Set Minor value |
altBeacon::setRSSI |
Set RSSI value |
altBeacon::setRSVD |
Set Reserved value |
altBeacon::getAdvData |
Get current advertising data |
altBeacon::getScanRsp |
Get current scan response data |
iBeacon::iBeacon
altBeacon::altBeacon
iBeacon::getManufacturerId
altBeacon::getManufacturerId
iBeacon::getUUID
altBeacon::getUUID
iBeacon::getMajor
altBeacon::getMajor
iBeacon::getMinor
altBeacon::getMinor
iBeacon::getRSSI
altBeacon::getRSSI
iBeacon::setManufacturerId
altBeacon::setManufacturerId
iBeacon::setUUID
altBeacon::setUUID
iBeacon::setMajor
altBeacon::setMajor
iBeacon::setMinor
altBeacon::setMinor
iBeacon::setRSSI
altBeacon::setRSSI
iBeacon::getAdvData
altBeacon::getAdvData
iBeacon::getScanRsp
altBeacon::getScanRsp
altBeacon::getRSVD
altBeacon::setRSVD
Class BLECharacteristic
BLECharacteristic Class
Description
A class used for creating and managing BLE GATT characteristics.
Members
Public Constructors |
|
---|---|
BLEC haracteristic::BLECharacteristic |
Constructs a BLECharacteristic object |
Public Methods |
|
BLECharacteristic::setUUID |
Set the characteristic UUID |
BLECharacteristic::getUUID |
Get the characteristic UUID |
BLECharacteristic::setBufferLen |
Set the size of the internal data buffer |
BLECharacteristic::getBufferLen |
Get the current size of the internal data buffer |
BL ECharacteristic::setReadProperty |
Get the current size of the internal data bufferSet the characteristic read property |
BLE Characteristic::setWriteProperty |
Set the characteristic write property |
BLEC haracteristic::setNotifyProperty |
Set the characteristic notify property |
BLECha racteristic::setIndicateProperty |
Set the characteristic indicate property |
BLECharacteristic::setProperties |
Set the characteristic properties |
BLECharacteristic::getProperties |
Get the characteristic properties |
BLECharacteristic::readString |
Read the characteristic data buffer as a String object |
BLECharacteristic::readData8 |
Read the characteristic data buffer as an unsigned 8-bit integer |
BLECharacteristic::readData16 |
Read the characteristic data buffer as an unsigned 16-bit integer |
BLECharacteristic::readData32 |
Read the characteristic data buffer as an unsigned 32-bit integer |
BLECharacteristic::writeString |
Write data to the characteristic data buffer as a String object or character array |
BLECharacteristic::writeData8 |
Write data to the characteristic data buffer as an unsigned 8-bit integer |
BLECharacteristic::writeData16 |
Write data to the characteristic data buffer as an unsigned 16-bit integer |
BLECharacteristic::writeData32 |
Write data to the characteristic data buffer as an unsigned 16-bit integer |
BLECharacteristic::setData |
Write data to the characteristic data buffer |
BLECharacteristic::getData |
Read data from the characteristic data buffer |
BLECharacteristic::getDataBuff |
Get a pointer to the characteristic data buffer |
BLECharacteristic::getDataLen |
Get the number of bytes of data in the characteristic data buffer |
BLECharacteristic::notify |
Send a notification to a connected device |
BLECharacteristic::indicate |
Send an indication to a connected device |
BLEC haracteristic::setUserDescriptor |
Add a user description descriptor to characteristic |
BLECha racteristic::setFormatDescriptor |
Add a data format descriptor to characteristic |
BLECharacteristic::Add a data format descriptor to characteristic |
Set a user function as a read callback |
BLE Characteristic::setWriteCallback |
Set a user function as a write callback |
BL ECharacteristic::setCCCDCallback |
Set a user function as a CCCD write callback |
BLECharacteristic::BLECharacteristic
BLECharacteristic::setUUID
BLECharacteristic::getUUID
BLECharacteristic::setBufferLen
BLECharacteristic::getBufferLen
BLECharacteristic::setReadProperty
BLECharacteristic::setWriteProperty
BLECharacteristic::setNotifyProperty
BLECharacteristic::setIndicateProperty
BLECharacteristic::setProperties
BLECharacteristic::getProperties
BLECharacteristic::readString
BLECharacteristic::readData8
BLECharacteristic::readData16
BLECharacteristic::readData32
BLECharacteristic::readData32
BLECharacteristic::writeData8
BLECharacteristic::writeData16
BLECharacteristic::writeData32
BLECharacteristic::setData
BLECharacteristic::getData
BLECharacteristic::getDataBuff
BLECharacteristic::getDataLen
BLECharacteristic::notify
BLECharacteristic::indicate
BLECharacteristic::setUserDescriptor
BLECharacteristic::setFormatDescriptor
BLECharacteristic::setReadCallback
BLECharacteristic::setWriteCallback
BLECharacteristic::setCCCDCallback
Class BLEClient
BLEClient Class
Members
Public Constructors |
---|
No public constructor is available for this class. You can get a pointer to an instance of this class using BLEDevice::addClient(). |
Public Methods |
|
---|---|
BLEClient::connected |
Check if the corresponding remote device for the client is connected |
BLEClient::discoverServices |
Start service discovery process for connected device |
BLEClient::discoveryDone |
Determine if service discovery process has been completed |
BLEClient::printServices |
Format and print discovered services to serial port |
BLEClient::getService |
Get a specific service on the remote device |
BLEClient::getConnId |
|
BLEClient::getClientId |
Get corresponding client ID |
BLEClient::setDisconnectCallback |
Set a user function to be called when the remote device is disconnected |
BLEClient::connected
BLEClient::discoverServices
BLEClient::discoveryDone
BLEClient::printServices
BLEClient::getService
BLEClient::getConnId
BLEClient::getClientId
BLEClient::setDisconnectCallback
Class BLEConnect
BLEConnect Class
Members
Public Constructors |
---|
No public constructor is available as this class is intended to be a singleton class. You can get a pointer to this class using BLEDevice::configConnection. |
Public Methods |
|
---|---|
BLEConnect::connect |
Connect to a target BLE device |
BLEConnect::disconnect |
Disconnect from a target BLE device |
BLEConnect::setScanInterval |
Set the BLE scanning interval when connecting |
BLEConnect::setScanWindow |
Set the BLE scanning window when connecting |
BLEConnect::setConnInterval |
Set the BLE connection interval duration |
BLEConnect::setConnLatency |
Set the BLE connection slave latency |
BLEConnect::setConnTimeout |
Set the BLE connection timeout value |
BLEConnect::updateConnParams |
Send new BLE connection parameters to a connected device |
BLEConnect::getConnInfo |
Get connection information |
BLEConnect::getConnAddr |
Get the Bluetooth address for a certain connection |
BLEConnect::getConnId |
Get the connection ID for a certain device |
BLEConnect::connect
BLEConnect::disconnect
BLEConnect::setScanInterval
BLEConnect::setScanWindow
BLEConnect::setConnInterval
BLEConnect::setConnLatency
BLEConnect::setConnTimeout
BLEConnect::updateConnParams
BLEConnect::getConnInfo
BLEConnect::getConnAddr
BLEConnect::getConnId
Class BLEDevice
BLEDevice Class
Members
Public Constructors |
---|
The public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named BLE. |
Public Methods |
|
---|---|
BLEDevice::init |
Allocate resources required for BLE functionality |
BLEDevice::deinit |
Free resources used by BLE functionality |
BLEDevice::connected |
Check if a BLE device is connected |
BLEDevice::setDeviceName |
Set BLE GAP device name |
BLEDevice::setDeviceAppearance |
Set BLE GAP device appearance |
BLEDevice::configAdvert |
Configure BLE advertising parameters |
BLEDevice::configScan |
Configure BLE scan parameters |
BLEDevice::setScanCallback |
Set callback function for BLE scans |
BLEDevice::beginCentral |
Start BLE stack in central mode |
BLEDevice::beginPeripheral |
Start BLE stack in peripheral mode |
BLEDevice::end |
Stop BLE stack |
BLEDevice::configServer |
Configure BLE stack for services |
BLEDevice::addService |
Add a service to the BLE stack |
BLEDevice::configClient |
Configure BLE stack for clients |
BLEDevice::addClient |
Add a client to the BLE stack |
BLEDevice::getLocalAddr |
Get local device Bluetooth address |
BLEDevice::init
BLEDevice::deinit
BLEDevice::connected
BLEDevice::setDeviceName
BLEDevice::setDeviceAppearance
BLEDevice::configAdvert
BLEDevice::configScan
#include 「BLEDevice.h」
#include 「BLEScan.h」
int dataCount = 0;
void scanFunction(T_LE_CB_DATA* p_data) {
printf(」rnScan Data %drn」, ++dataCount);
BLE.configScan()->printScanInfo(p_data);
}
void setup() {
BLE.init();
BLE.configScan()->setScanMode(GAP_SCAN_MODE_ACTIVE);
BLE.configScan()->setScanInterval(500); // Start a scan every 500ms
BLE.configScan()->setScanWindow(250); // Each scan lasts for 250ms
// Provide a callback function to process scan data.
// If no function is provided, default BLEScan::printScanInfo is used
BLE.setScanCallback(scanFunction);
BLE.beginCentral(0);
BLE.configScan()->startScan(5000); // Repeat scans for 5 seconds, then stop
}
void loop() {
}
BLEDevice::setScanCallback
BLEDevice::beginCentral
BLEDevice::beginPeripheral
BLEDevice::end
BLEDevice::configServer
BLEDevice::addService
BLEDevice::configClient
BLEDevice::addClient
BLEDevice::getLocalAddr
Class BLEHIDDevice
BLEHIDDevice Class
Description
A class used for creating and managing HID over GATT Profile (HOGP) services.
Members
Public Constructors |
---|
The public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named BLEHIDDev. |
Public Methods |
|
---|---|
BLEHIDDevice::init |
Initialize the HID Device Profile by creating the required services |
BLEHIDD evice::setNumOutputReport |
Configure the number of HID output reports |
BLEHID Device::setNumInputReport |
Configure the number of HID input reports |
B LEHIDDevice::setReportMap |
Configure the HID report map |
BLEHIDDevice::inputReport |
Send a HID input report |
BLEHIDDevice ::setOutputReportCallback |
Set a user callback function for receiving HID output reports |
BLEHIDD evice::bootKeyboardReport |
Send a HID boot keyboard input report |
BLEHIDDevice::setHidInfo |
Set HID info of the HID service |
B LEHIDDevice::setBattLevel |
Set battery level info of the Battery service |
BLEHIDDevice::setPNPInfo |
Set PNP information of the Device Information service |
BLEHIDDevi ce::setManufacturerString |
Set manufacturer information of the Device Information service |
BLE HIDDevice::setModelString |
Set model information of the Device Information service |
BLEHIDDevice::hidService |
Get reference to HID service |
BLE HIDDevice::devInfoService |
Get reference to Device Information service |
BLEHIDDevice::battService |
Get reference to Battery service |
BLEHIDDevice::init
BLEHIDDevice::setNumOutputReport
BLEHIDDevice::setNumInputReport
BLEHIDDevice::setReportMap
BLEHIDDevice::inputReport
BLEHIDDevice::setOutputReportCallback
BLEHIDDevice::bootKeyboardReport
BLEHIDDevice::setHidInfo
BLEHIDDevice::setBattLevel
BLEHIDDevice::setPNPInfo
BLEHIDDevice::setManufacturerString
BLEHIDDevice::setModelString
BLEHIDDevice::hidService
BLEHIDDevice::devInfoService
BLEHIDDevice::battService
Class BLEHIDGamepad
BLEHIDGamepad Class
Description
A class used for creating and managing a BLE HID Gamepad.
Members
Public Constructors |
|
---|---|
BLEHIDGame pad::BLEHIDGamepad |
Constructs a BLEHIDGamepad object |
Public Methods |
|
BLEHIDGa mepad::setReportID |
Set HID report ID for the HID Gamepad |
BLEHIDGame pad::gamepadReport |
Send a HID Gamepad report |
BLEHIDGa mepad::buttonPress |
Send a HID Gamepad report indicating buttons pressed |
BLEHIDGame pad::buttonRelease |
Send a HID Gamepad report indicating buttons released |
BLEHIDGamepad ::buttonReleaseAll |
Send a HID Gamepad report indicating no buttons pressed |
BLE HIDGamepad::setHat |
Send a HID Gamepad report indicating hat switch position |
BLEH IDGamepad::setAxes |
Send a HID Gamepad report indicating position of all axes |
BLEHIDGam epad::setLeftStick |
Send a HID Gamepad report indicating position of axes corresponding to left analog stick |
BLEHIDGame pad::setRightStick |
Send a HID Gamepad report indicating position of axes corresponding to right analog stick |
BLEHIDGa mepad::setTriggers |
Send a HID Gamepad report indicating position of axes corresponding to triggers |
Class BLEHIDKeyboard
BLEHIDKeyboard Class
Description
A class used for creating and managing a BLE HID Keyboard.
Members
Public Constructors |
|
---|---|
BLEHIDKeybo ard::BLEHIDKeyboard |
Constructs a BLEHIDKeyboard object |
Public Methods |
|
BLEHIDKe yboard::setReportID |
Set HID report ID for the HID Keyboard and HID consumer control |
BLEHIDKeybo ard::consumerReport |
Send a HID Consumer report |
BLEHIDKeybo ard::keyboardReport |
Send a HID Keyboard report |
BLEHIDKeyb oard::consumerPress |
Send a HID Consumer report indicating button pressed |
BLEHIDKeyboa rd::consumerRelease |
Send a HID Consumer report indicating button released |
BLEHI DKeyboard::keypress |
Send a HID Keyboard report indicating keys pressed |
BLEHIDK eyboard::keyRelease |
Send a HID Keyboard report indicating keys released |
BLEHIDKeyb oard::keyReleaseAll |
Send a HID Keyboard report indicating no keys pressed |
BLEHIDKey board::keyCharPress |
Send a HID Keyboard report indicating keys pressed to output an ASCII character |
BLEHIDKe yboard::keySequence |
Send a HID Keyboard report indicating keys pressed to output an ASCII string |
Class BLEHIDMouse
BLEHIDMouse Class
Description
A class used for creating and managing a BLE HID Mouse.
Members
Public Constructors |
|
---|---|
BLE HIDMouse::BLEHIDMouse |
Constructs a BLEHIDMouse object |
Public Methods |
|
BLE HIDMouse::setReportID |
Set HID report ID for the HID Mouse |
BLE HIDMouse::mouseReport |
Send a HID Mouse report |
BL EHIDMouse::mousePress |
Send a HID Mouse report indicating buttons pressed |
BLEH IDMouse::mouseRelease |
Send a HID Mouse report indicating buttons released |
BLEHIDM ouse::mouseReleaseAll |
Send a HID Mouse report indicating no buttons pressed |
B LEHIDMouse::mouseMove |
Send a HID Mouse report indicating mouse movement |
BLE HIDMouse::mouseScroll |
Send a HID Mouse report indicating mouse scroll wheel movement |
Class BLERemoteCharacteristic
BLERemoteCharacteristic Class
Members
Public Constructors |
---|
No public constructor is available for this class. You can get a pointer to an instance of this class using BLERemoteService::getCharacteristic(). |
Public Methods |
|
---|---|
BLERem oteCharacteristic::getDescriptor |
Get a specific descriptor on the remote device |
BLERemoteCharacteristic::getUUID |
Get the characteristic UUID |
BLERe moteCharacteristic::setBufferLen |
Set the size of the internal data buffer |
BLERe moteCharacteristic::getBufferLen |
Get the current size of the internal data buffer |
BLERemoteCharacteristic::canRead |
Determine if characteristic has read property enabled |
B LERemoteCharacteristic::canWrite |
Determine if characteristic has write property enabled |
BL ERemoteCharacteristic::canNotify |
Determine if characteristic has notify property enabled |
BLER emoteCharacteristic::canIndicate |
Determine if characteristic has indicate property enabled |
BLERem oteCharacteristic::getProperties |
Get the characteristic properties |
BLE RemoteCharacteristic::readString |
Read the characteristic data buffer as a String object |
BL ERemoteCharacteristic::readData8 |
Read the characteristic data buffer as an unsigned 8-bit integer |
BLE RemoteCharacteristic::readData16 |
Read the characteristic data buffer as an unsigned 16-bit integer |
BLE RemoteCharacteristic::readData32 |
Read the characteristic data buffer as an unsigned 32-bit integer |
BLER emoteCharacteristic::writeString |
Write data to the characteristic as a String object or character array |
BLE RemoteCharacteristic::writeData8 |
Write data to the characteristic as an unsigned 8-bit integer |
BLER emoteCharacteristic::writeData16 |
Write data to the characteristic as an unsigned 16-bit integer |
BLER emoteCharacteristic::writeData32 |
Write data to the characteristic as an unsigned 16-bit integer |
BLERemoteCharacteristic::setData |
Write data to the characteristic |
BLERemoteCharacteristic::getData |
Read data from the characteristic |
BLERemoteChar acteristic::enableNotifyIndicate |
Enable notification or indication for the characteristic |
BLERemoteChara cteristic::disableNotifyIndicate |
Disable notification and indication for the characteristic |
BLERemoteC haracteristic::setNotifyCallback |
Set a user function as a notification callback |
BLERemoteCharacteristic::getDescriptor
BLERemoteCharacteristic::getUUID
BLERemoteCharacteristic::setBufferLen
BLERemoteCharacteristic::getBufferLen
BLERemoteCharacteristic::canRead
BLERemoteCharacteristic::canWrite
BLERemoteCharacteristic::canNotify
BLERemoteCharacteristic::canIndicate
BLERemoteCharacteristic::getProperties
BLERemoteCharacteristic::readString
BLERemoteCharacteristic::readData8
BLERemoteCharacteristic::readData16
BLERemoteCharacteristic::readData32
BLERemoteCharacteristic::writeString
BLERemoteCharacteristic::writeData8
BLERemoteCharacteristic::writeData16
BLERemoteCharacteristic::writeData32
BLERemoteCharacteristic::setData
BLERemoteCharacteristic::getData
BLERemoteCharacteristic::enableNotifyIndicate
BLERemoteCharacteristic::disableNotifyIndicate
BLERemoteCharacteristic::setNotifyCallback
Class BLERemoteDescriptor
BLERemoteDescriptor Class
Members
Public Constructors |
---|
No public constructor is available for this class. You can get a pointer to an instance of this class using BLERemoteCharacteristic::getDescriptor(). |
Public Methods |
|
---|---|
BLERemoteDescriptor::getUUID |
Get the descriptor UUID |
B LERemoteDescriptor::setBufferLen |
Set the size of the internal data buffer |
B LERemoteDescriptor::getBufferLen |
Get the current size of the internal data buffer |
BLERemoteDescriptor::readString |
Read the descriptor data buffer as a String object |
BLERemoteDescriptor::readData8 |
Read the descriptor data buffer as an unsigned 8-bit integer |
BLERemoteDescriptor::readData16 |
Read the descriptor data buffer as an unsigned 16-bit integer |
BLERemoteDescriptor::readData32 |
Read the descriptor data buffer as an unsigned 32-bit integer |
BLERemoteDescriptor::writeString |
Write data to the descriptor as a String object or character array |
BLERemoteDescriptor::writeData8 |
Write data to the descriptor as an unsigned 8-bit integer |
BLERemoteDescriptor::writeData16 |
Write data to the descriptor as an unsigned 16-bit integer |
BLERemoteDescriptor::writeData32 |
Write data to the descriptor as an unsigned 16-bit integer |
BLERemoteDescriptor::setData |
Write data to the descriptor |
BLERemoteDescriptor::getData |
Read data from the descriptor |
BLERemoteDescriptor::getUUID
BLERemoteDescriptor::setBufferLen
BLERemoteDescriptor::getBufferLen
BLERemoteDescriptor::readString
BLERemoteDescriptor::readData8
BLERemoteDescriptor::readData16
BLERemoteDescriptor::readData32
BLERemoteDescriptor::writeString
BLERemoteDescriptor::writeData8
BLERemoteDescriptor::writeData16
BLERemoteDescriptor::writeData32
BLERemoteDescriptor::setData
BLERemoteDescriptor::getData
Class BLERemoteService
BLERemoteService Class
Members
Public Constructors |
---|
No public constructor is available for this class. You can get a pointer to an instance of this class using BLEClient::getService(). |
Public Methods |
|
---|---|
BLERemoteService::getUUID |
Get the service UUID |
BLE RemoteService::getCharacteristic |
Get a specific characteristic on the remote device |
BLERemoteService::getUUID
BLERemoteService::getCharacteristic
Class BLEScan
BLEScan Class
Members
Public Constructors |
---|
No public constructor is available as this class is intended to be a singleton class. You can get a pointer to this class using BLEDevice::configScan |
Public Methods |
|
---|---|
BLEScan::updateScanParams |
Update the current BLE advertisement settings to the lower Bluetooth stack |
BLEScan::startScan |
Start a BLE scan |
BLEScan::stopScan |
Stop a BLE scan |
BLEScan::setScanMode |
Set the BLE scanning mode |
BLEScan::setScanInterval |
Set the BLE scanning interval |
BLEScan::setScanWindow |
Set the BLE scanning window |
BLEScan::setScanDuplicateFilter |
Set the BLE scan duplicate filter |
BLEScan::scanInProgress |
Check if a scan is currently in progress |
BLEScan::printScanInfo |
Print out scanned information |
BLEScan::updateScanParams
BLEScan::startScan
BLEScan::stopScan
BLEScan::setScanMode
BLEScan::setScanInterval
BLEScan::setScanWindow
BLEScan::setScanDuplicateFilter
BLEScan::scanInProgress
BLEScan::printScanInfo
Class BLEService
BLEService Class
Members
Public Constructors |
|
---|---|
BLEService::BLEService |
Constructs a BLEService object |
Public Methods |
|
BLEService::setUUID |
Set service UUID |
BLEService::getUUID |
Get service UUID |
BLEService::addCharacteristic |
Add a characteristic to service |
BLEService::getCharacteristic |
Get a previously added characteristic |
BLEService::BLEService
BLEService::setUUID
BLEService::getUUID
BLEService::addCharacteristic
BLEService::getCharacteristic
Class BLEUUID
BLEUUID Class
Members
Public Constructors |
|
---|---|
BLEUUID::BLEUUID |
Create a UUID object |
Public Methods |
|
BLEUUID::str |
Get the character string representation of UUID |
BLEUUID::data |
Get the binary representation of UUID |
BLEUUID::length |
Get the length of UUID |
BLEUUID::BLEUUID
BLEUUID::str
BLEUUID::data
BLEUUID::length
Class BLEWifiConfigService
BLEWifiConfigService Class
Members
Public Constructors |
|
---|---|
BLEWifiCon figService::BLEWifiConfigService |
Only one instance of this class should be created |
Public Methods |
|
---|---|
BLEWifiConfigService::begin |
Start background thread to process WiFi configuration commands |
BLEWifiConfigService::end |
Stop background thread processing WiFi configuration commands |
BLEWifiConfigService::addService |
Add the service to the BLE stack |
BLEWifiConfigService::advData |
Get advertising data correctly formatted for WiFi configuration service |
BLEWifiConfigService::BLEWifiConfigService
BLEWifiConfigService::begin
BLEWifiConfigService::end
BLEWifiConfigService::addService
BLEWifiConfigService::advData
EPDIF
Class EpdIF
EpdIf Class
Members
Public Constructors |
---|
A public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named EpdIf. |
Public Methods |
|
---|---|
EpdIf::EPD_Dis_Part |
Put an image buffer to the frame memory, but not updating the display |
EpdIf::EPD_SetFrame |
Put display data to the frame memory, usually used for setup text display functions |
EpdIf::EPD_SetRAMValue_BaseMap |
To read image data stored in the RAM, but not display on the screen |
EpdIf::EPD_SetFrameMemory |
To read image data stored in the buffer, but not display on the screen |
EpdIf::EPD_UpdateDisplay |
Update the display |
EpdIf::EPD_ClearScreen_White |
Clear the frame memory with the White color, but not updating the display |
EpdIf::EPD_ClearScreen_Black |
Clear the frame memory with the Black color, but not updating the display |
EpdIf::EPD_Busy |
Wait until the Busy pin goes to low, which is the idle state |
EpdIf::EPD_Reset |
Used for the Epaper module reset. Often used to awaken the module in deep sleep |
EpdIf::EPD_Sleep |
After this command is transmitted, the chip would enter the deep-sleep mode to save power |
EpdIf:: EPD_Dis_Part
EpdIf:: EPD_SetFrame
EpdIf:: EPD_SetRAMValue_BaseMap
EpdIf:: EPD_SetFrameMemory
EpdIf:: EPD_UpdateDisplay
EpdIf:: EPD_ClearScreen_White
EpdIf:: EPD_ClearScreen_Black
EpdIf:: EPD_Busy
EpdIf:: EPD_Reset
EpdIf::EPD_Sleep
FatfsSDCard
Class SdFatFs
Description
Defines a class of SD FAT File system.
Syntax
class SdFatFs
Members
Public Constructors
SdFatFs::SdFatFs Constructs a SdFatFs object
SdFatFs::~SdFatFs Destructs a SdFatFs object
Public Methods
SdFatFs::begin |
Initialize SD FAT File System |
---|---|
SdFatFs::end |
Deinitialize SD FAT File System |
SdFatFs::*getRootPath |
Get the root path of the SD FAT File System |
SdFatFs::readDir |
List items under a specific folder |
SdFatFs::mkdir |
Create folder |
SdFatFs::rm |
Remove folder or file |
SdFatFs::isDir |
Check if a specific path is a directory |
SdFatFs::isFile |
Check if a specific path is a file |
SdFatFs::getLastModTime |
Get the last modified time for a file or directory |
SdFatFs::setLastModTime |
Set the last modified time for a file or directory |
SdFatFs::status |
Return the current status of SD |
SdFatFs::open |
Open a file |
SdFatFs::begin
SdFatFs::end
SdFatFs::*getRootPath
SdFatFs::readDir
SdFatFs::mkdir
SdFatFs::rm
SdFatFs::isDir
SdFatFs::isFile
SdFatFs::getLastModTime
SdFatFs::setLastModTime
SdFatFs::open
SdFatFs::status
Class SdFatFile
Description
Defines a class of SD FAT File.
Members
Public Constructors |
|
---|---|
SdFatFile::SdFatFile |
Constructs a SdFatFile object |
SdFatFile::~SdFatFile |
Destructs a SdFatFile object |
Public Methods |
|
SdFatFile::write |
Write 1 byte/bytes to file |
SdFatFile::read |
Read 1 byte/bytes from the file |
SdFatFile::peek |
Read 1 byte from file without move curser |
SdFatFile::available |
Check if the cursor is at EOF (End-Of-File) |
SdFatFile::bool |
Check if file is opened |
SdFatFile::seek |
Change cursor to a specific position |
SdFatFile::close |
Close file |
SdFatFile::write
SdFatFile:: read
Example Code
#include 「FatFs_SD.h」
char dirname[] = 「testdir」;
char filename[] = 「test.txt」;
char write_content[] = 「hello world!」;
FatFsSD fs;
void setup() {
char buf[128];
char absolute_filename[128];
fs.begin();
sprintf(absolute_filename, 「%s%s」, fs.getRootPath(), dirname);
fs.mkdir(absolute_filename);
printf(「create dir at \」%s"rn」, absolute_filename);
sprintf(absolute_filename, 「%s%s/%s」, fs.getRootPath(), dirname, filename);
SdFatFile file = fs.open(absolute_filename);
file.println(write_content);
file.close();
printf(「create file at \」%s"rn」, absolute_filename);
printf(「read back from \」%s"rn」, absolute_filename);
file = fs.open(absolute_filename);
memset(buf, 0, sizeof(buf));
file.read(buf, sizeof(buf));
file.close();
printf(「==== content ====rn」);
printf(「%s」, buf);
printf(「==== end ====rn」);
fs.end();
}
void loop() {
delay(1000);
}
#include 「FatFs_SD.h」
char filename[] = 「test.txt」;
char write_content[] = 「hello world!」;
FatFsSD fs;
void setup() {
char buf[128];
char absolute_filename[128];
fs.begin();
printf(「write something to \」%s"rn」, filename);
sprintf(absolute_filename, 「%s%s」, fs.getRootPath(), filename);
SdFatFile file = fs.open(absolute_filename);
file.println(write_content);
file.close();
printf(「write finishrnrn」);
printf(「read back from \」%s"rn」, filename);
file = fs.open(absolute_filename);
memset(buf, 0, sizeof(buf));
file.read(buf, sizeof(buf));
file.close();
printf(「==== content ====rn」);
printf(「%s」, buf);
printf(「==== end ====rn」);
fs.end();
}
void loop() {
delay(1000);
}
SdFatFile:: peek
SdFatFile:: available
SdFatFile:: flush
SdFatFile:: seek
SdFatFile:: close
#include <FatFs_SD.h>
FatFsSD fs;
char filename[] = 「test.txt」;
void setup() {
char absolute_filename[128];
uint16_t year = 2021;
uint16_t month = 4;
uint16_t date = 4;
uint16_t hour = 12;
uint16_t minute = 12;
uint16_t second = 12;
fs.begin();
sprintf(absolute_filename, 「%s%s」, fs.getRootPath(), filename);
SdFatFile file = fs.open(absolute_filename);
file.close();
fs.setLastModTime(absolute_filename, year, month, date, hour, minute, second);
fs.getLastModTime(absolute_filename, &year, &month, &date, &hour, &minute, &second);
printf(「filename:"%s"rn」, absolute_filename);
printf(「time mod:%04d/%02d/%02d %02d:%02d:%02drn」, year, month, date, hour, minute, second);
fs.end();
}
void loop() {
delay(1000);
}
FlashMemory
Class EpdIF
FlashMemoryClass Class
Members
Public Constructors |
|
---|---|
Fl ashMemoryClass::FlashMemoryClass |
Constructs a FlashMemoryClass object |
Fla shMemoryClass::~FlashMemoryClass |
Deconstructs a FlashMemoryClass object |
Public Methods |
|
FlashMemoryClass::begin |
Initialize/Re-initialize the base address and size |
FlashMemoryClass::read |
Read the content to buf |
FlashMemoryClass::update |
Write buf back to flash memory |
FlashMemoryClass::readWord |
Read 4 bytes from flash memory |
FlashMemoryClass::writeWord |
Write 4 bytes into flash memory |
FlashMemoryClass::buf_size |
The buf size |
FlashMemoryClass::*buf |
The buf to be operated |
FlashMemoryClass::FlashMemoryClass
#include <FlashMemory.h>
void setup() {
FlashMemory.read();
if (FlashMemory.buf[0] == 0xFF) {
FlashMemory.buf[0] = 0x00;
FlashMemory.update();
Serial.println(「write count to 0」);
} else {
FlashMemory.buf[0]++;
FlashMemory.update();
Serial.print(「Boot count: 「);
Serial.println(FlashMemory.buf[0]);
}
}
void loop() {
delay(1000);
}
#include <FlashMemory.h>
void setup() {
unsigned int value;
/* request flash size 0x4000 from 0xFC000 */
FlashMemory.begin(0xFC000, 0x4000);
/* read one word (32-bit) from 0xFC000 plus offset 0x3F00 */
value = FlashMemory.readWord(0x3F00);
printf(「value is 0x%08Xrn」, value);
if (value == 0xFFFFFFFF) {
value = 0;
} else {
value++;
}
/* write one word (32-bit) to 0xFC000 plus offset 0x3F00 */
FlashMemory.writeWord(0x3F00, value);
}
void loop() {
// put your main code here, to run repeatedly:
}
FlashMemoryClass::begin
FlashMemoryClass::read
FlashMemoryClass::update
FlashMemoryClass::readWord
FlashMemoryClass::writeWord
FlashMemoryClass::buf_size
FlashMemoryClass::*buf
GPIO
Class DHT
DHT Class
Members
Public Constructors |
|
---|---|
DHT::DHT |
Constructs a DHT object |
Public Methods |
|
DHT::begin |
Initialize the DHT sensor |
DHT::readTemperature |
Read temperature(Fahrenheit or Celcius) from the DHT sensor |
DHT::convertCtoF |
Convert a value from Celcius to Fahrenheit |
DHT::convertFtoC |
Convert a value from Fahrenheit to Celcius |
DHT::readHumidity |
Read humidity(%) from the DHT sensor |
DHT::computeHeatIndex |
Compute the HeatIndex from the readings (Using both Rothfusz and Steadman’s equations) |
DHT::read |
Check if the sensor is readable |
DHT::DHT
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain
#include 「DHT.h」
// The digital pin we’re connected to.
#define DHTPIN 8
// 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(115200);
Serial.println(「DHTxx test!」);
dht.begin();
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 『old』 (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(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(」 *Ft」);
Serial.print(「Heat index: 「);
Serial.print(hic);
Serial.print(」 *C 「);
Serial.print(hif);
Serial.println(」 *F」);
}
DHT::begin
DHT::readTemperature
DHT::convertCtoF
DHT::convertFtoC
DHT::computeHeatIndex
DHT::readHumidity
DHT::read
Class HttpClient
InterruptLock Class
Members
Public Constructors |
|
---|---|
InterruptLock::InterruptLock |
Constructs a InterruptLock object |
InterruptLock::~ InterruptLock |
Deconstructs a InterruptLock object |
GTimer
Class EpdIF
GTimerClass Class
Members
Public Constructors |
|
---|---|
GTimerClass::GTimerClass |
Constructs a GTimerClass object |
Public Methods |
|
GTimerClass::begin |
Initialize a timer and start it immediately |
GTimerClass::stop |
Stop a specific timer |
GTimerClass::reload |
Reload a specific timer |
GTimerClass::read_us |
Read current countdown value |
GTimerClass::begin
/*
This sketch shows how to use several hardware timers in invoke handler only once for each timer.
*/
#include <GTimer.h>
void myhandler(uint32_t data) {
Serial.print(「I am timer!」);
Serial.println(data);
}
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// timerid 0, period 1s, invoke myhandler, invoke only once, user data is 0
GTimer.begin(0, 1 * 1000 * 1000, myhandler, false, 0);
// timerid 1, period 2s, invoke myhandler, invoke only once, user data is 1
GTimer.begin(1, 2 * 1000 * 1000, myhandler, false, 1);
GTimer.begin(2, 3 * 1000 * 1000, myhandler, false, 2);
GTimer.begin(3, 4 * 1000 * 1000, myhandler, false, 3);
}
void loop() {
delay(1000);
}
Example: TimerPeriodical
/*
This sketch shows how to use hardware timer and invoke interrupt handler periodically
*/
#include <GTimer.h>
int counter = 0;
void myhandler(uint32_t data) {
counter++;
Serial.print(「counter: 「);
Serial.println(counter);
if (counter >= 10) {
Serial.println(「stop timer」);
GTimer.stop(0);
}
}
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// timerid 0, period 1s, invoke myhander
GTimer.begin(0, (1 * 1000 * 1000), myhandler);
}
void loop() {
delay(1000);
}
GTimerClass::stop
GTimerClass::reload
GTimerClass::read_us
Http
Class HttpClient
HttpClient Class
Members
Public Constructors |
|
---|---|
HttpClient::HttpClient |
Constructs a HttpClient object |
Public Methods |
|
HttpClient::beginRequest |
Start a more complex request |
HttpClient::endRequest |
End a more complex request |
HttpClient::get |
Connect to the server and start to send a GET request |
HttpClient::post |
Connect to the server and start to send a POST request |
HttpClient::put |
Connect to the server and start to send a PUT request |
HttpClient::startRequest |
Connect to the server and start to send the request |
HttpClient::sendHeader |
Send an additional header line |
HttpClient::sendBasicAuth |
Send a basic authentication header |
HttpClient::finishRequest |
Finish sending the HTTP request |
HttpClient::responseStatusCode |
Get the HTTP status code contained in the response |
HttpClient::readHeader |
Read the next character of the response headers |
HttpClient::skipResponseHeaders |
Skip any response headers to get to the body |
HttpClient::endOfHeadersReached |
Test whether all of the response headers have been consumed |
HttpClient::endOfBodyReached |
Test whether the end of the body has been reached |
HttpClient::contentLength |
Return the length of the body |
HttpClient::HttpClient
#include <HttpClient.h>
#include <WiFi.h>
#include <WiFiClient.h>
char ssid[] = 「YourNetwork」; // your network SSID (name)
char pass[] = 「password」; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
// Name of the server we want to connect to
const char kHostname[] = 「www.google.com」;
const char kPath[] = 「/」;
// Number of milliseconds to wait without receiving any data before we give up
const int kNetworkTimeout = 30*1000;
// Number of milliseconds to wait if no data is available before trying again
const int kNetworkDelay = 1000;
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600);
while ( status != WL_CONNECTED) {
Serial.print(「Attempting to connect to SSID: 「);
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(「Connected to wifi」);
printWifiStatus();
}
void loop() {
int err =0;
WiFiClient c;
HttpClient http(c);
err = http.get(kHostname, kPath);
if (err == 0)
{
Serial.println(「startedRequest ok」);
err = http.responseStatusCode();
if (err >= 0)
{
Serial.print(「Got status code: 「);
Serial.println(err);
// Usually you’d check that the response code is 200 or a
// similar 「success」 code (200-299) before carrying on,
// but we’ll print out whatever response we get
err = http.skipResponseHeaders();
if (err >= 0)
{
int bodyLen = http.contentLength();
Serial.print(「Content length is: 「);
Serial.println(bodyLen);
Serial.println();
Serial.println(「Body returned follows:」);
// Now we’ve got to the body, so we can print it out
unsigned long timeoutStart = millis();
char c;
// Whilst we haven’t timed out & haven’t reached the end of the body
while ( (http.connected() || http.available()) &&
((millis() - timeoutStart) < kNetworkTimeout) )
{
if (http.available())
{
c = http.read();
// Print out this character
Serial.print(c);
bodyLen–;
// We read something, reset the timeout counter
timeoutStart = millis();
}
else
{
// We haven’t got any data, so let’s pause to allow some to arrive
delay(kNetworkDelay);
}
}
}
else
{
Serial.print(「Failed to skip response headers: 「);
Serial.println(err);
}
}
else
{
Serial.print(「Getting response failed: 「);
Serial.println(err);
}
}
else
{
Serial.print(「Connect failed: 「);
Serial.println(err);
}
http.stop();
// And just stop, now that we’ve tried a download
while(1);
}
void printWifiStatus() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.print(rssi);
Serial.println(」 dBm」);
}
HttpClient::beginRequest
HttpClient::endRequest
HttpClient::get
HttpClient::post
HttpClient::put
HttpClient::startRequest
HttpClient::sendHeader
HttpClient::sendBasicAuth
HttpClient::finishRequest
HttpClient::responseStatusCode
HttpClient::readHeader
HttpClient::skipResponseHeaders
HttpClient::endOfHeadersReached
HttpClient::endOfBodyReached
HttpClient::contentLength
IRDevice
Class HttpClient
IRDevice Class
Members
Public Constructors |
|
---|---|
A public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named IR. |
Public Methods |
|
---|---|
IRDevice::getFreq |
Get the current IR modulation frequency |
IRDevice::begin |
Allocate resources and start the IR device with a custom frequency |
IRDevice::end |
Stop the IR device operations and free up resources |
IRDevice::send |
Send IR raw data |
IRDevice::beginNEC |
Allocate resources and start the IR device with a frequency suitable for the NEC protocol |
IRDevice::sendNEC |
Send data using the NEC protocol |
IRDevice::recvNEC |
Receive data using the NEC protocol |
IRDevice::getFreq
IRDevice::begin
IRDevice::end
IRDevice::send
Example Code
#include 「IRDevice.h」
// User defined txPin, rxPin and carrier frequency
#define IR_RX_PIN 8
#define IR_TX_PIN 9
#define CARRIER_FREQ 38000
unsigned int irRawSignal[] = {
9000, 4500, // starting bit
560, 560, 560, 560, 560, 1690, 560, 560, 560, 560, 560, 560, 560, 560, 560, 560, // address 00100000 : 4
560, 1690, 560, 1690, 560, 560, 560, 1690, 560, 1690, 560, 1690, 560, 1690, 560, 1690, // ~ address 11011111
560, 560, 560, 560, 560, 560, 560, 1690, 560, 560, 560, 560, 560, 560, 560, 560, // data 00010000 : 8
560, 1690, 560, 1690, 560, 1690, 560, 560, 560, 1690, 560, 1690, 560, 1690, 560, 1690, //~ data 11101111
560 // stoping bit
};
int DataLen = sizeof(irRawSignal) / sizeof(irRawSignal[0]); // 284/ 4 = 71
void setup()
{
Serial.begin(115200);
IR.begin(IR_RX_PIN, IR_TX_PIN, IR_MODE_TX, CARRIER_FREQ);
}
void loop()
{
IR.send(irRawSignal, DataLen);
Serial.println(「Finished Sending NEC Raw Data….」);
delay(3000);
}
IRDevice::beginNEC
#include 「IRDevice.h」
uint8_t adr = 0;
uint8_t cmd = 0;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
IR.beginNEC(8, 9, IR_MODE_RX); // configure for NEC IR protocol
}
void loop() {
if (IR.recvNEC(adr, cmd, 1000)) {
Serial.print(「Received 「);
Serial.print(adr);
Serial.print(cmd);
Serial.println();
} else {
Serial.println(「Received nothing, timed out」);
}
//IR.end();
}
IRDevice::sendNEC
#include 「IRDevice.h」
uint8_t adr = 0;
uint8_t cmd = 0;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
IR.beginNEC(8, 9, IR_MODE_TX); // configure for NEC IR protocol
}
void loop() {
if (cmd++ >=255) {
adr++;
}
IR.sendNEC(adr, cmd);
Serial.print(「Sent 「);
Serial.print(adr);
Serial.print(cmd);
Serial.println();
//IR.end(); // Call this method to stop IR device and free up the pins for other uses
}
IRDevice::recvNEC
MDNS
Class HttpClient
MDNSClass Class
Members
Public Constructors |
|
---|---|
The public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named MDNS. |
Public Methods |
|
---|---|
MDNSClass::begin |
Start MDNS operations |
MDNSClass::end |
Stop MDNS operations |
MDNSClass::registerService |
Add a service record |
MDNSClass::deregisterService |
Remove service record |
MDNSClass::updateService |
Update service record |
MDNSClass::begin
#include <WiFi.h>
#include <AmebaMDNS.h>
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「secretPassword」; // your network password
MDNSService service(「MyAmeba」, 「_arduino._tcp」, 「local」, 5000);
void setup() {
printf(「Try to connect to %srn」, ssid);
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
printf(「Failed. Wait 1s and retry…rn」);
delay(1000);
}
printf(「Connected to %srn」, ssid);
service.addTxtRecord(「board」, strlen(「ameba_rtl8195a」), 「ameba_rtl8195a」);
service.addTxtRecord(「auth_upload」, strlen(「no」), 「no」);
service.addTxtRecord(「tcp_check」, strlen(「no」), 「no」);
service.addTxtRecord(「ssh_upload」, strlen(「no」), 「no」);
printf(「Start mDNS servicern」);
MDNS.begin();
printf(「register mDNS servicern」);
MDNS.registerService(service);
}
void loop() {
// put your main code here, to run repeatedly:
delay(1000);
}
MDNSClass::end
MDNSClass::registerService
MDNSClass::deregisterService
MDNSClass::updateService
Class HttpClient
MDNSService Class
Members
Public Constructors |
|
---|---|
MDNSService::MDNSService |
Create a MDNS service record |
Public Methods |
|
MDNSService::addTxtRecord |
Add text to MDNS service record |
MDNSService::MDNSService
MDNSService::addTxtRecord
MQTTClient
Class PMUClass
PubSubClient Class
Members
Public Constructors |
|
---|---|
PubSubClient::PubSubClient |
Constructs a PubSubClient object |
Public Methods |
|
PubSubClient::setServer |
Set MQTT server address and port |
PubSubClient::setCallback |
Set callback function |
PubSubClient::setClient |
Set WiFi client |
PubSubClient::setStream |
Set data stream |
PubSubClient::connect |
Attempt to connect to server |
PubSubClient::disconnect |
Disconnect from current session |
PubSubClient::publish |
Publish a message to server |
PubSubClient::publish_P |
Same as above |
PubSubClient::subscribe |
Subscribe to a topic |
PubSubClient::unsubscribe |
Unsubscribe to a topic |
PubSubClient::loop |
Keep MQTT session alive and process any queuing tasks |
PubSubClient::connected |
Check if client still connected |
PubSubClient::state |
Return connection state |
PubSubClient::PubSubClient
#include <WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「secretPassword」; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio’s status
char mqttServer[] = 「test.mosquitto.org」;
char clientId[] = 「amebaClient」;
char publishTopic[] = 「outTopic」;
char publishPayload[] = 「hello world」;
char subscribeTopic[] = 「inTopic」;
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print(「Message arrived [「);
Serial.print(topic);
Serial.print(」] 「);
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
WiFiClient wifiClient;
PubSubClient client(wifiClient);
void reconnect() {
// Loop until we’re reconnected
while (!client.connected()) {
Serial.print(「Attempting MQTT connection…」);
// Attempt to connect
if (client.connect(clientId)) {
Serial.println(「connected」);
// Once connected, publish an announcement…
client.publish(publishTopic, publishPayload);
// … and resubscribe
client.subscribe(subscribeTopic);
} else {
Serial.print(「failed, rc=」);
Serial.print(client.state());
Serial.println(」 try again in 5 seconds」);
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
Serial.begin(38400);
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to SSID: 「);
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
client.setServer(mqttServer, 1883);
client.setCallback(callback);
// Allow the hardware to sort itself out
delay(1500);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
}
PubSubClient::setServer
PubSubClient::setCallback
PubSubClient::setClient
PubSubClient::setStream
PubSubClient::connect
PubSubClient::disconnect
PubSubClient::publish
PubSubClient::publish_P
PubSubClient::subscribe
PubSubClient::unsubscribe
PubSubClient::loop
PubSubClient::connected
PubSubClient::state
Readme
PubSubClient.cpp
PubSubClient.h
These libraries are under MIT License.
NTPClient
Readme
NTPClient.cpp
NTPClient.h
These libraries are licensed under MIT License.
PowerSave
Class PMUClass
PMUClass Class
Members
Public Constructors |
|
---|---|
PMUClass::PMUClass |
Constructs a PMUClass object |
Public Methods |
|
PMUCLASS::begin |
Initialize the PMUCLASS and select sleep mode |
PMUCLASS::AONTimerDuration |
Set the duration of AON Timer |
PMUCLASS::AONTimerCmd |
Disable the AON Timer for power save usage |
PMUCLASS::RTCWakeSetup |
Set up RTC Timer for power save usage |
PMUCLASS::enable |
Enable power save deep sleep mode |
PMUCLASS::AONWakeReason |
Check AON wakeup source |
PMUCLASS::WakePinCheck |
Check AON GPIO pin wakeup source |
PMUCLASS::AONWakeClear |
Clear all the AON wakeup source |
PMUCLASS::DsleepWakeStatusGet |
Check if deepsleep mode is set |
PMUCLASS::TL_sysactive_time |
Tickless mode system active time |
PMUCLASS::TL_wakelock |
Tickless mode wake lock, select acquire of release |
PMUCLASS::DS_AON_TIMER_WAKEUP |
Return the Wakeup source |
PMUCLASS::DS_RTC_WAKEUP |
Return the Wakeup source |
PMUCLASS::TL_UART_WAKEUP |
Return the Wakeup source |
PMUCLASS::TL_RTC_WAKEUP |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA12 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA13 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA14 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA15 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA16 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA17 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA18 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA19 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA20 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA21 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA25 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA26 |
Return the Wakeup source |
RTC
Class RTC
RTC Class
Members
Public Constructors |
|
---|---|
A public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named RTC. |
Public Methods |
|
---|---|
RTC:: Init |
Initializes the RTC device, including the Clock, the RTC registers, and other functions |
RTC:: DeInit |
Deinitialize the RTC device |
RTC:: Write |
Set the specified timestamp in seconds to RTC |
RTC:: Read |
Get the current timestamp in seconds from RTC |
RTC:: Wait |
Wait for 1 second |
RTC:: SetEpoch |
Convert human-readable time to epoch time |
RTC::Init
/*
* This function describes how to use the RTC API.
* The RTC function is implemented by an independent BCD timer/counter.
* This example will print out the time information every second.
*/
#include <stdio.h>
#include <time.h>
#include 「rtc.h」
#define YEAR 2020
#define MONTH 9
#define DAY 10
#define HOUR 20
#define MIN 30
#define SEC 40
/* Create an rtc object */
RTC rtc;
int32_t seconds;
struct tm *timeinfo;
void setup() {
Serial.begin(115200);
rtc.Init(); // initialize RTC
}
void loop() {
// step 1: convert user time to epoch
int epochTime = humanReadableToEpoch(YEAR, MONTH, DAY, HOUR, MIN, SEC);
// step 2: write epoch time to rtc
rtc.Write(epochTime);
while (1) {
seconds = rtc.Read();
printf(「Epoch Time (in s) since January 1, 1970 = %dsn」, seconds);
printf(「Time as a basic string = %s」, ctime(&seconds));
timeinfo = localtime(&seconds);
printf(「Time as a custom formatted string = %d-%d-%d %d:%d:%dn」,
(timeinfo->tm_year + 1900), (timeinfo->tm_mon + 1), timeinfo->tm_mday, timeinfo->tm_hour,
timeinfo->tm_min, timeinfo->tm_sec);
Serial.println();
rtc.wait(1);
}
}
// convert human readable time to epoch time
int humanReadableToEpoch(int year, int month, int day, int hour, int min, int sec) {
struct tm t;
time_t t_of_day;
t.tm_year = year - 1900; // Year - 1970
t.tm_mon = month - 1; // Month, where 0 = jan
t.tm_mday = day; // Day of the month
t.tm_hour = hour;
t.tm_min = min;
t.tm_sec = sec;
t.tm_isdst = -1; // Is DST on? 1 = yes, 0 = no, -1 = unknown
t_of_day = mktime(&t);
// printf(「seconds since the Epoch: %dn」, (long)t_of_day);
return t_of_day;
}
RTC::DeInit
RTC:: Write
RTC::Read
RTC:: Wait
RTC:: SetEpoch
SoftwareSerial
Class Adafruit_GPS
Adafruit_GPS Class
Members
Public Constructors |
|
---|---|
Adafruit_GPS::Adafruit_GPS |
Constructs an Adafruit_GPS object |
Public Methods |
|
Adafruit_GPS::begin |
Initialize serial communication |
*Adafruit_GPS:: lastNMEA |
Returns the last NMEA line received and unsets the received flag |
Adafruit_GPS:: newNMEAreceived |
Check to see if a new NMEA line has been received |
Adafruit_GPS:: common_init |
Initialization code used by all constructor types |
Adafruit_GPS:: sendCommand |
Send a command to the GPS device |
Adafruit_GPS:: pause |
Pause/unpause receiving new data |
Adafruit_GPS:: parseHex |
Read a Hex value and return the decimal equivalent |
Adafruit_GPS:: read |
Read one character from the GPS device |
Adafruit_GPS:: parse |
Parse an NMEA string |
Adafruit_GPS:: wakeup |
Wake the sensor up |
Adafruit_GPS:: standby |
Standby Mode Switches |
Adafruit_GPS::waitForSentence |
Wait for a specified sentence from the device |
Adafruit_GPS::LOCUS_StartLogger |
Start the LOCUS logger |
Adafruit_GPS::LOCUS_StopLogger |
Stop the LOCUS logger |
Adafruit_GPS::LOCUS_ReadStatus |
Read the logger status |
Adafruit_GPS::Adafruit_GPS
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>
// If you’re using a GPS module:
// Connect the GPS Power pin to 3.3V
// Connect the GPS Ground pin to ground
// Connect the GPS TX (transmit) pin to Digital 0
// Connect the GPS RX (receive) pin to Digital 1
#if defined(BOARD_RTL8195A)
SoftwareSerial mySerial(0, 1);
#elif defined(BOARD_RTL8710)
SoftwareSerial mySerial(17, 5); // RTL8710 need change GPS TX/RX to pin 17 and 5
#else
SoftwareSerial mySerial(0, 1);
#endif
Adafruit_GPS GPS(&mySerial);
// Set GPSECHO to 『false』 to turn off echoing the GPS data to the Serial console
// Set to 『true』 if you want to debug and listen to the raw GPS sentences.
#define GPSECHO false
void setup()
{
Serial.begin(38400);
Serial.println(「Adafruit GPS library basic test!」);
// 9600 NMEA is the default baud rate for Adafruit MTK GPS’s- some use 4800
GPS.begin(9600);
// uncomment this line to turn on RMC (recommended minimum) and GGA (fix data) including altitude
GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
// uncomment this line to turn on only the 「minimum recommended」 data
//GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCONLY);
// For parsing data, we don’t suggest using anything but either RMC only or RMC+GGA since
// the parser doesn’t care about other sentences at this time
// Set the update rate
GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ); // 1 Hz update rate
// For the parsing code to work nicely and have time to sort thru the data, and
// print it out we don’t suggest using anything higher than 1 Hz
// Request updates on antenna status, comment out to keep quiet
GPS.sendCommand(PGCMD_ANTENNA);
delay(1000);
// Ask for firmware version
mySerial.println(PMTK_Q_RELEASE);
}
uint32_t timer = millis();
void loop() // run over and over again
{
// in case you are not using the interrupt above, you’ll
// need to 『hand query』 the GPS, not suggested :(
// read data from the GPS in the 『main loop』
char c = GPS.read();
// if you want to debug, this is a good time to do it!
if (GPSECHO)
if (c) Serial.print(c);
// if a sentence is received, we can check the checksum, parse it…
if (GPS.newNMEAreceived()) {
// a tricky thing here is if we print the NMEA sentence, or data
// we end up not listening and catching other sentences!
// so be very wary if using OUTPUT_ALLDATA and trytng to print out data
//Serial.println(GPS.lastNMEA()); // this also sets the newNMEAreceived() flag to false
if (!GPS.parse(GPS.lastNMEA())) // this also sets the newNMEAreceived() flag to false
return; // we can fail to parse a sentence in which case we should just wait for another
}
// if millis() or timer wraps around, we’ll just reset it
if (timer > millis()) timer = millis();
// approximately every 2 seconds or so, print out the current stats
if (millis() - timer > 2000) {
timer = millis(); // reset the timer
Serial.print(」nTime: 「);
Serial.print(GPS.hour, DEC); Serial.print(『:』);
Serial.print(GPS.minute, DEC); Serial.print(『:』);
Serial.print(GPS.seconds, DEC); Serial.print(『.』);
Serial.println(GPS.milliseconds);
Serial.print(「Date: 「);
Serial.print(GPS.day, DEC); Serial.print(『/』);
Serial.print(GPS.month, DEC); Serial.print(「/20」);
Serial.println(GPS.year, DEC);
Serial.print(「Fix: 「); Serial.print((int)GPS.fix);
Serial.print(」 quality: 「); Serial.println((int)GPS.fixquality);
if (GPS.fix) {
Serial.print(「Location: 「);
Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
Serial.print(」, 「);
Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
Serial.print(「Location (in degrees, works with Google Maps): 「);
Serial.print(GPS.latitudeDegrees, 4);
Serial.print(」, 「);
Serial.println(GPS.longitudeDegrees, 4);
Serial.print(「Speed (knots): 「); Serial.println(GPS.speed);
Serial.print(「Angle: 「); Serial.println(GPS.angle);
Serial.print(「Altitude: 「); Serial.println(GPS.altitude);
Serial.print(「Satellites: 「); Serial.println((int)GPS.satellites);
}
}
}
Adafruit_GPS::begin
*Adafruit_GPS::lastNMEA
Adafruit_GPS::newNMEAreceived
Adafruit_GPS::common_init
Adafruit_GPS::sendCommand
Adafruit_GPS::pause
Adafruit_GPS::parseHex
Adafruit_GPS::read
Adafruit_GPS::parse
Adafruit_GPS::wakeup
Adafruit_GPS::standby
Adafruit_GPS::waitForSentence
Adafruit_GPS::LOCUS_StartLogger
Adafruit_GPS::LOCUS_StopLogger
Adafruit_GPS::LOCUS_ReadStatus
Class HttpClient
PMS3003 Class
Members
Public Constructors |
|
---|---|
PMS3003::PMS3003 |
Constructs a PMS3003 object |
Public Methods |
|
PMS3003::begin |
Initialize hardware UART |
PMS3003::end |
Free allocated space thus stopping UART |
PMS3003::get_pm1p0_cf1 |
Get PM1.0 under correction factor = 1 |
PMS3003:: get_pm2p5_cf1 |
Get PM2.5 under correction factor = 1 |
PMS3003:: get_pm10_cf1 |
Get PM10 under correction factor = 1 |
PMS3003:: get_pm1p0_air |
Get PM1.0 air quality |
PMS3003:: get_pm2p5_air |
Get PM2.5 air quality |
PMS3003:: get_pm10_air |
Get PM10 air quality |
PMS3003:update_cache |
Updates the cache memory |
PMS3003::pms3003_handle_interrupt |
Set up the serial event handler |
PMS3003::PMS3003
PMS3003::begin
PMS3003::end
PMS3003::get_pm1p0_cf1
PMS3003::get_pm2p5_cf1
PMS3003::get_pm10_cf1
PMS3003::get_pm1p0_air
PMS3003::get_pm2p5_air
PMS3003::get_pm10_air
PMS3003::pms3003_handle_interrupt
PMS3003::update_cache
Class SoftwareSerial
SoftwareSerial Class
Members
Public Constructors |
|
---|---|
SoftwareSerial::SoftwareSerial |
Constructs a SoftwareSerial object |
Public Methods |
|
SoftwareSerial::begin |
Sets the speed (baud rate) for the serial communication |
SoftwareSerial::listen |
Enables the selected software serial port to listen |
SoftwareSerial::end |
Same as stopListening |
SoftwareSerial::stopListening |
Stop listening on the port |
SoftwareSerial::peek |
Return a character that was received on the RX pin of the software serial port |
SoftwareSerial::write |
Prints data to the transmit pin of the software serial port as raw bytes |
SoftwareSerial::read |
Return a character that was received on the RX pin of the software serial port |
SoftwareSerial::available |
Get the number of bytes (characters) available for reading from a software serial port |
SoftwareSerial::flush |
Flush the received buffer |
SoftwareSerial::setBufferSize |
Set buffer size |
Soft wareSerial::setAvailableCallback |
Set available callback |
SoftwareSerial::handle_interrupt |
Private methods handles interrupt |
SoftwareSerial::SoftwareSerial
/*
The circuit: (BOARD RTL8195A)
* RX is digital pin 0 (connect to TX of other devices)
* TX is digital pin 1 (connect to RX of other devices)
*/
#include <SoftwareSerial.h>
#if defined(BOARD_RTL8195A)
SoftwareSerial mySerial(0, 1); // RX, TX
#elif defined(BOARD_RTL8710)
SoftwareSerial mySerial(17, 5); // RX, TX
#else
SoftwareSerial mySerial(0, 1); // RX, TX
#endif
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(57600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println(「Goodnight moon!」);
// set the data rate for the SoftwareSerial port
mySerial.begin(4800);
mySerial.println(「Hello, world?」);
}
void loop() { // run over and over
if (mySerial.available()) {
mySerial.write(mySerial.read());
}
}
SoftwareSerial::begin
SoftwareSerial::listen
SoftwareSerial::end
SoftwareSerial::isListening
SoftwareSerial::stopListening
SoftwareSerial::peek
SoftwareSerial::write
SoftwareSerial::read
SoftwareSerial::available
SoftwareSerial::flush
SoftwareSerial::setBufferSize
SoftwareSerial::setAvailableCallback
/*
The circuit: (BOARD RTL8195A)
RX is digital pin 0 (connect to TX of other devices)
TX is digital pin 1 (connect to RX of other devices)
*/
#include <SoftwareSerial.h>
#if defined(BOARD_RTL8195A)
SoftwareSerial mySerial(0, 1); // RX, TX
#elif defined(BOARD_RTL8710)
SoftwareSerial mySerial(17, 5); // RX, TX
#else
SoftwareSerial mySerial(0, 1); // RX, TX
#endif
uint32_t semaID;
// The callback is hooking at UART IRQ handler and please don’t do heavy task here.
void mySerialCallback(char c)
{
/* The parameter c is only for peeking. The actual data is
* still in the buffer of SoftwareSerial.
*/
if (c == 『r』 || c == 『n』) {
os_semaphore_release(semaID);
}
}
void setup() {
// use 1 count for binary semaphore
semaID = os_semaphore_create(1);
// There is a token in the semaphore, clear it.
os_semaphore_wait(semaID, 0xFFFFFFFF);
// set the data rate for the SoftwareSerial port
mySerial.begin(38400);
mySerial.setAvailableCallback(mySerialCallback);
}
void loop() { // run over and over
// wait semaphore for 5s timeout
if (os_semaphore_wait(semaID, 5 * 1000)) {
// we got data before timeout
while(mySerial.available()) {
mySerial.print((char)mySerial.read());
}
mySerial.println();
} else {
mySerial.println(「No data comes in.」);
}
}
SoftwareSerial::handle_interrupt
Readme
NewSoftSerial.h
by Mikal Hart
(http://arduiniana.org/libraries/newsoftserial).
SoftwareSerial.cpp
SoftwareSerial.h
These libraries are under GNU Lesser General Public License.
Adafruit_GPS.cpp
Adafruit_GPS.h
These libraries are under BSD License.
SPI
Class AmebaILI9341
AmebaILI9341 Class
Description
Defines a class to use ILI9341 TFT SPI display for Ameba.
Syntax
class AmebaILI9341
Members
Public Constructors |
|
---|---|
AmebaILI9341::AmebaILI9341 |
Constructs an AmebaILI9341 object |
Public Methods |
|
AmebaILI9341::begin |
Initialize SPI, pin mapping and screen configuration |
AmebaILI9341::setAddress |
Initialize image size and position |
AmebaILI9341::writecommand |
SPI transfer a command |
AmebaILI9341::writedata |
SPI transfer a piece of data |
AmebaILI9341::setRotation |
Set screen orientation |
AmebaILI9341::fillScreen |
Fill the screen with a color |
AmebaILI9341::clr |
Clear screen |
AmebaILI9341::fillRectangle |
Fill a rectangular space with a color |
AmebaILI9341::drawPixel |
Turn on a pixel on the screen |
AmebaILI9341::drawChar |
To print a character on the screen |
AmebaILI9341::drawLine |
Draw line on the screen |
AmebaILI9341::drawRectangle |
Draw a rectangle on the screen |
AmebaILI9341::drawCircle |
Draw a circle on the screen |
AmebaILI9341::write |
Same as drawChar |
AmebaILI9341::getWidth |
Return the width 240 |
AmebaILI9341::getHeight |
Return the height 320 |
AmebaILI9341::setCursor |
Set cursor to the desired position |
AmebaILI9341::setForeground |
Set foreground color |
AmebaILI9341::setBackground |
Set background color |
AmebaILI9341::setFontSize |
Set character font size |
AmebaILI9341::reset |
Reset pin to High or Low |
AmebaILI9341::AmebaILI9341
Description
Constructs an AmebaILI9341 object and set CS, DC and RESET pins .
Syntax
AmebaILI9341::AmebaILI9341(int csPin, int dcPin, int resetPin)
Parameters
csPin: pin for Chip Select dcPin: pin for Data/Command resetPin: pin for Reset
Returns
The function returns nothing.
Example Code
Example: : PM25_ON_ILI9341_TFT_LCD
This example demonstrates how to read pm2.5 value on PMS 3003 air-condition sensor and display it on ILI9341 TFT LCD.
/*
PMS 3003 pin map is as follow:
PIN1 :VCC, connect to 5V
PIN2 :GND
PIN3 :SET, 0:Standby mode, 1:operating mode
PIN4 :RXD :Serial RX
PIN5 :TXD :Serial TX
PIN6 :RESET
PIN7 :NC
PIN8 :NC
In this example, we only use Serial to get PM 2.5 value.
The circuit:
* RX is digital pin 0 (connect to TX of PMS 3003)
* TX is digital pin 1 (connect to RX of PMS 3003)
For RTL8195A ILI9341 TFT LCD with SPI interface has these pins:
D/C : connect to pin 9
CS : connect to pin 10
MOSI : connect to pin 11
MISO : connect to pin 12
CLK : connect to pin 13
VCC : connect to 3V3
GND : connect to GND
*/
#include 「SoftwareSerial.h」
#include 「SPI.h」
#include 「AmebaILI9341.h」
#if defined(BOARD_RTL8195A)
SoftwareSerial mySerial(0, 1); // RX, TX
#define TFT_RESET 8
#define TFT_DC 9
#define TFT_CS 10
#elif defined(BOARD_RTL8710)
SoftwareSerial mySerial(17, 5); // RX, TX
// IMPORTANT: Due to limit pin, we do not connect TFT_RESET pin.
#define TFT_RESET 0xFFFFFFFF
#define TFT_DC 2
#define TFT_CS 10
#endif
AmebaILI9341 tft = AmebaILI9341(TFT_CS, TFT_DC, TFT_RESET);
#define ILI9341_SPI_FREQUENCY 20000000
#define pmsDataLen 32
uint8_t buf[pmsDataLen];
int idx = 0;
int pm10 = 0;
int last_pm25 = 0;
int pm25 = 0;
int pm100 = 0;
uint16_t pm25color[] = {
0x9FF3,
0x37E0,
0x3660,
0xFFE0,
0xFE60,
0xFCC0,
0xFB2C,
0xF800,
0x9800,
0xC99F
};
void setup() {
Serial.begin(57600);
mySerial.begin(9600); // PMS 3003 UART has baud rate 9600
SPI.setDefaultFrequency(ILI9341_SPI_FREQUENCY);
tft.begin();
drawPictureFrames();
}
void loop() { // run over and over
uint8_t c;
idx = 0;
memset(buf, 0, pmsDataLen);
while (true) {
while (c != 0x42) {
while (!mySerial.available());
c = mySerial.read();
}
while (!mySerial.available());
c = mySerial.read();
if (c == 0x4d) {
// now we got a correct header)
buf[idx++] = 0x42;
buf[idx++] = 0x4d;
break;
}
}
while (idx != pmsDataLen) {
while(!mySerial.available());
buf[idx++] = mySerial.read();
}
pm10 = ( buf[10] << 8 ) | buf[11];
last_pm25 = pm25;
pm25 = ( buf[12] << 8 ) | buf[13];
pm100 = ( buf[14] << 8 ) | buf[15];
updateValueToTftScreen();
}
void drawPictureFrames() {
tft.setRotation(1);
tft.clr();
tft.setFontSize(1);
// Upper title
tft.setFontSize(1);
tft.setCursor(20,20);
tft.print(「PM2.5 DETECTOR」);
// PM 2.5 Circle Frame
tft.drawCircle(100,130,60, ILI9341_BLUE);
tft.drawCircle(100,130,61, ILI9341_BLUE);
tft.setFontSize(1);
tft.setCursor(90,85);
tft.print(「PM2.5」);
tft.setFontSize(1);
tft.setCursor(90,170);
tft.print(「um/m3」);
// PM 10 Circle Frame
tft.drawCircle(220,70,40, ILI9341_BLUE);
tft.setFontSize(1);
tft.setCursor(210,40);
tft.print(「PM10」);
tft.setFontSize(1);
tft.setCursor(205,95);
tft.print(「um/m3」);
// PM 1.0 Circle Frame
tft.drawCircle(220,170,40, ILI9341_BLUE);
tft.setFontSize(1);
tft.setCursor(205,140);
tft.print(「PM1.0」);
tft.setFontSize(1);
tft.setCursor(205,195);
tft.print(「um/m3」);
// right side bar, referenced from: http://taqm.epa.gov.tw/taqm/tw/
tft.fillRectangle(290, 30+ 0*2, 10, 12*2, pm25color[0]); // 0~11
tft.fillRectangle(290, 30+12*2, 10, 12*2, pm25color[1]); // 12-23
tft.fillRectangle(290, 30+24*2, 10, 12*2, pm25color[2]); // 24-35
tft.fillRectangle(290, 30+36*2, 10, 6*2, pm25color[3]); // 36-41
tft.fillRectangle(290, 30+42*2, 10, 6*2, pm25color[4]); // 42-47
tft.fillRectangle(290, 30+48*2, 10, 6*2, pm25color[5]); // 48-53
tft.fillRectangle(290, 30+54*2, 10, 6*2, pm25color[6]); // 54-58
tft.fillRectangle(290, 30+59*2, 10, 6*2, pm25color[7]); // 59-64
tft.fillRectangle(290, 30+65*2, 10, 6*2, pm25color[8]); // 65-70
tft.fillRectangle(290, 30+71*2, 10, 10*2, pm25color[9]); // >=71
tft.setCursor(302, 30);
tft.setFontSize(1);
tft.print(「0」);
tft.setCursor(302, 30+36*2);
tft.print(「36」);
tft.setCursor(302, 30+54*2);
tft.print(「54」);
tft.setCursor(302, 30+71*2);
tft.print(「71」);
// bottom right text
tft.setCursor(210,230);
tft.setFontSize(1);
tft.print(「Powered by Realtek」);
updateValueToTftScreen();
}
void updateValueToTftScreen() {
tft.setCursor(60, 111);
tft.setFontSize(5);
tft.setForeground( getPm25Color(pm25) );
if (pm25 < 10) {
tft.print(」 「);
} else if (pm25 < 100) {
tft.print(」 「);
}
tft.print(pm25);
tft.setCursor(195,60);
tft.setFontSize(3);
if (pm100 < 10) {
tft.print(」 「);
} else if (pm100 < 100) {
tft.print(」 「);
}
tft.print(pm100);
tft.setCursor(198,160);
if (pm10 < 10) {
tft.print(」 「);
} else if (pm10 < 100) {
tft.print(」 「);
}
tft.print(pm10);
tft.setFontSize(1);
tft.setForeground(ILI9341_WHITE);
if (last_pm25 > 80) {
tft.fillRectangle(275, 80*2+30-3, 12, 8, ILI9341_BLACK);
} else {
tft.fillRectangle(275, last_pm25*2+30-3, 12, 8, ILI9341_BLACK);
}
if (pm25 > 80) {
tft.setCursor(275, 80*2+30-3);
} else {
tft.setCursor(275, pm25*2+30-3);
}
tft.print(「=>」);
}
uint16_t getPm25Color(int v) {
if (v < 12) {
return pm25color[0];
} else if (v < 24) {
return pm25color[1];
} else if (v < 36) {
return pm25color[2];
} else if (v < 42) {
return pm25color[3];
} else if (v < 48) {
return pm25color[4];
} else if (v < 54) {
return pm25color[5];
} else if (v < 59) {
return pm25color[6];
} else if (v < 65) {
return pm25color[7];
} else if (v < 71) {
return pm25color[8];
} else {
return pm25color[9];
}
}
Notes and Warnings
NA
AmebaILI9341::begin
Description
Initialize hardware SPI, pin mapping and screen configuration
Syntax
void AmebaILI9341::begin(void)
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
This method is required to run first before other operations on the display.
AmebaILI9341::setAddress
Description
Initialize image size and positioning on the display
Syntax
void AmebaILI9341::setAddress(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1)
Parameters
x0: leftmost coordinate of the image y0: top coordinate of the image x1: rightmost coordinate of the image y1: bottom coordinate of the image
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Do not use this to set the cursor, use the “setCursor” method instead.
AmebaILI9341::writecommand
Description
Write a single-byte command to display
Syntax
void AmebaILI9341::writecommand(uint8_t command)
Parameters
command: a single byte command
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::writedata
Description
Write 1 byte of data to display
Syntax
void AmebaILI9341::writedata(uint8_t data)
Parameters
data: 1 byte data
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Only use this method to write 1 byte at a time.
AmebaILI9341::setRotation
Description
Setting screen orientation, “0” for no rotation, “1” for 90 degrees rotation and so on so forth.
Syntax
void AmebaILI9341::setRotation(uint8_t m)/span> Parameters
m: one of the 4 rotation modes -> “0” for no rotation, “1” for 90⁰, “2” for 180⁰, “3” for 270⁰
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
if m=4, it’s equivalent to mode 0, and m=5 for mode 1, m=6 for mode 2 so on so forth.
AmebaILI9341::fillScreen
Description
Fill the entire screen with one color
Syntax
void AmebaILI9341::fillScreen(uint16_t color)
Parameters
color: a 16-bit color reference defined in AmebaILI9341.h
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Refer to AmebaILI9341.h for available colors.
AmebaILI9341::clr
Description
Fill the entire screen with a certain background-color
Syntax
void AmebaILI9341::clr(void)
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341
Notes and Warnings
background-color can be set by calling setBackground method.
AmebaILI9341::fillRectangle
Description
Fill a rectangular space with a color on the screen
Syntax
void AmebaILI9341::fillRectangle(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color)
Parameters
x: leftmost coordinate of the image y: top coordinate of the image w: width of the image h: height of the image color: the color of the image
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
NA
AmebaILI9341::drawPixel
Description
Turn on a pixel on the screen
Syntax
void AmebaILI9341::drawPixel(int16_t x, int16_t y, uint16_t color)
Parameters
x: leftmost coordinate of the image y: top coordinate of the image color: the color of the image
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::drawChar
Description
Draw character on the screen
Syntax
void AmebaILI9341::drawChar(unsigned char c) void AmebaILI9341::drawChar(int16_t x, int16_t y, unsigned char c, uint16_t _fontcolor, uint16_t _background, uint8_t _fontsize)
Parameters
x: leftmost coordinate of the image y: top coordinate of the image c: a character _fontcolor: font color _background: background color _fontsize: font size
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
In the actual example, the Print method is used to print a string of character on the screen instead of using this method.
AmebaILI9341::drawLine
Description
Draw a straight line on the screen
Syntax
void AmebaILI9341::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1) void AmebaILI9341::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t color)
Parameters
x0: leftmost coordinate of the image y0: top coordinate of the image x1: leftmost coordinate of the image y1: top coordinate of the image color: the color of the image
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::drawRectangle
Description
Draw a rectangular shape on the screen
Syntax
void AmebaILI9341::drawRectangle(int16_t x, int16_t y, int16_t w, int16_t h) void AmebaILI9341::drawRectangle(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color)
Parameters
x: leftmost coordinate of the image y: top coordinate of the image w: width of the image h: height of the image color: the color of the image
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::drawCircle
Description
Draw a circular shape on the screen
Syntax
void AmebaILI9341::drawCircle(int16_t x0, int16_t y0, int16_t r) void AmebaILI9341::drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color)
Parameters
x0: leftmost coordinate of the image y0: top coordinate of the image r: radius of the image color: the color of the image
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Include “AmebaServo.h” to use the class function.
AmebaILI9341::write
Description
Same as drawChar, write a character on the screen
Syntax
size_t AmebaILI9341::write(uint8_t c)
Parameters
c: a character to be written on the screen
Returns
Number of bytes written
Example Code
NA
Notes and Warnings
This an inherited method from Print class and is seldom used.
AmebaILI9341::getWidth
Description
Get the width of the image
Syntax
int16_t AmebaILI9341::getWidth(void)
Parameters
The function requires no input parameter.
Returns
Width of the image
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::getHeight
Description
Get the height of the image
Syntax
int16_t AmebaILI9341::getHeight(void)
Parameters
The function requires no input parameter.
Returns
Height of the image
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::setCursor
Description
Set the cursor to a specific position on the screen
Syntax
void AmebaILI9341::setCursor(int16_t x, int16_t y)
Parameters
x: coordinate on the x-axis y: coordinate on the y-axis
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
NA
AmebaILI9341::setForeground
Description
Set foreground color
Syntax
void AmebaILI9341::setForeground(uint16_t color)
Parameters
color: one of the colors available in AmebaILI9341.h
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
NA
AmebaILI9341::setBackground
Description
Set background color
Syntax
void AmebaILI9341::setBackground(uint16_t _background)
Parameters
_background: one of the colors available in AmebaILI9341.h
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
NA
AmebaILI9341::setFontSize
Description
Set the font size of the characters printed on the screen.
Syntax
void AmebaILI9341::setFontSize(uint8_t size)
Parameters
size: font size, default 1 for smallest, 5 for largest font size
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
NA
AmebaILI9341::reset
Description
Reset the pin to High or Low
Syntax
void AmebaILI9341::reset(void)
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
Class SPISettings_SPIClass
SPISettings Class
Members
Public Constructors |
|
---|---|
SPISettings::SPISettings |
Create a SPISettings object and set SPI clock speed, bit order and data mode |
SPISettings::SPISettings
SPIClass Class
Members
Public Constructors |
|
---|---|
SPIClass::SPIClass |
Constructs an SPI object |
Public Methods |
|
SPIClass::transfer |
Transfer data through SPI |
SPIClass::transfer16 |
Transfer a 16-bits data through SPI |
SPIClass::beginTransaction |
Set slave select pin and SPI initial settings |
SPIClass::endTransaction |
Stop SPI transaction |
SPIClass::begin |
Associate each SPI pin to Ameba pin using ameba HAL APIs |
SPIClass::end |
Stop SPI master mode |
SPIClass::setBitOrder |
Set MSB first or LSB first |
SPIClass::setDataMode |
Set to one of the four data modes |
SPIClass::setClockDivider |
Set to correct clock speed (no effect on Ameba) |
SPIClass::setDefaultFrequency |
Set default SPI frequency |
SPIClass::SPIClass
SPIClass::transfer
SPIClass::transfer16
SPIClass::beginTransaction
SPIClass::endTransaction
SPIClass::begin
SPIClass::end
SPIClass::setBitOrder
SPIClass::setDataMode
SPIClass::setClockDivider
SPIClass::setDefaultFrequency
Readme
The Ameba SPI related APIs and examples are works based on SPI Master library for arduino written by Cristian Maglie <c.maglie@arduino.cc> and Paul Stoffregen <paul@pjrc.com> (Transaction API).
These libraries are under GNU Lesser General Public License, version 2.1.
Sys
Wiring_OS_API
Wiring OS API
Members
Public Methods |
|
---|---|
os_thread_create_arduino |
Create a thread and add it to Active Threads and set it to state READY |
os_thread_get_id_arduino |
Return the thread ID of the current running thread |
os_thread_terminate_arduino |
Terminate execution of a thread and remove it from Active Threads |
os_thread_yield_arduino |
Pass control to next thread that is in state READY |
os_thread_set_priority_arduino |
Change priority of an active thread |
os_thread_get_priority_arduino |
Get current priority of an active thread |
os_signal_set_arduino |
Set the specified Signal Flags of an active thread |
os_signal_clear_arduino |
Clear the specified Signal Flags of an active thread |
os_signal_wait_arduino |
Wait for one or more Signal Flags to become signaled for the current RUNNING thread |
os_timer_create_arduino |
Create a timer |
os_timer_start_arduino |
Start or restart a timer |
os_timer_stop_arduino |
Stop the timer |
os_timer_delete_arduino |
Delete a timer that was created by os_timer_create |
os_semaphore_create_arduino |
Create and Initialize a Semaphore object used for managing resources |
os_semaphore_wait_arduino |
Wait until a Semaphore token becomes available |
os_semaphore_release_arduino |
Release a Semaphore token |
os_semaphore_delete_arduino |
Delete a Semaphore that was created by os_semaphore_create |
os_get_free_heap_size_arduino |
Return the available heap memory space when called |
os_thread_create_arduino
os_thread_get_id_arduino
os_thread_terminate_arduino
os_thread_yield_arduino
os_thread_set_priority_arduino
os_thread_get_priority_arduino
os_signal_set_arduino
os_signal_clear_arduino
os_signal_wait_arduino
os_timer_create_arduino
os_timer_start_arduino
os_timer_stop_arduino
os_timer_delete_arduino
os_semaphore_create_arduino
os_semaphore_wait_arduino
os_semaphore_release_arduino
os_semaphore_delete_arduino
os_get_free_heap_size_arduino
WDT
Class WDT
WDT Class
Members
Public Constructors |
|
---|---|
A public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named WDT. |
Public Methods |
|
---|---|
WDT:: InitWatchdog |
Initializes the watchdog, include time setting, and mode register |
WDT:: StartWatchdog |
Start the watchdog counting |
WDT:: StopWatchdog |
Stop the watchdog counting |
WDT:: RefreshWatchdog |
Refresh the watchdog counting to prevent WDT timeout |
WDT:: InitWatchdogIRQ |
Switch the watchdog timer to interrupt mode and register a watchdog timer timeout interrupt handler |
WDT:: InitWatchdog
/*
* This example describes how to use watchdog api.
* In this example, watchdog is setup to 5s timeout.
* Watchdog won’t bark if we refresh it before timeout in smallTask.
* The timer is also reloaded after refresh.
* Otherwise, while running bigTask, watchdog will restart system in default or call callback function if registered.
*/
#include 「wdt.h」
#define RUN_CALLBACK_IF_WATCHDOG_BARKS (0)
WDT wdt;
void setup() {
Serial.begin(115200);
wdt.InitWatchdog(5000); // setup 5s watchdog
#if RUN_CALLBACK_IF_WATCHDOG_BARKS
wdt.InitWatchdogIRQ(my_watchdog_irq_handler, 0);
#else
// system would restart in default when watchdog barks
#endif
wdt.StartWatchdog(); // enable watchdog timer
successfulTask();
failedTask();
while (1)
;
}
void loop() {
}
void successfulTask(void) {
Serial.println(」……doing small task……」);
for (int i = 0; i < 50000000; i++) // dummy task
asm(」 nop」);
Serial.println(「refresh watchdogrn」);
wdt.RefreshWatchdog();
}
/*
* Doing this task will lead to failed refresh the
* watchdog timer within the time limits of 5 seconds
*/
void failedTask(void) {
Serial.println(」……doing big task……」);
for (int i = 0; i < 10; i++) {
Serial.print(「doing dummy task #」);
Serial.println(i, DEC);
for (int j = 0; j < 50000000; j++) // dummy task
asm(」 nop」);
}
Serial.println(「refresh watchdogrn」);
wdt.RefreshWatchdog();
}
void my_watchdog_irq_handler(uint32_t id) {
printf(「watchdog barks!!!rn」);
WDG_Cmd(DISABLE);
}
WDT:: StartWatchdog
WDT:: StopWatchdog
WDT:: RefreshWatchdog
WDT:: InitWatchdogIRQ
WiFi
Class WiFi
WiFiClass Class
Members
Public Constructors |
|
---|---|
WiFiClass::WiFiClass |
Constructs a WiFiClass object and initializes the WiFi libraries and network settings |
Public Methods |
|
WiFiClass::firmwareVersion |
Get firmware version |
WiFiClass:: begin |
Start Wifi connection for OPEN networks |
WiFiClass:: config |
Configure network IP settings |
WiFiClass:: setDNS |
Set the DNS server IP address to use |
WiFiClass:: disconnect |
Disconnect from the network |
WiFiClass:: macAddress |
Get the interface MAC address |
WiFiClass:: localIP |
Get the interface IP address |
WiFiClass:: subnetMask |
Get the interface subnet mask address |
WiFiClass:: gatewayIP |
Get the gateway IP address |
WiFiClass:: SSID |
Return the current SSID associated with the network |
WiFiClass:: BSSID |
Return the current BSSID associated with the network |
WiFiClass:: RSSI |
Return the current RSSI (Received Signal Strength in dBm) associated with the network |
WiFiClass:: encryptionType |
Return the Encryption Type associated with the network |
WiFiClass:: scanNetworks |
Start scan WiFi networks available |
WiFiClass:: SSID |
Return the SSID discovered during the network scan |
WiFiClass:: encryptionType |
Return the encryption type of the networks discovered during the scanNetworks |
WiFiClass:: encryptionTypeEx |
Return the security type and encryption type of the networks discovered during the scanNetworks |
WiFiClass:: RSSI |
Return the RSSI of the networks discovered during the scanNetworks |
WiFiClass:: status |
Return Connection status |
WiFiClass:: hostByName |
Resolve the given hostname to an IP address |
WiFiClass:: apbegin |
Start AP mode |
WiFiClass:: disablePowerSave |
Disable power-saving mode |
WiFiClass::WiFiClass
WiFiClass::firmwareVersion
#include <WiFi.h>
// char ssid[] = 「yourNetwork」; // your network SSID (name)
// char pass[] = 「secretPassword」; // your network password
char ssid[] = 「SINGTEL-D45F」; // your network SSID (name)
char pass[] = 「mooxuteeth」; // your network key
int status = WL_IDLE_STATUS; // the Wifi radio’s status
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to WPA SSID: 「);
Serial.println(ssid);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// you’re connected now, so print out the data:
Serial.print(「You’re connected to the network」);
printCurrentNet();
printWifiData();
}
void loop() {
// check the network connection once every 10 seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print(「MAC address: 「);
Serial.print(mac[0], HEX);
Serial.print(「:」);
Serial.print(mac[1], HEX);
Serial.print(「:」);
Serial.print(mac[2], HEX);
Serial.print(「:」);
Serial.print(mac[3], HEX);
Serial.print(「:」);
Serial.print(mac[4], HEX);
Serial.print(「:」);
Serial.println(mac[5], HEX);
}
void printCurrentNet() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print the MAC address of the router you’re attached to:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print(「BSSID: 「);
Serial.print(bssid[5], HEX);
Serial.print(「:」);
Serial.print(bssid[4], HEX);
Serial.print(「:」);
Serial.print(bssid[3], HEX);
Serial.print(「:」);
Serial.print(bssid[2], HEX);
Serial.print(「:」);
Serial.print(bssid[1], HEX);
Serial.print(「:」);
Serial.println(bssid[0], HEX);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.println(rssi);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print(「Encryption Type:」);
Serial.println(encryption, HEX);
Serial.println();
}
WiFiClass::begin
WiFiClass::config
WiFiClass::setDNS
WiFiClass::disconnect
WiFiClass::macAddress
WiFiClass::localIP
WiFiClass::subnetMask
#include <WiFi.h>
char ssid[] = 「SINGTEL-D45F_5G」; // the name of your network
int status = WL_IDLE_STATUS; // the Wifi radio’s status
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to open SSID: 「);
Serial.println(ssid);
status = WiFi.begin(ssid);
// wait 10 seconds for connection:
delay(10000);
}
// you’re connected now, so print out the data:
Serial.print(「You’re connected to the network」);
printCurrentNet();
printWifiData();
}
void loop() {
// check the network connection once every 10 seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print(「MAC address: 「);
Serial.print(mac[0], HEX);
Serial.print(「:」);
Serial.print(mac[1], HEX);
Serial.print(「:」);
Serial.print(mac[2], HEX);
Serial.print(「:」);
Serial.print(mac[3], HEX);
Serial.print(「:」);
Serial.print(mac[4], HEX);
Serial.print(「:」);
Serial.println(mac[5], HEX);
// print your subnet mask:
IPAddress subnet = WiFi.subnetMask();
Serial.print(「NetMask: 「);
Serial.println(subnet);
// print your gateway address:
IPAddress gateway = WiFi.gatewayIP();
Serial.print(「Gateway: 「);
Serial.println(gateway);
}
void printCurrentNet() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print the MAC address of the router you’re attached to:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print(「BSSID: 「);
Serial.print(bssid[5], HEX);
Serial.print(「:」);
Serial.print(bssid[4], HEX);
Serial.print(「:」);
Serial.print(bssid[3], HEX);
Serial.print(「:」);
Serial.print(bssid[2], HEX);
Serial.print(「:」);
Serial.print(bssid[1], HEX);
Serial.print(「:」);
Serial.println(bssid[0], HEX);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.println(rssi);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print(「Encryption Type:」);
Serial.println(encryption, HEX);
}
WiFiClass::gatewayIP
WiFiClass::SSID
WiFiClass::BSSID
WiFiClass::RSSI
WiFiClass::encryptionType
WiFiClass::scanNetworks
#include <WiFi.h>
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// Print WiFi MAC address:
printMacAddress();
}
void loop() {
// scan for existing networks:
Serial.println(「Scanning available networks…」);
listNetworks();
delay(10000);
}
void printMacAddress() {
// the MAC address of your Wifi shield
byte mac[6];
// print your MAC address:
WiFi.macAddress(mac);
Serial.print(「MAC: 「);
Serial.print(mac[0], HEX);
Serial.print(「:」);
Serial.print(mac[1], HEX);
Serial.print(「:」);
Serial.print(mac[2], HEX);
Serial.print(「:」);
Serial.print(mac[3], HEX);
Serial.print(「:」);
Serial.print(mac[4], HEX);
Serial.print(「:」);
Serial.println(mac[5], HEX);
}
void listNetworks() {
// scan for nearby networks:
Serial.println(」* Scan Networks *」);
int numSsid = WiFi.scanNetworks();
if (numSsid == -1) {
Serial.println(「Couldn’t get a wifi connection」);
while (true);
}
// print the list of networks seen:
Serial.print(「number of available networks:」);
Serial.println(numSsid);
// print the network number and name for each network found:
for (int thisNet = 0; thisNet < numSsid; thisNet++) {
Serial.print(thisNet);
Serial.print(」) 「);
Serial.print(WiFi.SSID(thisNet));
Serial.print(」tSignal: 「);
Serial.print(WiFi.RSSI(thisNet));
Serial.print(」 dBm」);
Serial.print(」tEncryptionRaw: 「);
printEncryptionTypeEx(WiFi.encryptionTypeEx(thisNet));
Serial.print(」tEncryption: 「);
printEncryptionType(WiFi.encryptionType(thisNet));
}
}
void printEncryptionTypeEx(uint32_t thisType) {
/* Arduino wifi api use encryption type to mapping to security type.
* This function demonstrate how to get more richful information of security type.
*/
switch (thisType) {
case SECURITY_OPEN:
Serial.print(「Open」);
break;
case SECURITY_WEP_PSK:
Serial.print(「WEP」);
break;
case SECURITY_WPA_TKIP_PSK:
Serial.print(「WPA TKIP」);
break;
case SECURITY_WPA_AES_PSK:
Serial.print(「WPA AES」);
break;
case SECURITY_WPA2_AES_PSK:
Serial.print(「WPA2 AES」);
break;
case SECURITY_WPA2_TKIP_PSK:
Serial.print(「WPA2 TKIP」);
break;
case SECURITY_WPA2_MIXED_PSK:
Serial.print(「WPA2 Mixed」);
break;
case SECURITY_WPA_WPA2_MIXED:
Serial.print(「WPA/WPA2 AES」);
break;
}
}
void printEncryptionType(int thisType) {
// read the encryption type and print out the name:
switch (thisType) {
case ENC_TYPE_WEP:
Serial.println(「WEP」);
break;
case ENC_TYPE_TKIP:
Serial.println(「WPA」);
break;
case ENC_TYPE_CCMP:
Serial.println(「WPA2」);
break;
case ENC_TYPE_NONE:
Serial.println(「None」);
break;
case ENC_TYPE_AUTO:
Serial.println(「Auto」);
break;
}
}
WiFiClass::SSID
WiFiClass::encryptionType
WiFiClass::encryptionTypeEx
WiFiClass::RSSI
WiFiClass::status
WiFiClass::hostByName
WiFiClass::apbegin
#include
char ssid[] = 「yourNetwork」; //Set the AP’s SSID
char pass[] = 「Password」; //Set the AP’s password
char channel[] = 「1」; //Set the AP’s channel
int status = WL_IDLE_STATUS; // the Wifi radio’s status
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// attempt to start AP:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to start AP with SSID: 「);
Serial.println(ssid);
status = WiFi.apbegin(ssid, pass, channel);
delay(10000);
}
//AP MODE already started:
Serial.println(「AP mode already started」);
Serial.println();
printWifiData();
printCurrentNet();
}
void loop() {
// check the network connection once every 10 seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print your subnet mask:
IPAddress subnet = WiFi.subnetMask();
Serial.print(「NetMask: 「);
Serial.println(subnet);
// print your gateway address:
IPAddress gateway = WiFi.gatewayIP();
Serial.print(「Gateway: 「);
Serial.println(gateway);
Serial.println();
}
void printCurrentNet() {
// print the SSID of the AP:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print the MAC address of AP:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print(「BSSID: 「);
Serial.print(bssid[0], HEX);
Serial.print(「:」);
Serial.print(bssid[1], HEX);
Serial.print(「:」);
Serial.print(bssid[2], HEX);
Serial.print(「:」);
Serial.print(bssid[3], HEX);
Serial.print(「:」);
Serial.print(bssid[4], HEX);
Serial.print(「:」);
Serial.println(bssid[5], HEX);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print(「Encryption Type:」);
Serial.println(encryption, HEX);
Serial.println();
}
WiFiClass::disablePowerSave
Class WiFiClient
WiFiClient Class
Members
Public Constructors |
|
---|---|
WiFiClient::WiFiClient |
Constructs a WiFiClient instance that connects to the specified IP address and port. |
Public Methods |
|
WiFiClient::connect |
Connect to the IP address and port |
WiFiClient::write |
Write a single byte into the packet |
WiFiClient::available |
Number of bytes remaining in the current packet |
WiFiClient::read |
Read a single byte from the current packet |
WiFiClient:: peek |
Return the next byte from the current packet without moving on to the next byte |
WiFiClient:: flush |
Finish reading the current packet |
WiFiClient::stop |
Stop client connection |
WiFiClient::connected |
Check if client is connected, return 1 if connected, 0 if not |
WiFiClient::setRecvTimeout |
Set receiving timeout |
WiFiClient::WiFiClient
#include <WiFi.h>
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「password」; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
//IPAddress server(64,233,189,94); // numeric IP for Google (no DNS)
char server[] = 「www.google.com」; // name address for Google (using DNS)
WiFiClient client;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
;
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to SSID: 「);
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(「Connected to wifi」);
printWifiStatus();
Serial.println(」nStarting connection to server…」);
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println(「connected to server」);
// Make a HTTP request:
client.println(「GET /search?q=ameba HTTP/1.1」);
client.println(「Host: www.google.com」);
client.println(「Connection: close」);
client.println();
}
}
void loop() {
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// if the server’s disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println(「disconnecting from server.」);
client.stop();
// do nothing forevermore:
while (true);
}
}
void printWifiStatus() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.print(rssi);
Serial.println(」 dBm」);
}
WiFiClient::connect
WiFiClient::write
WiFiClient::available
WiFiClient::read
WiFiClient::peek
WiFiClient::flush
WiFiClient::stop
WiFiClient::connected
WiFiClient::setRecvTimeout
Class WiFiServer
WiFiServer Class
Members
Public Constructors |
|
---|---|
WiFiServer::WiFiServer |
Constructs a WiFiServer object and creates a server that listens for incoming connections on the specified port |
Public Methods |
|
WiFiServer::available |
Gets a client that is connected to the server and has data available for reading. The connection persists when the returned client object goes out of scope; you can close it by calling the client.stop() |
WiFiServer::begin |
Tells the server to begin listening for incoming connections |
WiFiServer::write |
Write data to all the clients connected to a server |
WiFiServer::WiFiServer
#include <WiFi.h>
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「secretPassword」; // your network password
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(5000);
void setup() {
Serial.begin(9600); // initialize serial communication
pinMode(9, OUTPUT); // set the LED pin mode
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
while (true); // don’t continue
}
String fv = WiFi.firmwareVersion();
if ( fv != 「1.1.0」 )
Serial.println(「Please upgrade the firmware」);
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print(「Attempting to connect to Network named: 「);
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
server.begin(); // start the tcp server on port 5000
printWifiStatus(); // you’re connected now, so print out the status
}
char buffer[256];
void loop() {
WiFiClient client = server.available();
while (client.connected()) {
memset(buffer, 0, 256);
int n = client.read((uint8_t*)(&buffer[0]), sizeof(buffer));
if (n > 0) {
for (int i=0; i<n; i++) {
Serial.print(buffer[i]);
}
n = client.write(buffer, n);
if (n <= 0) break;
}
}
client.stop();
}
void printWifiStatus() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.print(rssi);
Serial.println(」 dBm」);
}
WiFiServer::available
WiFiServer::begin
WiFiServer::write
Class WiFiSSLClient
WiFiSSLClient Class
Members
Public Constructors |
|
---|---|
WiFiSSLClient::WiFiSSLClient |
Constructs a WiFiSSLClient instance that always connects in SSL to the specified IP address and port |
Public Methods |
|
WiFiSSLClient::connect |
Connect to the IP address and port |
WiFiSSLClient::write |
Write a single byte into the packet |
WiFiSSLClient::available |
Number of bytes remaining in the current packet |
WiFiSSLClient::read |
Read a single byte from the current packet |
WiFiSSLClient:: peek |
Return the next byte from the current packet without moving on to the next byte |
WiFiSSLClient:: flush |
Finish reading the current packet |
WiFiSSLClient::stop |
Stop SSL client connection |
WiFiSSLClient::connected |
Check if SSL client is connected, return 1 if connected, 0 if not |
WiFiSSLClient:: setRootCA |
Set Root CA for authentication |
WiFiSSLClient:: setClientCertificate |
Set certificate of the client |
WiFiSSLClient::setRecvTimeout |
Set receiving timeout |
WiFiSSLClient::setPreSharedKey |
Set the pre shared key (PSK) to use for authentication |
WiFiSSLClient::WiFiSSLClient
#include
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「secretPassword」;// your network password (use for WPA, or WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
char server[] = 「www.google.com」; // name address for Google (using DNS)
//unsigned char test_client_key[] = 「」; //For the usage of verifying client
//unsigned char test_client_cert[] = 「」; //For the usage of verifying client
//unsigned char test_ca_cert[] = 「」; //For the usage of verifying server
WiFiSSLClient client;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to SSID: 「);
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid,pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(「Connected to wifi」);
printWifiStatus();
Serial.println(」nStarting connection to server…」);
// if you get a connection, report back via serial:
if (client.connect(server, 443)) { //client.connect(server, 443, test_ca_cert, test_client_cert, test_client_key)
Serial.println(「connected to server」);
// Make a HTTP request:
client.println(「GET /search?q=realtek HTTP/1.0」);
client.println(「Host: www.google.com」);
client.println(「Connection: close」);
client.println();
}
else
Serial.println(「connected to server failed」);
}
void loop() {
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// if the server’s disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println(「disconnecting from server.」);
client.stop();
// do nothing forevermore:
while (true);
}
}
void printWifiStatus() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print(「MAC address: 「);
Serial.print(mac[0], HEX);
Serial.print(「:」);
Serial.print(mac[1], HEX);
Serial.print(「:」);
Serial.print(mac[2], HEX);
Serial.print(「:」);
Serial.print(mac[3], HEX);
Serial.print(「:」);
Serial.print(mac[4], HEX);
Serial.print(「:」);
Serial.println(mac[5], HEX);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.print(rssi);
Serial.println(」 dBm」);
}
WiFiSSLClient::connect
WiFiSSLClient::write
WiFiSSLClient::available
WiFiSSLClient::read
WiFiSSLClient::peek
WiFiSSLClient::flush
WiFiSSLClient::stop
WiFiSSLClient::connected
WiFiSSLClient::setRootCA
WiFiSSLClient::setClientCertificate
WiFiSSLClient::setRecvTimeout
WiFiSSLClient::setPreSharedKey
Class WiFiUdp
WiFiUDP Class
Members
Public Constructors |
|
---|---|
WiFiUDP::WiFiUDP |
Constructs a WiFiUDP instance of the WiFi UDP class that can send and receive UDP messages |
Public Methods |
|
WiFiUDP:: begin |
initialize, start listening on the specified port. Returns 1 if successful, 0 if there are no sockets available to use |
WiFiUDP:: stop |
Finish with the UDP socket |
WiFiUDP:: beginPacket |
Start building up a packet to send to the remote host-specific in IP and port |
WiFiUDP:: endPacket |
Finish off this packet and send it |
WiFiUDP:: write |
Write a single byte into the packet |
WiFiUDP:: writeImmediately |
Send packet immediately from the buffer |
WiFiUDP:: parsePacket |
Start processing the next available incoming packet |
WiFiUDP::available |
Number of bytes remaining in the current packet |
WiFiUDP::read |
Read a single byte from the current packet |
WiFiUDP:: peek |
Return the next byte from the current packet without moving on to the next byte |
WiFiUDP:: flush |
Finish reading the current packet |
WiFiUDP:: remoteIP |
Return the IP address of the host who sent the current incoming packet |
WiFiUDP:: remotePort |
Return the port of the host who sent the current incoming packet |
WiFiUDP:: setRecvTimeout |
Set receiving timeout |
WiFiUDP::WiFiUDP
#include <WiFi.h>
#include <WiFiUdp.h>
int status = WL_IDLE_STATUS;
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「secretPassword」; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
unsigned int localPort = 2390; // local port to listen on
char packetBuffer[255]; //buffer to hold incoming packet
char ReplyBuffer[] = 「acknowledged」; // a string to send back
WiFiUDP Udp;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to SSID: 「);
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid,pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(「Connected to wifi」);
printWifiStatus();
Serial.println(」nStarting connection to server…」);
// if you get a connection, report back via serial:
Udp.begin(localPort);
}
void loop() {
// if there’s data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize) {
Serial.print(「Received packet of size 「);
Serial.println(packetSize);
Serial.print(「From 「);
IPAddress remoteIp = Udp.remoteIP();
Serial.print(remoteIp);
Serial.print(」, port 「);
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
int len = Udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
}
Serial.println(「Contents:」);
Serial.println(packetBuffer);
// send a reply, to the IP address and port that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
}
}
void printWifiStatus() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.print(rssi);
Serial.println(」 dBm」);
}
WiFiUDP::begin
WiFiUDP::stop
WiFiUDP::beginPacket
WiFiUDP::endPacket
WiFiUDP::write
WiFiUDP::writeImmediately
WiFiUDP::parsePacket
WiFiUDP::available
WiFiUDP::read
WiFiUDP::peek
WiFiUDP::flush
WiFiUDP::remoteIP
WiFiUDP::remotePort
WiFiUDP::setRecvTimeout
Readme
WiFi.cpp
WiFi.h
WiFiServer.cpp
WiFiServer.h
WiFiUdp.cpp
WiFiUdp.h
Wire
Class TwoWire
TwoWire Class
Members
Public Constructors |
|
---|---|
TwoWire::TwoWire |
Constructs a TwoWire object |
Public Methods |
|
TwoWire::begin |
Initialize I2C master/slave |
TwoWire::setClock |
Set I2C frequency |
TwoWire::beginTransmission |
Begin I2C transmission |
TwoWire::endTransmission |
End I2C transmission |
TwoWire::requestFrom |
Set I2C requestFrom |
TwoWire::write |
Write data to I2C |
TwoWire::available |
Check if I2C is available |
TwoWire::read |
Read data from I2C |
TwoWire::peek |
Read peek from I2C |
TwoWire::flush |
Do nothing, use, and transmission(..) to force data transfer |
TwoWire::onReceive |
Callback function when I2C on receive |
TwoWire::onRequest |
Callback function when I2C on request |
TwoWire::TwoWire
#include <Wire.h>
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
}
byte x = 0;
void loop() {
Wire.beginTransmission(8); // transmit to device #8
Wire.write(「x is 「); // sends five bytes
Wire.write(x); // sends one byte
Wire.endTransmission(); // stop transmitting
x++;
delay(500);
}
Example: MasterReader
#include <Wire.h>
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output
}
void loop() {
Wire.requestFrom(8, 6); // request 6 bytes from slave device #8
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);
}
This example demonstrates the use of the wire library reads data from an I2C/TWI slave device.
TwoWire::begin
TwoWire::setClock
TwoWire::beginTransmission
TwoWire::endTransmission
WARNING: Nothing in the library keeps track of whether the bus tenure has been properly ended with a STOP. It is very possible to leave the bus in a hung state if no call to endTransmission(true) is made. Some I2C devices will behave oddly if they do not see a STOP.
If the input parameter is void, this provides backward compatibility with the original definition, and expected behavior, of endTransmission.
TwoWire::requestFrom
TwoWire::write
TwoWire::available
TwoWire::read
TwoWire::peek
TwoWire::flush
TwoWire::onReceive
TwoWire::onRequest
Wire_Readme
The Ameba LCD related api and example are works based on “New LiquidCrystal library” (https://bitbucket.org/fmalpartida/new-liquidcrystal/).
These include,
These files inherit the licence of “New LiquidCrystal Library” which are under a Creative Commons Attribution-ShareAlike 3.0 Unported License. CC BY-SA 3.0.
Resources
Links
支援
常見問題
如何購買 Ameba RTL8722DM Board?
請參考 購買連結。
RTL8722CSM/RTL8722DM 支持哪些藍牙標準?
兩者皆支援 BLE 5.0。 Classic Bluetooth (BR/EDR) 則不支援。
支持哪些BLE設備?
RTL8722CSM/RTL8722DM 可當作 BLE Central 或 BLE Peripheral 設備。
RTL8722CSM /RTL8722DM上的所有接腳都可用嗎?
不,標有“NC”的未連接到任何接腳,因此無法使用。
RTL8722CSM/RTL8722DM 有支援 XIP (execute in place)嗎?
有支援。
RTL8722CSM 有支援 5G WiFi 嗎?
不,只有 RTL8722DM 支援雙頻 2.4G + 5G WiFi。 RTL8722CSM 只有支援單頻 2.4G WiFi。
如何進入下載模式?
按住UART DOWNLOAD按鈕,然後按下RESET按鈕並放開UART DOWNLOAD和RESET按鈕。
故障排除
無法找到藍牙裝置RTL8722CSM/RTL8722DM
請確保天線連接正確。 檢查您的程式碼有確認正確的藍牙配置。
程式碼操作不如預期
嘗試使用``printf()`` 和
Serial.print()
語法除錯。 如果問題仍然存在,您可以在論壇尋求幫助
連接到RTL8722CSM / RTL8722DM UART後,為什麼串行終端上沒有輸出?
RTL8722CSM / RTL8722DM 默認配置為115200波特率,請檢查串行終端是否配置為115200。
程序無法下載到RTL8722CSM / RTL8722DM中
- 請按照以下步驟正確下載。
請進入下載模式。 進入下載模式時,開發版綠色LED指示燈將閃爍。
下載過程中,開發版紅色LED指示燈將閃爍。
下載成功後,Arduino IDE會出現通知。
WiFi有時信號較弱
RTL8722CSM / RTL8722DM 的預設天線使用I-Pex連接器。 請更換/連接I-Pex連接器天線。
為什麼開發版無法上電?
請確認已連接電阻R43旁的連接器J38。 該連接器用於將電源鏈接到IC。
遇到開發板連接到電腦的驅動程式問題?
請參考下列USB 驅動程式 https://ftdichip.com/drivers /。
Ameba RTL8722DM MINI
Welcome to Ameba RTL8722DM MINI Arduino online documentation.
入門手冊
Ameba ARDUINO:RTL8722DM MINI 入門手冊
工作環境
AmebaD RTL8722DM MINI 開發板目前支持 Windows OS 32 位元和 64 位元(WIN7/8/10)、Linux OS(Ubuntu 18 LTS/20 LTS/最新)和 macOS 作業系統。請使用最新的作業系統版本以獲得最佳體驗。在本文檔中,請使用最新版本的 Arduino IDE(至少 1.8.12 版)。
AmebaD RTL8722DM MINI 介紹
Ameba是一個易於編程的微控制器平台,可用於開發各種物聯網應用程序。AmebaD有各種外圍接口,包括WiFi, GPIO INT, I2C, UART, SPI, PWM, ADC。通過這些接口,AmebaD可以連接LED、開關、壓力計、濕度計、PM2.5粉塵傳感器等電子元件。
Ameba所收集的數據可以通過WiFi無線上傳,並被智能設備上的應用程序使用,實現物聯網的應用。
AmebaD 和 Arduino UNO 的尺寸類似,如上圖所示。
# |
PIN name |
GPIO INT |
ADC |
PWM |
UART |
SPI |
I2C |
---|---|---|---|---|---|---|---|
D0 |
GPIOB_0 |
✓ |
I2C0 SDA |
||||
D1 |
GPIOB_1 |
✓ |
A4 |
Serial2_TX |
|||
D2 |
GPIOB_2 |
✓ |
A5 |
Serial2_RX |
|||
D3 |
GPIOB_3 |
✓ |
A6 |
||||
D4 |
GPIOB_4 |
✓ |
A0 |
✓ |
|||
D5 |
GPIOB_5 |
✓ |
A1 |
✓ |
I2C0 SCL |
||
D6 |
GPIOB_6 |
✓ |
A2 |
I2C0 SDA |
|||
D7 |
GPIOB_7 |
✓ |
A3 |
✓ |
|||
D8 |
GPIOA_2 |
✓ |
|||||
D9 |
GPIOA_12 |
✓ |
✓ |
Serial2_TX |
SPI1_MOSI |
||
D10 |
GPIOA_13 |
✓ |
✓ |
Serial2_RX |
SPI1_MISO |
||
D11 |
GPIOA_14 |
✓ |
SPI1_CLK |
||||
D12 |
GPIOA_15 |
✓ |
SPI1_CS |
||||
D13 |
GPIOA_16 |
✓ |
|||||
D14 |
GPIOA_28 |
✓ |
✓ |
||||
D15 |
GPIOA_18 |
✓ |
Serial1_TX |
||||
D16 |
GPIOA_19 |
✓ |
Serial1_RX |
||||
D17 |
GPIOA_30 |
✓ |
✓ |
||||
D18 |
GPIOA_21 |
✓ |
Serial1_TX |
||||
D19 |
GPIOA_22 |
✓ |
Serial1_RX |
||||
D20 |
GPIOA_23 |
✓ |
✓ |
||||
D21 |
GPIOA_24 |
✓ |
✓ |
||||
D22 |
GPIOA_31 |
✓ |
I2C0 SCL |
設置開發環境
步驟一、安裝驅動程序
首先,通過 Micro USB 將 RTL8722DM MINI 連接到電腦:
步驟二、設置 Arduino IDE
並將以下網址粘貼到 “Additional Boards Manager URLs” 欄位:
https://github.com/ambiot/ambd_arduino/raw/master/Arduino_package/package_realtek.com_amebad_index.json
接下來,選擇 “Tools” -> “Board” -> “Boards Manager”:
“Boards Manager”大約需要10~20秒來刷新所有硬件文件(如果網絡狀況不好,可能需要更長的時間)。每次連接新硬件時,我們都需要重新打開Boards Manager。因此,我們先關閉然後再次打開它。在列表中找到“Realtek AmebaD Boards (32-bits ARM Cortex-M33 @200MHz)”,點擊“Install”,Arduino IDE會自動開始下載AmebaD所需的文件。
AmebaD_Arduino_patch1_SDK”,請至少選擇 1 個 SDK。目前有 5 個最新發布的 SDK 選項。
“AmebaD_Arduino_patch2_Tools”,請根據您的作業系統進行選擇。有 Windows、Linux 和 MacOS。
“AmebaD_Arduino_Source_Code”,此部分為可選下載,用來參考最新原始碼。
下載選擇的文件,然後解壓(patch1 和patch2 是必須的)。有“Install_中文.doc”/“Install_中文.pdf”供您參考安裝步驟。根據您的系統,請運行“Offline_SDK_installation_tool”文件夾中的安裝工具。
安裝工具運行成功後,您可以打開Arduino IDE並選擇 “tools” -> “Board“ -> “Boards Manager…”。嘗試在列表中找到“Realtek AmebaD Boards (32-bits ARM Cortex-M33 @200MHz)”,點擊“Install”,Arduino IDE開始下載AmebaD所需的文件。
最後,我們在“tools”->“Board”->“Ameba ARM (32-bits) Boards”->“RTL8722DM MINI”中選擇了AmebaD作為當前連接的開發板:
嘗試第一個範例
步驟一、編譯和上傳
Arduino IDE 打開一個帶有完整示例代碼的新視窗。
接下來,我們直接編譯示例代碼,點擊 “Sketch” -> “Verify/Compile”
Arduino IDE在IDE窗口的底部區域打印編譯消息。編譯完成後,會得到如下圖所示的消息:
想要進入上傳模式,首先按住UART_DOWNLOAD按鈕不放,然後輕按RESET按鈕。上傳成功后,你可以看到板載的綠色和藍色 LED熄滅。
用戶可選擇檢查開發板是否進入上傳模式。 打開串行監視器並查找“#Flash Download Start”。請注意,某些串口終端可能會顯示如下圖所示的未知字符是正常的。
同樣,在上傳過程中IDE會自動顯示消息。上傳過程需要相當長的時間 (大約30秒到1分鐘)。上傳完成後,您會看到 “Done uploading” 消息。
步驟二、運行 Blink 示例
(End)
備註
如果您遇到任何問題,請參考 支援 。
Peripherals & Examples
Basic Examples
Ameba ARDUINO: [RTL8722CSM][RTL8722DM] Supported ARDUINO built-in example list
There are many built-in examples in Arduino. In the table below, we list all examples that are compatible with Ameba.
Category |
Name |
Comment |
---|---|---|
01.Basics |
AnalogReadSerial |
Connect potentiometer to 3.3V |
BareMinimum |
||
Blink |
Connect LED to pin 8 |
|
DigitalReadSerial |
||
Fade |
||
ReadAnalogVoltage |
ADC can read a maximum of 3.3V. |
|
02.Digital |
BlinkWithoutDelay |
Connect LED to pin 8 |
Button |
Connect LED to pin 13 |
|
Debounce |
Connect LED to pin 13 |
|
DigitalInputPullup |
Connect LED to pin 13 |
|
StateChangeDetection |
Connect LED to pin 13 |
|
toneKeyboard |
||
toneMelody |
||
toneMultiple |
||
tonePitchFollower |
||
03.Analog |
AnalogInOutSerial |
|
AnalogInput |
Connect LED to pin 13 |
|
Analog Write Mega |
||
Calibration |
Connect another LED to pin 13 |
|
Fading |
||
Smoothing |
||
04.Communication |
ASCIITable |
|
Dimmer |
Use serial baud rate 115200 |
|
Graph |
Use serial baud rate 115200, Connect potentiometer to 3.3V |
|
Midi |
Please use Serial1 and pin 26, or use Serial2 and pin 17 |
|
MultiSerial |
||
PhysicalPixel |
Use serial baud rate 115200 |
|
ReadASCIIString |
||
SerialCallResponse |
Use serial baud rate 115200 |
|
Serial CallResponseASCII |
Use serial baud rate 115200 |
|
SerialEvent |
||
SerialPassthrough |
||
VirtualColorMixer |
Use serial baud rate 115200 |
|
05.Control |
Arrays |
Use pins 1, 2, 3, 4, 5, 6 |
ForLoopIteration |
Use pins 1, 2, 3, 4, 5, 6 |
|
IfStatementConditional |
||
switchCase |
||
switchCase2 |
||
While StatementConditional |
Connect another LED to pin 13 |
|
06.Display |
barGraph |
Use another pin to replace pin 7 |
RowColumnScanning |
||
07.Strings |
CharacterAnalysis |
|
String AdditionOperator |
||
StringAppendOperator |
||
StringCaseChanges |
||
StringCharacters |
||
String ComparisonOperators |
||
StringIndexOf |
||
StringLength |
||
StringLengthTrim |
||
StringReplace |
||
String StartsWithEndsWith |
||
StringSubstring |
||
StringToInt |
Network Examples
Scan Available WiFi Hotspots in The Surroundings
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Antenna x 1
Example
“Tools” -> “Board”
“File” -> “Examples” -> “AmebaWiFi” -> “ScanNetworks”
:Then upload the sample code and press the reset button on Ameba. Afterwards, you can see “**Scan Networks**” message appears, with the detected WiFi hotspots and the information of each hotspot.
Code Reference
First we use
WiFi.macAddress(mac)
to get the MAC address of Ameba: https://www.arduino.cc/en/Reference/WiFiMACAddressThen we use
WiFi.scanNetworks()
to detect WiFi hotspots: https://www.arduino.cc/en/Reference/WiFiScanNetworksTo get information of detected WiFi hotspot: We use
WiFi.SSID(thisNet)
to retrieve SSID of a network: https://www.arduino.cc/en/Reference/WiFiSSID We useWiFi.RSSI(thisNet)
to get the signal strength of the connection to the router: https://www.arduino.cc/en/Reference/WiFiRSSIWe use
WiFi.encryptionType(thisNet)
to get the encryption type of the network: https://www.arduino.cc/en/Reference/WiFiEncryptionType
Comparison with Arduino
#include
to
use SPI to communicate with WiFi module.#include
is not needed.Connect to WiFi
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Procedure
There three common encryption type in WiFi connection. The first one is “OPEN”, which means there is no password needed to connect to this network. The second type of encryption is WPA, which requires the correct password to access. The third type is WEP, which requires a hexadecimal password and a keyindex.
In the following, we will give a brief introduction on how to establish WiFi connection with these three types of encryption on Ameba.
First, make sure the correct Ameba development board is selected in “Tools” -> “Board”.
Open (WiFi connection without password)
Open the “ConnectNoEncryption” example in
“File” -> “Examples” -> “AmebaWiFi” -> “ConnectWithWiFi” -> “ConnectNoEncryption”
![]()
In the sample code, modify “ssid” to be the same as the WiFi SSID to be connected to.
Next, upload the sample code, and press the reset button on Ameba. Then you will see a message “You’re connected to the networkSSID: XXXXX”, and the information of this WiFi connection is printed in the serial monitor every 10 seconds.
![]()
WiFi connection with WPA encryption
Open the “ConnectWithWPA” example in
“File” -> “Examples” -> “AmebaWiFi” -> “ConnectWithWiFi” -> “ConnectWithWPA”
In the sample code, modify “ssid” to the WiFi SSID to be connected to and “pass” to the network password.
Next, upload the sample code, and press the reset button on Ameba. Then you will see a message “You’re connected to the networkSSID: XXXXX”, and the information of this WiFi connection is printed in the serial monitor every 10 seconds.
WiFi connection with WEP encryption
Open the “ConnectWithWEP” example in
“File” -> “Examples” -> “AmebaWiFi” -> “ConnectWithWiFi” -> “ConnectWithWEP”
In the sample code, modify “ssid” to the SSID to be connected, “key” to the hexadecimal password, “keyIndex” to your key index number.
Next, upload the sample code, and press the reset button on Ameba. Then you will see a message “You’re connected to the networkSSID: XXXXX”, and the information of this WiFi connection is printed in the IDE every 10 seconds.
Code Reference
WiFi.SSID()
to get SSID of the current connected network.WiFi.RSSI()
to get the signal strength of the connection.WiFi.encryptionType()
to get the encryption type of the WiFi
connection.WiFi.BSSID()
to get the MAC address of the router you are
connected to.WiFi.macAddress()
to get the MAC address of Ameba.WiFi.localIP()
to get the IP address of Ameba.WiFi.subnetMask()
to get the subnet mask.WiFi.gatewayIP()
to get the WiFi shield’s gateway IP address.Comparison with Arduino
#include
to
use SPI to communicate with WiFi module.#include
is not needed.Use Ameba as Server to communicate with Client
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Laptop(Make sure it is connected to the same network domain as Ameba, and tcp tools are installed.)
Example
In this example, we first connect Ameba to WiFi, then we use Ameba as server to communicate with client.
First, we make sure the correct Ameba development board is set in “Tools” -> “Board”
Then, open the Simple WiFi Server example in “File” -> “Examples” ->
“AmebaWiFi” -> “SimpleServerWiFi”
In the sample code, modify the highlighted parameters and enter the ssid and password for your WiFi connection.
Next, upload the code, then press the reset button on Ameba. At this moment, you will see the connection information is displayed in the console.
Next, we use the socket tool in the laptop to be the client and connect to the IP address of the Ameba board shown in the connection information at port 5000. (Note: The socket tool we used in this example is “sokit”)
Click on the “Client” tab to choose the client mode, specify the IP and port of the server, then click “TCP Connect”.
If the connection is established successfully, the server shows a message: “A client connected to this Server”, and the IP and port of the connected client.
In this example, when the client and server are connected and the client sends a string to Ameba server, the Ameba server returns the identical string back to the client.
The string sent to server is returned and showed at the client side.
Code Reference
WiFi.begin()
to establish WiFi connection;WiFi.SSID()
to get SSID of the current connected network.WiFi.RSSI()
to get the signal strength of the connection.WiFi.localIP()
to get the Ameba WiFi shield’s IP address.Server(port)
to create a server that listens on the specified
port.server.begin()
to tell the server to begin listening for incoming
connections.server.available()
to get a client that is connected to the server
and has data available for reading.client.read()
to read the next byte received from the server.client.write()
to write data to the server.client.stop()
to disconnect from the server.Use Ameba to retrieve HTTP websites from the internet
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaHttp” -> “SimpleHttpExample”
Code Reference
WiFi.begin()
to establish WiFi connection:WiFi.SSID()
to get SSID of the current connected network.WiFi.RSSI()
to get the signal strength of the connection.WiFi.localIP()
to get the IP address of Ameba.Use http.get()
to send a GET request to the website.
Use Ameba to retrieve information from the Internet
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaWiFi” -> “WiFiWebClient”
In the sample code, modify the highlighted snippet and enter the required information (ssid, password, key index) required to connect to your WiFi network.
Upload the code and press the reset button on Ameba. Then you can see the information retrieved from Google is shown in the Arduino serial monitor.
Code Reference
WiFi.SSID()
to get
SSID of the current connected network.WiFi.RSSI()
to get the signal strength of the connection.WiFi.localIP()
to get the IP address of Ameba.WiFiClient()
to create a client.client.connect()
to connect to the IP address and port specified.client.println()
to print data followed by a carriage return and
newline.client.available()
to return the number of bytes available for
reading.client.read()
to read the next byte received from the server the
client is connected to.client.stop()
to disconnect from the server the client is
connected to.Use Ameba as Server to control LED
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Breadboard x 1
LED x 1
1KΩ Resistor x 1
Procedure
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
“File” -> “Examples” -> “AmebaWiFi” -> “SimpleWebServerWiFi”
Upload the code and press the reset button on Ameba. When the connection is established, you will see the message:
“To see this page in action, open a browser to http://xxx.xxx.xxx.xxx”
in the Arduino IDE as shown in the figure:
Next, open the browser of a computer or a cell phone under the same WiFi domain, enter the address in the message.
In the webpage, you can turn on/off the LED.
Code Reference
WiFi.begin()
to establish WiFi connection.WiFi.SSID()
to get SSID of the current connected network.WiFi.localIP()
to get the IP address of Ameba.WiFiServer server()
to create a server that listens on the
specified port.server.begin()
to tell the server to begin listening for incoming
connections.server.available()
to get a client that is connected to the server
and has data available for reading.client.connected()
to get whether or not the client is connected.client.println()
to print data followed by a carriage return and
newline.client.print()
to print data to the server that a client is
connected to.client.available()
to return the number of bytes available for
reading.client.read()
to read the next byte received from the server the
client is connected to.client.stop()
to disconnect from the server the client is
connected to.Use Ameba as Server to send Ameba status
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaWiFi” -> “WiFiWebServer”
Code Reference
WiFi.begin()
to establish WiFi connection.WiFi.SSID()
to get SSID of the current connected network.WiFi.RSSI()
to get the signal strength of the connection.WiFi.localIP()
to get the IP address of Ameba.WiFiServer server()
to create a server that listens on the
specified port.server.begin()
to tell the server to begin listening for incoming
connections.server.available()
to get a client that is connected to the server
and has data available for reading.client.connected()
to check whether or not the client is connected.client.println()
to print data followed by a carriage return and
newline.client.print()
to print data to the server that a client is
connected to.client.available()
to return the number of bytes available for
reading.client.read()
to read the next byte received from the server the
client is connected to.client.stop()
to disconnect from the server the client is
connected to.Use Ameba as UDP server
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaWiFi”
-> “WiFiUdpSendReceiveString”
Compile the code and upload it to Ameba. After pressing the Reset button, Ameba connects to WiFi and starts the UDP server with port 2390. After the UDP server starts service, Ameba prints the “Starting connection to server” message and waits for client connection.
Code Reference
begin()
to open an UDP port on Ameba.parsePacket()
to wait for data from client.remoteIP()
and remotePort()
to
get the IP and port of the client.read()
to read the data sent by client.beginPacket()
, write()
, end()
.Retrieve Universal Time (UTC) By Ameba
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaWiFi” -> “WiFiUdpNtpClient”
Use MQTT To Upload And Listen To Data
Intro to MQTT
MQTT (Message Queuing Telemetry Transport) is a protocol proposed by IBM and Eurotech. The introduction in MQTT Official Website: MQTT is a machine-to-machine (M2M)/”Internet of Things” connectivity protocol. It was designed as an extremely lightweight publish/subscribe messaging transport. We can say MQTT is a protocol designed for IoT. MQTT is based on TCP/IP and transmits/receives data via publish/subscribe. Please refer to the figure below:
In the operation of MQTT, there are several roles:
Publisher: Usually publishers are the devices equipped with sensors (ex. Ameba). Publishers uploads the data of the sensors to MQTT-Broker, which serves as a database with MQTT service.
Subscriber: Subscribers are referred to the devices which receive and observe messages, such as a laptop or a mobile phone.
Topic: Topic is used to categorized the messages, for example the topic of a message can be “PM2.5” or “Temperature”. Subscribers can choose messages of which topics they want to receive.
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaMQTTClient” ->
“MQTT_Basic”
The “mqttServer” refers to the MQTT-Broker, we use the free MQTT sandbox “test.mosquitto.org” for testing.
“clientId” is an identifier for MQTT-Broker to identify the connected device.
“publishTopic” is the topic of the published message, we use “outTopic” in the example. The devices subscribe to “outTopic” will receive the message.
“publishPayload” is the content to be published.
“subscribeTopic” is to tell MQTT-broker which topic we want to subscribe to.
Install and open the MQTTLens, click “+” next to “Connection” on the left, and fill in the required information
Connection Name: Used to identify the connection, you can choose a name you like.
Hostname: The MQTT-Broker server, here we use “iot.eclipse.org”
Client ID: We use the default randomly generated ID.
Use Amazon AWS IoT Shadow Service
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
REST API endpoint: In the value “https://a1a7oo4baosgyy.iot.us-east-1.amazonaws.com/things/ameba/shadow”, the part “a1a7oo4baosgyy.iot.us-east-1.amazonaws.com” is the MQTT Broker server address.
MQTT topic:The value “$aws/things/ameba/shadow/update” represents the MQTT topic we will use in the AWS IoT Shadow service (if we use MQTT only, without AWS IoT Shadow service, then we can specify other topic name). It is recommended to use “$aws/things/ameba/shadow/update” here.
Ameba setting
“File” -> “Examples” -> “AmebaMQTTClient” -> “Amazon_AWS_IoT_Basic”
Compile and run
Alternatives
Ameba can also retrieve the current LED status variable from the AWS shadow. This is done by sending a message to the “shadow/get” topic. Refer to the Amazon_AWS_IoT_with_ACK example code for more information.
Code Reference
pinMode(led_pin, OUTPUT);
digitalWrite(led_pin, led_state);
WiFiSSLClient wifiClient;
wifiClient.setRootCA((unsigned char*)rootCABuff);
wifiClient.setClientCertificate((unsigned char*)certificateBuff,(unsigned char*)privateKeyBuff);
client.setServer(mqttServer, 8883);
client.setCallback(callback);
loop()
, call reconnect()
function and try to connect to MQTT Broker
server and do the certificate verification.while (!client.connected()) {
for (int i=0; i<5; i++) {
client.subscribe(subscribeTopic[i]);
}
sprintf(publishPayload,
"{\"state\":{\"reported\":{\"led\":%d}},\"clientToken\":\"%s\"}",
led_state, clientId);
client.publish(publishTopic, publishPayload);
if (strstr(topic, "/shadow/get/accepted") != NULL) {
If there is, the message is from the control side. If the attribute state in the message is different from current state, publish the new state.
updateLedState(desired_led_state);
Use MQTT over TLS
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” ->
“AmebaMQTTClient” -> “MQTT_TLS”
Upload PM2.5 Data to LASS System
Intro to LASS
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
PlanTower PMS3003 or PMS5003 x1
Example
In this example, we use applications mentioned at our website, including:
MQTT: a MQTT-Broker to connect to LASS. The Client is “FT1_0XXXX”, the XXXX are the four last digits of Ameba’s Wi-Fi MAC, and the outTopic is “LASS/Test/Pm25Ameba/clientID“, where clientID is the actual Ameba’s MQTT client ID.
NTP: uploaded data must have time notation
PM2.5: uploaded data includes PM2.5 information
“File” -> “Examples” -> “AmebaMQTTClient” ->
“lass_basic”
gps_lat
and gps_lon
.Ameba AP Mode
In AP mode, Ameba can accept at most 3 station connections, and can be set to open mode or WPA2 mode.
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaWiFi” ->
“WiFiAPMode”
In the highlighted code snippet, fill in your SSID, PASSWORD and CHANNEL.
The code highlighted in green is the API we used to turn on the AP mode in security mode.
If you want to turn on the AP mode in open mode, please modify the code to
status = WiFi.apbegin(ssid, channel);
Then upload the sample code and press reset, and you can see related information shown in serial monitor.
In the figure below, we show the messages shown in serial monitor when two stations connect to Ameba AP in open mode:
In the figure below, we show the messages shown in serial monitor when a station connects to Ameba AP in security mode:
Use mDNS To Let Arduino IDE Find Ameba
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
mDNS (Multicast DNS) is a protocol used in the local area network. It delivers the network information like IP address and provided services to others. mDNS is based on the UDP protocol, and it sends packets to 224.0.0.251 with port 5353 under IPv4 address. The naming style for the service follows the format: {Instance Name}.{Protocol Name}.{Domain}
Instance Name: used to identify the name of the service
Protocol Name: Divided into two parts, the front end is in regard to the name of the service, and it adds baseline as a prefix. The rear end is in regard to the transport protocol name it used, and it also adds baseline as a prefix
Domain: Local area network in normal cases
“File” -> “Examples” -> “AmebaMDNS” -> “mdns_on_arduino_ide”
Next, go to (“Tools” ->
“Port”), and you can find out at least one Serial Port. This port is
simulated by Ameba board via USB. Choose this port and upload the
compiled code to Ameba.After uploading the code, press the reset
button on Ameba and waiting for Ameba to connect with AP and activate
the mDNS service after a while. You can see the Log at the bottom of the
Serial Monitor.
Then you can find out the added item “Network
Ports” “MyAmeba at 192.168.1.167 (Ameba RTL8722DM/RTL8722CSM)”,
“MyAmeba” is the device name we set up, and “IP” is the IP address that
AP assigned to Ameba, the IP address should be the same with the IP
shown in the Serial Monitor. Last, “Ameba RTL8722DM/RTL8722CSM” is the
type name of the board, and it means that Ameba can let Arduino IDE
identify the mDNS service successfully.(We still can not use the
Internet to upload the code, and we will explain this part in the OTA
example.)
Does your computer in the same local area network with the Ameba?
Restart the Arduino IDE, and it will find the mDNS service again
Check the Log in Serial Monitor if the Ameba connects to the AP and activate mDNS service successfully
Code Reference
The program set up the mDNS service in the beginning, the first parameter is Instance Name, and it is changeable in this example. The second parameter is the protocol that the service used, and it would be “_arduino._tcp” for Arduino IDE. The third parameter is Domain, and it would be “local” in common. The fourth parameter is the port number for the service, it is 5000 here and we doesn’t use it in the example.
MDNSService service("MyAmeba", "_arduino._tcp", "local", 5000);
After connected to the network, we set up some text fields for the service. For the following example, “board” is the name of the field, “ameba_rtl8721d” is the value of the field. “board” is used to let Arduino IDE check installed SDK to see if it exists known device or not. We will use the name of the device if there is known device, users can change “ameba_rtl8721d” to “yun” or other names to find out what’s the difference if interested.
service.addTxtRecord("board", strlen("ameba_rtl8721d"),"ameba_rtl8721d");
Then we add three text fields “auth_upload”, “tcp_check”, and “ssh_upload”, this example does not activate these services.
service.addTxtRecord("auth_upload", strlen("no"), "no");
service.addTxtRecord("tcp_check", strlen("no"), "no");
service.addTxtRecord("ssh_upload", strlen("no"), "no");
Next we activate MDNS
MDNS.begin();
and register to the mDNS service.
MDNS.registerService(service);
Use Firebase To Push Messaging Services
Preparation
Ameba x 1
Android Studio
Smart phone with Google Play Service x 1
Example
In the era of the popularity of smart phones, people often receive reminders from specific apps. In this example, we will teach how to use Google Firebase to send messages from the Ameba Client to mobile phones.
First, we use Firebase Cloud Messaging (FCM) as a cross-platform messaging solution that lets you deliver messages for free and reliably.
With FCM, you can notify your client application (App) to sync emails or other data. You can send a message to drive user engagement. For instant messaging content, a message can transfer up to 4KB of payload to the client application.

The FCM implementation includes two main parts for sending and receiving:
You can use Admin SDK or HTTP&XMPP API to send messages.To test or send marketing or engagement messages with powerful built-in targeting and analytics, you can also useNotifications composer
We know that Ameba can send messages to specific apps as long as it implements the http client function.
First of all, we must first set up an environment for developing Android apps. Please download Android Studio first on Android official website.
https://developer.android.com/studio/install
Then we can use the Android example provided by Firebase to download Firebase Quickstart Samples.
https://github.com/firebase/quickstart-android
Open Android Studio and click on Import Project, select the messaging project in Firebase Quickstart Samples. Since we won’t use other functions, we can only choose the messaging project.
Android Studio will need to install the SDK and Google repository for the first time to start the messaging project. You can refer to the following page for update.
https://developer.android.com/studio/intro/update
Wait until the required components for compiling the app are installed, you can open the messaging project, and Android Studio comes with the Firebase registration function.

As shown above, open the toolbar and click Tools->Select Firebase.

Open Firebase Assisant in the right pane, then see Cloud Messaging, select Set up Firebase Cloud Messaging to start the registration process.

Click Connect to Firebase

Then bring out the page, and click on Firebase on the left and log in to the Gmail account. Once you log in, you will be taken to the Firebase homepage.

Let’s keep the homepage first, we need to go to the Firebase Console and go back to Android Studio.

We can see that when the webpage is successfully logged in, Android Studio also brings up the login information dialog box, click connect to Firebase


As shown above, the messaging app is installed and executed successfully on the phone. Click LOG TOKEN at this time.

There will be a Token ID, which is the Access Token required to send the message, representing the ID of the FCM service APP installed on a particular phone. This ID is unique and will be reassigned when the app is removed and re-installed. It means that the message can be sent to a specific phone. The FCM service can also push messages to a NEWS (Topic). This section can be found in Firebase topic-messaging:
https://firebase.google.com/docs/cloud-messaging/android/topic-messaging
Therefore, we need to save this Access Token, return to Android Studio as shown below, select Debug at the log level of the Logcat. When you press the LOG TOKEN button on the App, Logcat will print out the Access Token ID. We will save the code after the InstanceID Token: in the Log message.

Then we have to go back to the page that was brought when we first logged into Firebase.

Click in the upper right corner to go to the console

At this point, You can see that Android Studio has just built the messaging project for us in the operation.

Click to enter the messaging project with settings page, as shown above.

Select Set up

“File” -> “Examples” -> “AmebaWiFi” -> “Firebase.ino”

As shown above, ACCESS_TOKEN and SERVER_KEY are defined in the reverse white part, that is, the ACCESS token ID that we just saved from the APP and the Server Key saved in the Firebase console page. We fill in the two sets of IDs, compile and upload them to Ameba. Press the Reset button and open the terminal.

Connect to FCM Server after connecting to AP

After showing Connect to Server successful, it means that the FCM connection is successful and the message will be sent. During the process, HTTP/1.1 200 OK will be received to indicate that the message is successfully pushed. At this time, the mobile phone screen is opened and the App receives the message from Ameba.

Code Reference
https://firebase.google.com/docs/cloud-messaging/send-message
The main payload format in the program is as follows. The user can freely change the Title and Body of the message. Body represents the content of the message.
char const* payload = "{" \
"\"to\": \"" ACCESS_TOKEN "\"," \
"\"notification\": {" \
"\"body\": \"Hello World!\"," \
"\"title\" : \"From Realtek Ameba\" " \
"} }" ;
setup() {
if (client.connect(server, 80)) {
Serial.println("connected to server");
// Make a HTTP request:
sprintf(message,"%s%s%s%s%s%d%s%s%s","POST /fcm/send HTTP/1.1\nContent-Type: application/json\nAuthorization: key=",SERVER_KEY,"\nHost: ",HOST_NAME,"\nContent-Length: ",strlen(payload),"\n\n",payload,"\n");
printf("\nRequest:\n%s \n",message);
client.println(message);
client.println();
}
}
The sprintf part puts the payload into the HTTP POST content and sends the message out after connecting to the FCM Server.
loop(){
while (client.available()) {
char c = client.read();
Serial.write(c);
}
}
Waiting for the response from Server and printing out the response.
Access IFTTT Via Ameba
Introduction to IFTTT
IFTTT, known as If This Then That, is a website and mobile app and free web-based service to create the applets, or the chains of simple conditional statements. The applet is triggered by changes that occur within other web services such as Gmail, Facebook, Telegram, Instagram, Pinterest etc.
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
An account from https://ifttt.com/ , in order to access IFTTT service*
備註
Upon log in, there are several cloud and online services that are integrated with IFTTT platforms.
Example
Generate Applet from IFTTT
In this example, we obtain an example of IFTTT Applet to send email to specified recipient.
To run the example, HTTP POST feature of the Ameba is used to post a simple webhook service that is received by IFTTT platform and in turn be used to trigger a response (sending an email).
After logging in https://ifttt.com/, click Create from the top bar.
Click “Add” to add the trigger.
Choose Webhooks service as shown below. Alternatively, search the service by typing into the search bar.
After that, the available triggers will appear. Choose Receive a Web request.
Next, an Event Name is required to identify the trigger successfully. In this example, set the Event name as “test_event”.
Next, click Add in Then That field to create the action service taken in response to the last trigger.
Choose Email as the action service.
Click on Send me an email.
Under the template of Send me an Email, the contents of the email, such as subject and body is editable. Click Create Action to complete the action. Take note that Email service is offered to the email address registered under IFTTT account.
Post the Trigger via Ameba
“File” -> “Examples” -> “AmebaWiFi” -> “HTTP_IFTTT_Post”
The WiFi credentials to connect to the Wi-Fi hotspot or access point of desirable choice.
Under the Host name field, enter the host name of the IFTTT service “maker.ifttt.com”.
Under the Path name field, enter the Event name and key field “/trigger/Event name/with/key/Key Field”
Event name: The event name should be the same as the one specified in the IFTTT applet. In this example, the event name is “test_event”.
Key Field: Available under webhook service in individual IFTTT account. See the next step for the steps to obtain the Key Field.
To obtain a key from documentation tab of the Webhooks, find the webhook service in the Explore tab.
On the Webhooks service page, click on the Documentation tab.
The key can be found in the documentation page. Also, information on how HTTP request can be used.
Thereafter an email is sent to recipient email account registered at IFTTT Applet and email notification will be received.
Use Ameba To Securely Retrieve Information From The Internet
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
This example uses Ameba to securely retrieve information from the internet using SSL. SSL is an acronym for Secure Sockets Layer. It is a cryptographic protocol designed to provide communications security over a computer network, by encrypting the messages passed between server and client.
Open the “WiFiSSLClient” example in “File” -> “Examples” -> “AmebaWiFi”
-> “WiFiSSLClient”
.
In the sample code, modify the highlighted snippet to reflect your WiFi network settings.
Upload the code and press the reset button on Ameba once the upload is finished.
Open the serial monitor in the Arduino IDE and observe as Ameba retrieves a text file from os.mbed.com.
Code Reference
Use “WiFiSSLClient client;” to create a client that uses SSL. After creation, the client can be used in the same way as a regular client.
BLE – BLE Battery Service
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Android / iOS mobile phone
Example
Introduction
BLE connections use a server client model. The server contains the data of interest, while the client connects to the server to read the data. Commonly, a Bluetooth peripheral device acts as a server, while a Bluetooth central device acts as a client. Servers can contain many services, with each service containing a some set of data. Clients can send requests to read or write some data and can also subscribe to notifications so that the server can send data updates to a client.
In this example, a basic battery service is set up on the Ameba Bluetooth stack. A mobile phone is used to connect to the Ameba peripheral device and read the battery data.
Procedure
Ensure that the following Bluetooth apps are installed on your mobile phone. These apps will show you the raw data sent by Ameba and allow you to interact with the data.
The recommended application is nRF connect, and is available at the links below:
LightBlue is an alternative application that can also be used, but has less features:
Open the example, “Files” -> “Examples” -> “AmebaBLE” ->
“BLEBatteryService”
Connect to the Ameba Bluetooth device, and a list of available services should appear. Click on the battery service to expand it, and you can see the battery level data value. The arrows highlighted in the box on the right are used to read data and subscribe to notifications. Click on the single arrow to read the battery level value, and a 90% value will appear.
Click on the triple arrow to subscribe to updates on the battery level value, and the battery value will start updating by itself.
The serial monitor will show the sketch increasing the battery level every second. When you click on either of the arrows, the sketch running on the Ameba will be notified, and will print out the action taken.
Code Reference
BLEService and BLECharacteristic classes are used to create and define the battery service to run on the Bluetooth device.
BLE.configAdvert()->setAdvType(GAP_ADTYPE_ADV_IND)
is used to set the
advertisement type to a general undirected advertisement that allows for
connections.
setReadCallback()
and setCCCDCallback()
is used to register functions
that will be called when the battery level data is read, or notification
is enabled by the user.
BLE.configServer(1)
is used to tell the Bluetooth stack that there will
be one service running.
addService()
registers the battery service to the Bluetooth stack.
BLE – BLE Beacon
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Android / iOS mobile phone
Example
Introduction
A BLE beacon broadcasts its identity to nearby Bluetooth devices, to enable the other devices to determine their location relative to the beacon, and to perform actions based on information broadcasted by the beacon.
Example applications of beacons include indoor positioning system, location-based advertising and more.
From the definition of its purpose as a broadcast device, a BLE beacon thus cannot be connected to, and can only send information in its Bluetooth advertisement packets.
There are several BLE beacon protocols. The Ameba BLEBeacon library supports the iBeacon and AltBeacon protocols.
Procedure
LightBlue is an alternative application that can also be used, but has less features:
Open the example, “Files” -> “Examples” -> “AmebaBLE” -> “BLEBeacon”
Upload the code and press the reset button on Ameba once the upload is finished.
On your mobile phone, open the Bluetooth app and scan for the beacon signal broadcast by Ameba.
If you happen to be in an environment with multiple BLE beacons, you can tap the entries to expand them, and verify that the beacon data is identical to the data in the sketch.
Code Reference
setRssi()
is used to set the received signal strength indicator (rssi)
data field for a beacon. The specification states that this should be
the received signal strength from the beacon at a 1 meter distance. With
no method to measure this, it is set to -65dBm as an estimate.
setMajor()
and setMinor()
are used to set the two data fields. The
purpose of these data are left for the manufacturer of the beacon to
define, and can be used in any way.
setUUID()
is used to give the beacon a universally unique identifier
(UUID). This is a 128-bit number usually expressed as a hexadecimal
string. It is used to identify each unique beacon, and can be randomly
generated for free online.
The BLEBeacon library includes both iBeacon and AltBeacon classes, replace line 6 iBeacon with altBeacon to create an AltBeacon instead. The data fields are mostly the same, with only minor changes, please look at the header files for more details.
BLE.init()
is used to allocate memory and prepare Ameba for starting the
Bluetooth stack.
BLE.configAdvert()
is used to configure the Bluetooth advertisement
settings, to which we pass the beacon data and set the device as
non-connectable.
BLE.beginPeripheral()
starts Ameba in Bluetooth peripheral mode, after
which it will begin to advertise with the beacon data provided.
BLE – BLE Scan
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Android / iOS mobile phone
Example
Introduction
This example configures the Ameba as a Bluetooth central device, uses the scan functionality to scan for other Bluetooth devices, and prints out the results to the serial monitor.
Procedure
Open the example, “Files” -> “Examples” -> “AmebaBLE” -> “BLEScan”
If you have the Bluetooth app nRF Connect installed, you can also use it to send out Bluetooth advertisements for the Ameba to pick up.
Code Reference
setScanMode(GAP_SCAN_MODE_ACTIVE)
is used to set the scan mode. Active
scanning will request for an additional scan response data packet from a
device when it is found. Passive scanning will only look at the
advertisement data, and not request for additional data.
setScanInterval()
and setScanWindow()
are used to set the frequency and
duration of scans in milliseconds. A scan will start every interval
duration, and each scan will last for the scan window duration. The scan
window duration should be lesser or equal to the scan interval. Set a
short interval to discover devices rapidly, set a long interval to
conserve power.
setScanCallback(scanFunction)
is used to register a function to be
called when scan results are received. This can be used to set a user
function for additional processing of scan data, such as looking for a
specific device. If no function is registered, the scan results are
formatted and printed to the serial monitor by default.
beginCentral(0)
is used to start the Bluetooth stack in Central mode.
The argument 0 is used to indicate that no clients will be operating in
central mode.
startScan(5000)
is used to start the scanning process for a specified
duration of 5000 milliseconds. The scan will repeat according to the set
scan interval and scan window values. After 5000 milliseconds, the scan
process will stop, and will be ready to be started again.
BLE – Battery Client
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
Introduction
BLE connections use a server client model. The server contains the data of interest, while the client connects to the server to read the data. Commonly, a Bluetooth peripheral device acts as a server, while a Bluetooth central device acts as a client. Servers can contain many services, with each service containing a some set of data. Clients can send requests to read or write some data and can also subscribe to notifications so that the server can send data updates to a client.
In this example, a basic battery client is set up on the Ameba Bluetooth stack. The client connects to another Ameba board running the corresponding BLE battery service to read the battery level data.
Procedure
On the first Ameba board, upload the BLEBatteryService example code and let it run.
For the second Ameba board, open the example “Files” -> “Examples” ->
“AmebaBLE” -> “BLEBatteryClient”
.
Upload the code and press the reset button on Ameba once the upload is finished.
Open the serial monitor and observe the log messages as the Ameba board with the battery client scans, connects, and reads data from the Ameba board with the battery service.
Highlighted in yellow, the Ameba board with the battery client first scans for advertising BLE devices with the advertised device name “AMEBA_BLE_DEV” and the advertised service UUID of 0x180F representing the battery service.
After finding the target device, the Ameba board with the battery client forms a BLE connection and searches for a battery service on the connected device, highlighted in blue.
With the client connected to the service, the battery client begins to read data using both regular data reads and notifications, highlighted in green.
Code Reference
BLEClient is used to create a client object to discover services and characteristics on the connected device.
setNotifyCallback()
is used to register a function that will be called when a battery level notification is received.
BLE.configClient()
is used to configure the Bluetooth stack for client operation.
addClient(connID)
creates a new BLEClient object that corresponds to the connected device.
BLE – WiFi Configuration Service
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Android / iOS mobile phone
Example
Introduction
In this example, a WiFi configuration service is set up on the Ameba Bluetooth stack. A mobile phone with the configuration app connects to the Ameba device using BLE and configures the Ameba to connect to the correct WiFi access point.
Procedure
Ensure that the Realtek WiFi configuration app is installed on your mobile phone, it is available at:
Open the example, “Files” -> “Examples” -> “AmebaBLE” ->
“BLEWifiConfigService”
.
Upload the code and press the reset button on Ameba once the upload is finished.
On your mobile phone, open the Realtek WiFiConfig app and tap the round button to scan for Ameba boards.
Select the correct Ameba board from the scan results. The app will connect to the Ameba board and ask the board to scan for WiFi networks and send the scan results back to the app using BLE.
If your phone is currently connected to a WiFi network, the app will ask for the WiFi password to connect the Ameba board to the same WiFi network. Tap “Select AP” to choose another WiFi network, or enter the password and tap continue to connect Ameba to the selected WiFi network.
After the Ameba board connects to the WiFi network, the following message will be shown. Tap “Try another AP” to connect to another WiFi network or tap “Confirm” to keep the current WiFi network and disconnect BLE from the Ameba board.
Code Reference
BLEWifiConfigService is used to create an instance of the WiFi configuration service to run on the Bluetooth device.
BLE.configAdvert()->setAdvType(configService.advData())
is used to set
the correct advertisement data necessary for the phone app to find the
Ameba Bluetooth device.
BLE – BLE UART Client
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 2
Example
Introduction
In this example, two RTL8722 boards are connected using BLE. One board runs a BLE UART service, while the other connects to the service using a client and both boards are able to communicate with text messages over the UART service.
Procedure
On the first board, upload the BLE UART service example code. Refer to the example guide for detailed instructions.
For the second board, open the example, “Files” -> “Examples” ->
“AmebaBLE” -> “BLEUartClient”
.
Code Reference
The BLEClient class is used to discover the services that exist on a connected BLE device. The discovery process will create BLERemoteService, BLERemoteCharacteristic and BLERemoteDescriptor objects corresponding to the services, characteristics and descriptors that exist on the connected device. These objects can then be used to read and write data to the connected device.
BLE – BLE UART Service
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Android / iOS smartphone
Example
Introduction
Procedure
Open the example, “Files” -> “Examples” -> “AmebaBLE” ->
“BLEUartService”
.




Code Reference
set__Property()
methods, and callback
functions are registered using the set__Callback()
methods. The
required buffer size is also set for each characteristic so that it
has enough memory to store a complete string.notify()
method is used to
inform the connected device of the new data.BLE – DHT over BLE UART
Materials
AmebaD [RTL8722DM/ RTL8722CSM/ RTL8722DM MINI] x 1
DHT11 or DHT22 or DHT21
Android / iOS smartphone
Example
Introduction
In this example, the data obtained from a DHT temperature and humidity sensor are transmitted over a BLE UART service to a smartphone. Refer to the other examples for detailed explanations of using the DHT sensor and the BLE UART service.
Procedure
Connect the DHT sensor to the Ameba board following the diagram.
RTL8722DM / RTL8722CSM:
RTL8722DM MINI:
Open the example, “Files” -> “Examples” -> “AmebaBLE” ->
“DHT_over_BLEUart”
.
BLE – PWM over BLE UART
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
RGB LED
Android / iOS smartphone
Example
Introduction
In this example, a smartphone app is used to transmit commands over BLE UART to control the PWM outputs and change the color of a RGB LED. Refer to the other example guides for detailed explanations of the BLE UART service.
Procedure
Connect the RGB LED to the RTL8722 board following the diagram, the common LED pin may need to connect to 3.3V or GND depending on the type of LED (common anode / common cathode).
RTL8722DM / RTL8722CSM:
RTL8722DM MINI:
Open the example, “Files” -> “Examples” -> “AmebaBLE” ->
“PWM_over_BLEUart”
.
Upload the code and press the reset button on Ameba once the upload is finished.
Using the color selection wheel, saturation, and brightness sliders, choose a desired color and click select to send the RGB values to the board. You should see the RGB LED change to the matching color.
Code Reference
The RGB values are sent as three consecutive bytes prefixed by “!C” characters. The “!” exclamation mark is used to indicate that the following data is a command, and the “C” character is used to indicate that the data is RGB values. The received UART message is checked in the callback function for “!C” first, otherwise it is treated as a regular message and printed to the serial terminal.
BLE - HID Gamepad
Materials
AmebaD [RTL8722DM/RTL8722CSM/RTL8722DM MINI] x 1
BLE capable host device [Windows / Linux / MacOS / Android
Example
Introduction
In this example, the RTL8722 board emulates a HID gamepad connected using BLE.
Procedure
Open the example, “Files” -> “Examples” -> “AmebaBLE” -> BLEHIDGamepad
.
Code Reference
By default, the board emulates a gamepad with an 8-direction hat switch (d-pad), 6 analog axes and 16 buttons. How the inputs are interpreted is dependent on the host device, and the button ordering may differ between devices. Also, some axes or buttons may be disabled or missing on certain host devices.
BLE - HID Keyboard
Materials
AmebaD [RTL8722DM/RTL8722CSM/RTL8722DM MINI] x 1
BLE capable host device [Windows / Linux / MacOS / Android
Example
Introduction
In this example, the RTL8722 board emulates a HID keyboard connected using BLE.
Procedure
Open the example, “Files” -> “Examples” -> “AmebaBLE” -> BLEHIDKeyboard
.
BLE - HID Mouse
Materials
AmebaD [RTL8722DM/RTL8722CSM/RTL8722DM MINI] x 1
BLE capable host device [Windows / Linux / MacOS / Android
Example
Introduction
In this example, the RTL8722 board emulates a HID mouse connected using BLE.
Procedure
Open the example, “Files” -> “Examples” -> “AmebaBLE” -> “BLEHIDMouse”
.
Code Reference
How the mouse input is interpreted is dependent on the host system. Some systems, such as mobile operating systems, may not support all mouse button input functions.
Approximate UDP Receive Delay
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Windows computer connected to same network
Example
This example uses Ameba to receive UDP packets from a computer and calculates the UDP receive delay.
Ameba Preparation
Open the “CalculateUdpReceiveDelay” example in
“File” -> “Examples” -> “AmebaWiFi” -> “UDP_Calculation” -> “CalculateUdpReceiveDelay”
.
In the sample code, modify the highlighted section to enter the information required (ssid, password, key index) to connect to your WiFi network.
Upload the code and press the reset button on Ameba once the upload is finished. Open the serial monitor in Arduino IDE and take note of the IP address assigned to Ameba.
Computer Preparation
On the computer, Cygwin will be required to compile the code to send the UDP packets. Cygwin can be downloaded from https://www.cygwin.com/
Follow the instructions there to install it. Next, from the “CalculateUdpReceiveDelay” Arduino example, copy the code from the bottom between “#if 0” and “#endif”, into a new text file, change the hostname to the IP address assigned to Ameba, and rename the file to “UdpReceiveDelay.cpp”.
Next, open a Cygwin terminal, change the working directory to the location of “UdpReceiveDelay.cpp”, and use the command “g++ UdpReceiveDelay.cpp -o UdpDelay” to compile the code. A file named “UdpDelay.exe” will be created in the same directory.
Running the Example
Reset the Ameba, wait for the WiFi to connect, and check that the IP address remains the same. On the computer, run the UdpDelay.exe file, and the computer will begin to send packets to Ameba. Once 10000 packets have been received, Ameba will calculate the average delay and print out the result to the serial monitor. It may take up to a few minutes for 10000 packets to be sent.
Approximate UDP Receive Timeout
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Windows computer connected to same network
Example
This example uses Ameba to receive UDP packets from a computer and calculates the allowed UDP receive timeout setting.
Ameba Preparation
Open the “CalculateUdpReceiveTimeout” example in
“File” -> “Examples” -> “AmebaWiFi” -> ” UDP_Calculation ” -> “CalculateUdpReceiveTimeout”
.
In the sample code, modify the highlighted section to enter the information required (ssid, password, key index) to connect to your WiFi network.
Upload the code and press the reset button on Ameba once the upload is finished.
Open the serial monitor in Arduino IDE and take note of the IP address assigned to Ameba.
Computer Preparation
On the computer, Cygwin will be required to compile the code to send the UDP packets. Cygwin can be downloaded from https://www.cygwin.com/
Follow the instructions there to install it. Next, from the “CalculateUdpReceiveTimeout” Arduino example, copy the code from the bottom between “#if 0” and “#endif”, into a new text file, change the hostname to the IP address assigned to Ameba, and rename the file to “UdpReceiveTimeout.cpp”.
Next, open a Cygwin terminal, change the working directory to the location of “UdpReceiveTimeout.cpp”, and use the command “g++ UdpReceiveTimeout.cpp -o UdpTimeout” to compile the code. A file named “UdpTimeout.exe” will be created in the same directory.
Running the Example
Reset the Ameba, wait for the WiFi to connect, and check that the IP address remains the same. On the computer, run the UdpTimeout.exe file, and the computer will begin to send packets continuously to Ameba.
The timeout value is set to 1000ms initially. For each packet received successfully, Ameba decreases the timeout value. The next packet must be received within the timeout period, otherwise Ameba registers a failed packet and increases the timeout value. Open the serial monitor and observe the timeout value converge to a minimum value.
Approximate UDP Sending Delay
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Windows computer connected to same network
Example
This example uses Ameba to send UDP packets to a computer and calculates the UDP sending delay.
Ameba Preparation
Open the “CalculateUdpSendDelay” example in “File” -> “Examples” ->
“AmebaWiFi” -> ” UDP_Calculation ” -> “CalculateUdpSendDelay”
.
In the sample code, modify the highlighted section to enter the information required (ssid, password, key index) to connect to your WiFi network.
The server variable also needs to be changed to match the IP address of your computer. You can find the IP address using the “ipconfig” command in a terminal window.
Computer Preparation
On the computer, Cygwin will be required to compile the code to send the UDP packets. Cygwin can be downloaded from https://www.cygwin.com/
Follow the instructions there to install it. Next, from the “CalculateUdpSendDelay” Arduino example, copy the code from the bottom between “#if 0” and “#endif”, into a new text file and rename the file to “UdpSendDelay.cpp”.
Next, open a Cygwin terminal, change the working directory to the location of “UdpSendDelay.cpp”, and use the command “g++ UdpSendDelay.cpp -o UdpDelay” to compile the code. A file named “UdpDelay.exe” will be created in the same directory.
Running the Example
First, on the computer, run the UdpDelay.exe file, and the computer will begin to listen for packets from Ameba.
Next, compile and upload the code from the Arduino IDE to Ameba and press the reset button when the upload is complete.
The Ameba will begin to send UDP packets to the computer. Once 10000 packets have been received, the computer will calculate the average delay and print out the result.
It will take some time for 10000 packets to be sent.
Google Cloud IoT
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Google Cloud IoT Configuration
1. Select or create a Cloud Platform project In the Google Cloud Console, select an existing project or create a new project. You will need a Project ID to use with Ameba.
If creating a new project, enter a project name, and take note of the Project ID generated.
2. Enable billing for your project Billing needs to be enabled for your project to use Google Cloud Platform features. Follow the guide in Google cloud documentation to enable billing. https://cloud.google.com/billing/docs/how-to/modify-project 3. Enable the Cloud IoT Core API In Google Cloud console, click on the top left menu button and search for IoT Core.
Click enable to activate Google Cloud IoT API for your project.
4. Create a Cloud Pub/Sub topic In Google Cloud console, click on the top left menu button and search for Pub/Sub.
Create a new topic for your project and give it a suitable topic ID.
After the topic is created, go to the permissions tab of the info panel, and add “cloud-iot@system.gserviceaccount.com” with the role of “Pub/Sub Publisher”.
5.Create a device registry Go back to the IoT Core settings page and create a new registry.
Choose a suitable Registry ID and in which to store data. Remember the **Registry ID and Regionfor use with Ameba later. For the Pub/Sub topic, select the topic created in the previous step.
6. Create a public/private key pair Using Openssl in a terminal in Windows/Linux/MacOs, run the following commands to generate a private and public key pair. Two files will be created by these commands, “ec_private.pem” containing the private key, and “ec_public.pem” containing the public key.
$ openssl ecparam -genkey -name prime256v1 -noout -out ec_private.pem
$ openssl ec -in ec_private.pem -pubout -out ec_public.pem
Run the next command to extract out the private key, and remember the highlighted string of hexadecimal numbers for use with Ameba later.
$ openssl ec -in ec_private.pem -noout -text
7. Create a device Go back to the IoT Core settings page and create a new device.
Give the device a suitable Device ID and remember it for use with Ameba later.
In the authentication section of the additional options, upload the previously generated “ec_public.pem” public key.
8. Create a Cloud Pub/Sub subscription To observe messages sent by Ameba, create a subscription in Pub/Sub.
Choose a suitable subscription ID and select the previously created topic.
Example
“File” -> “Examples” -> “AmebaMQTTClient” ->
“Google_Cloud_IoT”
.Code Reference
In setup()
, we set up RootCA which is required to form a TLS connection
with Google’s servers.
wifiClient.setRootCA((unsigned char*)rootCABuff);
In loop()
, each loop checks the Internet status and re-connect to it
when the environment has a problem.
if (WiFi.status() != WL_CONNECTED) {
while (WiFi.begin(ssid, pass) != WL_CONNECTED)
{
delay(1000);
}
Serial.println("Connected to wifi");
}
To publish messages, mqtt_id , clientPass and pub_topic are required. mqtt_id is generated by printing the project ID, server location, registry ID and device ID in the required format:
mqtt_id = (char *)malloc(strlen("projects/") + strlen(project_id) + strlen("/locations/us-central1/registries/") + strlen(registry_id) + strlen("/devices/") + strlen(device_id) + 1);
sprintf(mqtt_id, "projects/%s/locations/us-central1/registries/%s/devices/%s", project_id, registry_id, device_id);
clientPass
is generated using a JSON web token (JWT) generator function,
which requires the project ID and current time, and signs it with the
private key:
clientPass = CreateJwt(project_id, timeClient.getEpochTime(), priv_key);
pub_topic
is generated by printing the project ID and topic in the
required format:
pub_topic = (char *)malloc(strlen("/devices/") + strlen(device_id) + strlen("/events") + 1);
sprintf(pub_topic, "/devices/%s/events", device_id);
MQTT Server setting:
client.setServer(GOOGLE_MQTT_SERVER, GOOGLE_MQTT_PORT);
client.setPublishQos(MQTTQOS1);
client.waitForAck(true);
Connect to google cloud and publish messages:
if (client.connect(mqtt_id, clientUser, clientPass.c_str())){
// ...
for(int i = 0; i < count; i++){
// ...
sprintf(payload, "This is Ameba's %d message!!", i);
ret = client.publish(pub_topic, payload);
// ...
}
// ...
client.disconnect();
}
free(mqtt_id);
free(pub_topic);
IPv6 – Ameba as IPv6 Server/Client over TCP
Materials
AmebaD [RTL8722DM/RTL8722CSM/RTL8722DM MINI] / [RTL8720DN(BW16)] x 2
Example
Introduction
This example shows how Ameba can communicate on the local network using Internet Protocol version 6 over TCP. Note that this example only works after you have set up the server and then configure the client accordingly.
Procedure
Step 1. IPv6TCPServer
Open the example, “Files” -> “Examples” -> “AmebaWiFi” -> “IPv6TCPServer”
.
In the sample code, modify the highlighted section to enter the information required (ssid, password) to connect to your WiFi network.
Next, upload the code and press the reset button on Ameba once the upload is finished. Open Serial Monitor and copy the IPv6 address of the Server (the highlighted area) for later use,
Step 2. IPv6TCPClient
Now take the second Ameba D and open another example, “Files” -> “Examples” -> “AmebaWiFi” -> “IPv6TCPClient”
.
In the sample code, modify the highlighted section to enter the information required (ssid, password) to connect to your WiFi network.
From the previous step, we have obtained the Server’s IPv6 address, now we copy the server’s IPv6 address to “IPv6TCPClient” example in the highlighted area below,
IPv6 – Ameba as IPv6 Server/Client over UDP
Materials
AmebaD [RTL8722DM/RTL8722CSM/RTL8722DM MINI] / [RTL8720DN(BW16)] x 2
Example
Introduction
This example shows how Ameba can communicate on the local network using Internet Protocol version 6 over UDP. Note that this example only works after you have set up the server and then configure the client accordingly.
In the sample code, modify the highlighted section to enter the information required (ssid, password) to connect to your WiFi network.
Next, upload the code and press the reset button on Ameba once the upload is finished. Open Serial Monitor and copy the IPv6 address of the Server (the highlighted area) for later use,
Step 2. IPv6UDPClient
Now take the second Ameba D and open another example, “Files” -> “Examples” -> “AmebaWiFi” -> “IPv6UDPClient”
.
In the sample code, modify the highlighted section to enter the information required (ssid, password) to connect to your WiFi network.
From the previous step, we have obtained the Server’s IPv6 address, now we copy the server’s IPv6 address to “IPv6UDPClient” example in the highlighted area below,
使用元件
溫濕度傳感器
|
距離測量的功能
|
使用 SPI 接口的 TFT LCD 顯示屏
|
|
QVGA TFT LCD 顯示器模組
|
高質量 GPS 定位模組
|
高輸出功率的伺服電機
|
Peripheral Examples
GPIO - Measure The Distance By Ultrasound Module
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
HC-SR04 Ultrasonic x 1
Dropping resistor or Level converter
Example
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Next, open the sample code in “File” -> “Examples” -> “AmebaGPIO” -> “HCSR04_Ultrasonic”
Compile and upload to Ameba, then press the reset button. Open the Serial Monitor, the calculated result is output to serial monitor every 2 seconds.
Note that the HCSR04 module uses the reflection of sound wave to calculate the distance, thus the result can be affected by the surface material of the object (e.g., harsh surface tends to cause scattering of sound wave, and soft surface may cause the sound wave to be absorbed).
Code Reference
Before the measurement starts, we need to pull high the TRIG pin for 10us and then pull low. By doing this, we are telling the HC-SR04 that we are about to start the measurement:
digitalWrite(trigger_pin, HIGH);
delayMicroseconds(10);
digitalWrite(trigger_pin, LOW);
Next, use pulseIn to measure the time when the ECHO pin is pulled high.
duration = pulseIn (echo_pin, HIGH);
Finally, use the formula to calculate the distance.
distance = duration / 58;
GPIO - Measuring The Temperature And Humidity
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
DHT11 or DHT22 or DHT21
Example
Since one of the 4 pins has no function, there are temperature/humidity sensors with only 3 pins on the market:
DHT is normally in the sleeping mode. To get the temperature/humidity data, please follow the steps:
Awake DHT: Ameba toggles low its DATA pin of GPIO. Now the DATA pin of GPIO serves as digital out to Ameba.
DHT response: DHT also toggle low its DATA pin of GPIO. Now the DATA pin of GPIO serves as digital in for Ameba.
DHT sends data: DHT sends out the temperature/humidity data (which has size 5 bytes) in a bit by bit manner. To represent each bit, DHT first pull low the DATA GPIO pin for a while and then pull high. If the duration of high is smaller than low, it stands for bit 0. Otherwise it stands for bit 1.
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Open the sample code in “Files” -> “Examples” -> “AmebaGPIO” ->
“DHT_Tester”
. Compile and upload to Ameba, then press the reset button.
The result would be shown on the Serial Monitor.
Code Reference
Use dht.readHumidity()
read the humidity value, and
use dht.readTemperature()
to read the temperature value.
Every time we read the temperature/humidity data, Ameba uses the buffered temperature/humidity data unless it found the data has expired (i.e., has not been updated for over 2 seconds). If the data is expired, Ameba issues a request to DHT to read the latest data.
GPIO - Use GPIO Interrupt To Control LED
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
LED x 1
Button x 1
Example
In this example, we use a button to trigger interrupt and control the LED. When we press and release the button, the LED dims, press and release the button again, and the LED lights.Note that in the Arduino example “Button and LED”, LED only lights when the button is pressed and hold, when we release the button, the LED dims.
Open the example, “Files” -> “Examples” -> “AmebaGPIO” ->
“LED_InterruptCtrl”
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Code Reference
In
setup()
we set Pin 12 to
INPUT_IRQ_RISE
, this means that an interrupt occurs when the voltage of this pin changes from GND to 3V3. Therefore, we connect the other side of the button to 3V3, so as to trigger interrupt event when the button is pressed.
pinMode(button, INPUT_IRQ_RISE);
On the other hand, we can set pin 12 to
INPUT_IRQ_FALL
, this means that an interrupt occurs when the voltage of this pin changes from 3V3 to GND. In this case, the other side of the button is connected to GND.Next, we need to specify the funtion to be execute to handle the interrupt:
digitalSetIrqHandler(button, button_handler);
The second parameter is a function pointer, with prototype:
void button_handler(uint32_t id, uint32_t event)
In this handler, every time we press and release the button, we trigger an interrupt, and change the status of the LED.
PWM – Play Music
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Buzzer x 1
Example
A sound is composed of volume, tone and timbre. Volume is determined by the amplitude of the sound wave. Tone is determined by the frequency of the sound wave. Timbre is determined by the waveform of the sound wave.
In this example, we use PWM to control the buzzer to emit sound with desired tone. As PWM outputs square wave, if we wish to emit tone C4 (frequency=262Hz), we have to make PWM to output square wave with wavelength 1/262 = 3.8ms:
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
“Examples” -> “AmebaAnalog” -> “TonePlayMelody”
Code Reference
In the sample code, we initiate a melody array, which stores the tones to make. Another array, noteDurations, contains the length of each tone, 4 represents quarter note (equals to 3000ms/4 = 750ms, and plus an extra 30% time pause), 8 represents eighth note.
PWM – Using A Servo
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Servo x 1 (Ex. Tower Pro SG90)
Example
A typical servo has 3 wires, the red wire is for power, black or brown one should be connected to GND, and the other one is for signal data. We use PWM signal to control the rotation angle of the axis of the servo. The frequency of the signal is 50Hz, that is length 20ms. Each servo defines its pulse bandwidth, which is usually 1ms~2ms.
To control the rotation angle, for example if 1ms-length pulse rotates the axis to degree 0, then 1.5 ms pulse rotates the axis to 90 degrees, and 2 ms pulse rotates the axis to 180 degrees. Furthermore, a servo defines the “dead bandwidth”, which stands for the required minimum difference of the length of two consecutive pulse for the servo to work.
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
“File” -> “Examples” -> “AmebaAnalog” ->
“ServoSweep”
Code Reference
The Servo API of Ameba is similar to the API of Arduino. To distinguish from the original API of Arduino, we name the header file “AmebaServo.h” and the Class “AmebaServo”, the usage is identical to the Arduino API.
The default pulse bandwidth of Arduino Servo is 0.5ms~2.4ms, which is the same as Tower Pro SG90. Therefore, we set the attached pin directly:
myservo.attach(9);
Next, rotate the axis to desired position:
myservo.write(pos);
I2C - Communicate with Arduino UNO via I2C
Introduction of I2C
There are two roles in the operation of I2C, one is “master”, the other is “slave”. Only one master is allowed and can be connected to many slaves. Each slave has its unique address, which is used in the communication between master and the slave. I2C uses two pins, one is for data transmission (SDA), the other is for the clock (SCL). Master uses the SCL to inform slave of the upcoming data transmission, and the data is transmitted through SDA. The I2C example was named “Wire” in the Arduino example.
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Arduino UNO x 1
Example
Setting up Arduino Uno to be I2C Slave
“Tools” -> “Board” -> “Arduino Uno”
“Examples” -> “Wire” -> “slave_receiver”
:Then click “Sketch” -> “Upload”
to compile and upload the example to Arduino Uno.
Setting up Ameba to be I2C Master
“Tools” -> “Board”
“File” -> “Examples” ->
“AmebaWire” -> “MasterWriter”
Wiring
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Code Reference
I2C - Display Data On LCD Screen
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
I2C 2×16 LCD
Example
“File” -> “Examples” -> “AmebaWire” -> “LCD_HelloWorld”
.After 8 seconds, you can input to the Serial Monitor the string you would like to display on the LCD.
For example, we enter “123456789” and press “Send”:
Code Reference
The required settings of each model of LCD might be different, the constructor we use in this example is:
LiquidCrystal_I2C(uint8_t lcd_Addr, uint8_t En, uint8_t Rw, uint8_t Rs,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7,
uint8_t backlighPin, t_backlighPol pol);
And the setting parameters are as follows:
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address
The first parameter 0x27 is the address of I2C. Each of the following 8 parameters represents the meaning of each bit in a byte, i.e., En is bit 2, Rw is bit 1, Rs is bit 0, d4 is bit 4, and so forth.
backlight()
to light the screen,setCursor(0, 0)
to set the position of the cursor.lcd.print()
to output string on the screen.I2C - Use I2C to receive data from Arduino UNO
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Arduino UNO x 1
Example
Setting up Arduino Uno to be I2C Slave
“Tools” -> “Board” ->
“Arduino Uno”
:“Examples” -> “Wire” -> “slave_sender”
Then click “Sketch” -> “Upload” to compile and upload the example to Arduino Uno.
Setting up Ameba to be I2C Master
“File” -> “Examples” -> “AmebaWire” -> “MasterReader”
Wiring
Code Reference
Wire.begin()
/ Wire.begin(address)
to join the I2C bus as a
master or slave, in the Master case the address is not required.Wire.requestFrom()
to specify from which Slave
to request data.UART - Communicate with the computer via UART
Introduction of UART
UART uses two wire, one for transmitting and the other one for receiving, so the data transmission is bidirectional. The communication uses a predefined frequency (baud rate) to transmit data. In Arduino, UART is called “Serial”. There is only one hardware UART on Arduino Uno and it is primarily used to read the log and messages printed by Arduino (so it is also called “Log UART”). If we use the hardware UART for other purposes, the Log UART does not have resources to function. To provide more UART connections, it is possible to use a GPIO pin to simulate the behavior of UART with a software approach, this is called Software Serial. Ameba is equipped with several hardware UART ports, but it is also compatible with the Software Serial library.
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
USB to TTL Adapter x 1
Example
Install USB to TTL Adapter
Executing the Example
“File” -> “Examples” ->
“AmebaSoftwareSerial” -> “SoftwareSerial_Basic”
:Next, open a serial port terminal, such as Putty or Tera Term. (Putty is used in this example). Open the Putty window, choose “Serial” in connection type, and specify the port number of the USB to TTL adapter (e.g. COM8). In the speed field, fill in the baud rate of this connection. Note that both sides of the connection should use the same baud rate. In this example we set baud rate 4800.
Next, select “Serial” on the left side. Set data bits to 8, stop bits to 1, parity to none, and flow control to none.
Then click Open and press the reset button on Ameba. You can see the “Hello, world?” message appears in Putty. If characters are typed into Putty, the input characters would be sent to Serial RX of Ameba by TX of USB to TTL Adapter, and returned by Serial TX of Ameba. Finally, RX of USB to TTL Adapter receives the returned characters and prints them in Putty. Therefore, if you insert “I am fine”, you will get something like this:
Code Reference
SoftwareSerial:begin(speed)
to set the baud rate for the
serial communication:write()
to send data, and use SoftwareSerial:available()
to get the
number of bytes available for reading from a software serial port:UART - Retrieve GPS Position
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Adafruit Ultimate GPS Breakout x 1 (Refer to official document)
Example
In this example, we use Adafruit Ultimate GPS Breakout. Its data format
is pure text, so we can connect it to USB to TTL Adapter and observe the
output.
It follows the NMEA sentence format (refer to http://aprs.gids.nl/nmea/)
The GPS signal is weak in indoor environment.
The status that the GPS signal is not received is called “not fix”.
Bring the GPS module outdoors, when the GPS signal is “fix”,
you would get message similar to the figure below.
First field is the GMT time (Greenwich Mean Time), that is 032122.000 in this example. The time format is HH:MM:SS.SSS, i.e., 03:21:22.000. Note that the time zone and the daylight-saving time adjustment should be handled on your own.
Second field represents the status code
V: Void (Invalid)
A: Active, meaning the GPS signal is fix.
The third to sixth fields represent the geolocation
In this example, 2446.8181,N represents 24 degrees 46.8181 minutes north latitude, and 12059.7251,E represents 120 degrees 59.7251 minutes east longitude.
We can search +24 46.8181’, +120 59.7251’ in Google map
to check whether the position is correct.
The seventh field is relative speed(knot). 1 knot = 1.852km/hr, in this example the relative speed is 0.39 knot.
The eighth field is the moving angle, which is calculated by its moving orbit.
The ninth field is the date with format ddMMyy. In this example, “270116” stands for day 27, January, year 2016.
The last field is checksum. In the example we have *53 as checksum.
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Open the example in “Files” -> “Examples” ->
“AmebaSoftwareSerial” -> “Adafruit_GPS_parsing”
.
UART – Set Callback Function For UART Communications
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
USB to TTL Adapter x 1
Example
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Open the example in “File” -> “Examples” -> “AmebaSoftwareSerial” ->
“SoftwareSerial_Irq_Callback”
Once the serial port is open, type in the terminal and press the enter key, and you will see the corresponding output.
Code Reference
mySerial.setAvailableCallback(mySerialCallback);
is used to set the
function mySerialCallback as a callback function for software serial.
When a new character is received, the callback function checks if the
character corresponds to the enter key, and releases the semaphore if it
is true, which in turn allows the main loop to print out all the
previously received characters.
PM2.5 Concentration in The Air
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
PlanTower PMS3003 or PMS5003 x 1
Example
PMS3003 (or PMS5003) is a sensor of air quality, it can detect the concentration of those 0.3 to 10 micrometer particulate matters in the air. The sensor output its data via UART.
The PMS3003 (or PMS5003) sensor detects the concentration value of PM 1.0, PM 2.5, PM 10. Take PM 2.5 for example, it stands for the fine particles with a diameter of 2.5 micrometers or less.
Open the example in “File” -> “Examples” -> “AmebaSoftwareSerial” -> “PMS3003_AirQuality”
There are 8 pins in PMS3003:
PMS3003 requires 5V power, but the working voltage of its IC is 3.3C. Therefore, the working voltage of Reset, TX, RX, Set are 3.3 as well. If the “Set” pin is pulled to high, the PMS3003 is put to operating mode. If the “Set” pin is pulled low, the PMS3003 is put to standby mode.
TX/RX pins are for UART connection. Under operating mode, PMS3003 output the data it reads continuously. Each data is of 32 byte, please refer to the following article for detailed data format information:
https://www.dfrobot.com/wiki/index.php?title=PM2.5_laser_dust_sensor_SKU:SEN0177 RTL8722
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
In this example, we do not use the “Set” and “Reset” pins.
Compile the code and upload it to Ameba. After pressing the Reset button, Ameba starts to output the PM 2.5 data to serial monitor.
Flash Memory - Store data in FlashEEProm
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
Code Reference
By default, the Flash Memory API uses address 0xFF000~0xFFFFF to store data.
There is limitation when writing to flash memory. That is, you can not directly write data to the same address you used in last write. To do that correctly, you need erase the sector first. The Flash API of Ameba uses a 4K SRAM to record the user modification and do the erase/write task together.
FlashMemory.read()
to read from Flash memory.FlashMemory.buf[0] = 0x00;
to manipulate the 4K buf.FlashMemory.update();
to update the data in buf to Flash Memory.Flash Memory - Use Flash Memory Larger Than 4K
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” ->
“AmebaFlashMemory” -> “ReadWriteOneWord”
Code Reference
We can use the flash api we used in previous flash memory example, but
we need to use begin()
function to specify the desired starting address
and memory size.
FlashMemory.begin(0xFC000, 0x4000);
Use readWord()
to read the value stored in a memory address. In the
example, we read the value stored in memory offset 0x3F00, that is
0xFC000 + 0x3F00 = 0xFFF00. readWord()
function reads a 32-bit value and
returns it.
value = FlashMemory.readWord(0x3F00);
Use writeWord()
to write to a memory address. The first argument is the
memory offset, the second argument is the value to write to memory.
FlashMemory.writeWord(0x3F0C, value);
SPI – Print Image And Text On LCD Screen
If you are not familiar with SPI, please read Introduction to SPI first.
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
ILI9341 TFT LCD with SPI interface x 1
Example
We have tested the following two models of ILI9341 TFT LCD with SPI interface:
Adafruit 2.8″ TFT LCD (with touch screen)
QVGA 2.2″ TFT LCD
Common pins in ILI9341 TFT LCD with SPI interface:
MOSI: Standard SPI Pin
MISO: Standard SPI Pin
SLK: Standard SPI Pin
CS: Standard SPI Pin
RESET: Used to reboot LCD.
D/C: Data/Command. When it is at Low, the signal transmitted are commands, otherwise the data transmitted are data.
LED (or BL): Adapt the screen backlight. Can be controlled by PWM or connected to VCC for 100% backlight.
VCC: Connected to 3V or 5V, depends on its spec.
GND: Connected to GND.
RTL8722DM / RTL8722CSM and QVGA TFT LCD Wiring Diagram:
RTL8722DM MINI and QVGA TFT LCD Wiring Diagram:
RTL8722DM / RTL8722CSM and Adafruit 2.8』』 TFT LCD touch shield Wiring Diagram:
RTL8722DM MINI and Adafruit 2.8』』 TFT LCD touch shield Wiring Diagram:
Open the example, “Files” -> “Examples” -> “AmebaSPI” -> “ILI9341_TFT_LCD_basic”
Code Reference
RGB 16-bit
ILI9341 uses RGB 16-bit to display colors. Different from RGB 24-bit, it uses 5 bits for red, 6 bits for green, 5 bits for blue. For example, the RGB 24-bit representation of sky blue is 0x87CEFF, that is in binary:
Red: 0x87 = B10000111
Green: 0xCE = B11001110
Blue: 0xFF = B11111111
and converted to RGB 16-bit:
Red: B10000
Green: B110011
Blue: B11111
Then concatenate them, which forms B1000011001111111 = 0x867F
Drawing of ILI9341
First you must specify the range of the rectangle to draw, then pass the 2-byte RGB 16-bit color to ILI9341 corresponding to each pixel one by one, in this way ILI9341 fills each color to each pixel.
You still must specify the drawing range even though the range covers only one pixel.
From the rules we mentioned above, we can conclude that drawing vertical or horizontal lines are faster than diagonal lines.
Printing text on ILI9341
In our API, each character is 5×7 but each character is printed to size 6×8 (its right side and below are left blank), so as to separate from next character. For example, the character “A”:
The font size represents the dot size. For example, if the font size is 2, each dot in the character is a 2×2 rectangle
Screen rotation
ILI9341 provides 0, 90, 180, 270 degrees screen rotation.
If the original width is 240 and original height is 320, when the screen rotates 90 degrees, the width becomes 320 and the height becomes 240.
SPI – Show PM2.5 Concentration On ILI9341 TFT LCD
If you are not familiar with SPI, please read Introduction to SPI first.
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
ILI9341 TFT LCD with SPI interface x 1
Plantower PMS3003 or PMS5003 x 1
Example
Open the example, “Files” -> “Examples” -> “AmebaSPI” -> “PM25_on_ILI9341_TFT_LCD”
Compile and upload to Ameba, then press the reset button.
Then you can see the concentration value of PM1.0, PM2.5 and PM10 on the LCD.
Code Reference
In this example, first rotate the screen by 90 degrees, and draw the static components such as the circles, the measuring scale, and the title text. After the concentration value is detected, it is printed inside the circle.
Timer - Using The Periodic GTimer
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] / [RTL8720DN(BW16)] x 1
Example
“File” -> “Examples” -> “AmebaGTimer” -> “TimerPeriodical”
. Compile and upload to Ameba, and press reset.Code Reference
GTimer.begin(0, 1 * 1000 * 1000, myhandler);
The GTimer is periodic by default, therefore “myhandler” function is
called every second. When we want to stop the GTimer, use stop()
:
GTimer.stop(0);
Timer - Using The Single-Use GTimer
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] / [RTL8720DN(BW16)] x 1
Example
In this example, we will use 4 One-Time GTimer, and pass user data to each timer.
Open the example “File” -> “Examples” -> “AmebaGTimer” -> “TimerOneshot”
.
Compile and upload to Ameba, and press reset.
Then you can see the 4 timer log printed to the serial monitor in series.
Code Reference
The first argument of begin() is the Timer ID (0~3). The second argument is the value of the timer (in microseconds). In the example, we fill in 1000000us = 1s. The third argument specifies the function to call when the time is up. The fourth argument is to set whether this timer is a periodic timer, we use “false” here to begin a single-use timer. The fifth argument is the user data, we give 0 here to represent that this is timer 0.
GTimer.begin(0, 1 * 1000 * 1000, myhandler, false, 0);
Next, we set up the second timer, which has timer value 2 seconds, and user data 1. And other timers are set similarly.
GTimer.begin(1, 2 * 1000 * 1000, myhandler, false, 1);
In myhandler function, we print the user data to serial monitor. Since the 4 timers are separately set to count for 1, 2, 3, 4 seconds, from 1 second to 4 second, the user data of each timer are printed on the serial monitor in order. After 4 second, no log will be printed.
Power Save Deep Sleep Mode
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
Introduction
Ameba-D supports two low power modes which are deepsleep mode and sleep mode. Deepsleep mode turns off more power domain than sleep mode. The power consumptions of DeepSleep Mode is around 7uA to 8uA compare to normal state around 22mA. This example describes how to enter deepsleep mode and configure wakeup source.
“File” -> “Examples” -> “AmebaPowerSave” -> “DeepSleepMode”
DS_WAKEUP_SOURCE
is used to set the wake-up source, user can chose 3
wake up sources now,AON timer (SET_DS_AON_TIMER_WAKEUP);
AON pins (SET_DS_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON timer can be set from 0 to 32760000 range (unit ms) by
AON_TIMER_SLEEP_DURATION
There are 4 pins can be set as AON pins and active high for wake-up,
D16, D17, D26 and D27. The AON pin can be set by
SET_DS_AON_WAKEPIN_WAKEUPPIN
RTC timer wake-up system by set alarm. The alarm has 4 values, day,
hour, min and sec. All 4 values can be set by DS_RTC_ALARM_DAY
,
DS_RTC_ALARM_HOUR
, DS_RTC_ALARM_MIN
, and DS_RTC_ALARM_SEC
When finished the condition values setting, system will run and switch between normal and deepsleep mode controlled by wakeup source. Serial Monitor displays the switching log.
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
Power Save Deep Sleep DHT Eink
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
DHT11 or DHT22 or DHT21 x 1
LCD I2C screen x 1
Example
“File” -> “Examples” -> “AmebaPowerSave” ->
“DeepSleep_DHT_Eink_Example”
DS_WAKEUP_SOURCE
is used to set the wake-up source, user can chose 3
wake up sources now,AON timer (SET_DS_AON_TIMER_WAKEUP);
AON pins (SET_DS_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON timer can be set from 0 to 32760000 range (unit ms) by
AON_TIMER_SLEEP_DURATION
There are 4 pins can be set as AON pins and active high for wake-up,
D16, D17, D26 and D27. The AON pin can be set by
SET_DS_AON_WAKEPIN_WAKEUPPIN
RTC timer wake-up system by set alarm. The alarm has 4 values, day,
hour, min and sec. All 4 values can be set by DS_RTC_ALARM_DAY
,
DS_RTC_ALARM_HOUR
, DS_RTC_ALARM_MIN
, and DS_RTC_ALARM_SEC
DHTPIN
is used to set DHT sensor data pin. User can choose any GPIO
pins.DHTTYPE
is used to set DHT sensor type. (DHT11, DHT22 and DHT33)When finished the condition values setting, system will run and switch between normal working mode and deepsleep mode controlled by wakeup source. Eink screen will display the temperature and humidity data measured from DHT sensor when system is awake.
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
Power Save Deep Sleep DHT LCD
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
DHT11 or DHT22 or DHT21 x 1
LCD I2C screen x 1
Example
Introduction
Ameba-D supports low power modes which are deepsleep mode. Deepsleep mode turns off most of the system power domain. The power consumptions of core module in DeepSleep Mode is around 7uA to 8uA compare to normal state around 22mA. This example gives demo of system switch between “working” and “sleep”(power save).Using DHT sensor to read data and display on LCD screen when system is awake. After 5 seconds system auto enter DeepSleep Mode for power save. System will wake up by wakeup source.( Aon timer, Aon Pins or RTC timer).
“File” -> “Examples” -> “AmebaPowerSave” ->
“DeepSleep_DHT_LCD_Example”
DS_WAKEUP_SOURCE
is used to set the wake-up source, user can chose 3
wake up sources now,AON timer (SET_DS_AON_TIMER_WAKEUP);
AON pins (SET_DS_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON timer can be set from 0 to 32760000 range (unit ms) by
AON_TIMER_SLEEP_DURATION
There are 4 pins can be set as AON pins and active high for wake-up,
D16, D17, D26 and D27. The AON pin can be set by
SET_DS_AON_WAKEPIN_WAKEUPPIN
RTC timer wake-up system by set alarm. The alarm has 4 values, day,
hour, min and sec. All 4 values can be set by DS_RTC_ALARM_DAY
,
DS_RTC_ALARM_HOUR
, DS_RTC_ALARM_MIN
, and DS_RTC_ALARM_SEC
DHTPIN
is used to set DHT sensor data pin. User can choose any GPIO
pins.DHTTYPE
is used to set DHT sensor type. (DHT11, DHT22 and DHT33)When finished the condition values setting, system will run and switch between normal working mode and deepsleep mode controlled by wakeup source. LCD screen will display the temperature and humidity data measured from DHT sensor when system is awake.
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
Power Save Tickless Mode
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
Introduction
Ameba-D supports two low power modes which are deepsleep mode and sleep mode. The power consumptions of Tickless Sleep Mode is around 28uA to 30uA compare to normal state around 15mA. This example describes how to use freertos tickless with uart interruptable interface.
“File” -> “Examples” -> “AmebaPowerSave” -> “TicklessMode”
DS_WAKEUP_SOURCE
is used to set the wake-up source, user can chose 3
wake up sources now,AON timer (SET_DS_AON_TIMER_WAKEUP);
AON pins (SET_DS_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON timer can be set from 0 to 32760000 range (unit ms) by
AON_TIMER_SLEEP_DURATION
There are 4 pins can be set as AON pins and active high for wake-up,
D16, D17, D26 and D27. The AON pin can be set by
SET_DS_AON_WAKEPIN_WAKEUPPIN
RTC timer wake-up system by set alarm. The alarm has 4 values, day,
hour, min and sec. All 4 values can be set by DS_RTC_ALARM_DAY
,
DS_RTC_ALARM_HOUR
, DS_RTC_ALARM_MIN
, and DS_RTC_ALARM_SEC
There are 4 pins can be set as AON pins and active high for wake-up,
D16, D17, D26 and D27. The AON pin can be set by
SET_TL_AON_WAKEPIN_WAKEUP
TL_SYSACTIVE_TIME
is for setting time duration of the system to keep
alive. (unit ms)
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
Use NTPClient Library To Obtain Local Time
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
In this example, we use an NTP client to sync with NTP
servers using UDP and keep track of time locally.
Open the example.
“File” -> “Examples”-> “NTPClient” -> “Advanced”
Code Reference
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000);
begin()
function, which causes the client to sync with the NTP
server and get the UTC time.WiFiUDP ntpUDP;
timeClient.begin();
getFormattedTime()
is used to format the received UTC
time into the local time zone. update()
is called every loop so that the
NTPClient will sync with the NTP server once every update interval.timeClient.update();
timeClient.getFormattedTime();
Transmit IR NEC Raw Data And Decode
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 2
Grove – Infrared Emitter x1 (Figure 1)
Grove – Infrared Receiver x1 (Figure 2)
Example
In this example, we use two Ameba RTL8722 modules that connecting with an infrared (IR) Emitter and an IR Receiver separately to transmit and receive IR NEC Raw data.
For more details, please refer to SB-Projects’ topic of IR Remote Control Theory to learn the theory of IR remote controls operation and a collection of IR protocol descriptions. In this example, we are going to use NEC (Now Renesas, also known as Japanese Format) as the transmission protocol.
8-bit address and 8-bit command length.
Extended mode available, doubling the address size.
Address and command are transmitted twice for reliability.
Pulse distance modulation.
The carrier frequency of 38kHz.
Bit time of 1.125ms or 2.25ms.
Since a total number of 32-bit data together with the header and the end-bit will be transferred (Figure 5). If we separate the data in the time-frame (in us), there will be ( 2 + 32 ) x 2 + 1 = 69 “marks” / “spaces” to be transmitted (Figure 6), which forms the raw NEC data we would like to transmit in our Arduino “*.ino” file. This part of the code can be modified by users. Details of how to obtain raw data code for your remote devices, you may refer to Ken Shirriff’s blog, where it provides multiple libraries provided online.
Figure 7 and 8 shows the pin configuration of IR Emitter and Receiver with Ameba RTL8722 board.
Figure 9 and Figure 10 shows the pin configuration of IR Emitter and Receiver with Ameba RTL8722DM MINI.
After the connection is being set up correctly, we will move to the coding part for this example. First, make sure the correct Ameba development board is selected in Arduino IDE: “Tools” -> “Board”.
Open the “IRSendRAW” example in “File” -> “Examples” -> “AmebaIRDevice”
-> “IRSendRAW”
(Figure 11) and upload to 1st board connected with IR
Emitter:
After successfully upload the sample code for IRSendRaw, you might need
to upload the IRRecvNEC example for the 2nd board connected with IR
Receiver from “File” -> “Examples” -> “AmebaIRDevice” -> “IRRecvNEC”
.
After opening the serial monitor on the IR Receiver side and press the reset buttons on two boards, the data “48” will be received every 3 seconds (due to the delays () function, not compulsory to wait). After decoding the signal from the receiving Pin D8 and transmitting Pin D9 with Logic Analyser and Pulse View (Figure 10), the result is also shown as “48” after decoding the receiving data with IR NEC Protocol.
Code Reference
E-Paper - Display Images
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
Front view of the e-Paper Module:
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
RTL8720DN(BW16) Wiring Diagram:
Firstly, you need to prepare a picture/photo in the format of 296×128 pixels. We can easily find a photo resizing tool online, for example, the Online Image Resizer.
Following the instructions on the website, then download the generated image in JPG format.
Secondly, we use the Image2LCD tool to transfer the downloaded 296×128 image into hexadecimal codes. You can visit this YouTube link to get detailed instructions.
“File” → “Examples” → “AmebaEink” → “EinkDisplayImage”
:Code Reference
E-Paper - Display Text
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
Front view of the e-Paper Module:
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
RTL8720DN(BW16) Wiring Diagram:
“File” -> “Examples” -> “AmebaEink” -> “EinkDisplayText”
:Upload the code to the board and press the Reset button after the uploading is done. You will find these texts displayed on the board:
Code Reference
[1] We use Good Display GDEH029A1 2.9 Inch / 296×128 Resolution / Partial Refresh Arduino Sample Code to get the e-Paper successfully Display: http://www.good-display.com/product/201.html
E-Paper - Display User-generated QR Code
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
Front view of the e-Paper Module:
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
RTL8720DN(BW16) Wiring Diagram:
Modify the URL in the loop() section as your wish, after that, verify and upload the code to the Ameba board. Upon successfully upload the sample code and press the reset button, a QR code generated based on the URL of your input will be shown on the E-Paper module. The QR code showing below leads to our Ameba IoT official website: Ameba ARDUINO
Code Reference
A Simple RTC Example
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
This example demonstrates how to use the RTC library methods. This function describes how to use the RTC API. The RTC function is implemented by an independent BCD timer/counter.
"File" -> "Examples" -> "AmebaRTC" -> "RTC"
:Upon successfully upload the sample code and press the reset button, this example will print out time information since the user initialized time every second in the Serial Monitor.
Code Reference
A Simple RTC Alarm
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
This example demonstrates how to use the RTC library methods to create a RTC Alarm, so that to do some tasks when an alarm is matched. In particular, the RTC time is set at 16:00:00 and an alarm at 16:00:10. When the time matches, “Alarm Match” information will be printed on the serial monitor.
First, select the correct Ameba development board from the Arduino IDE: “Tools” -> “Board”.
Then open the 「RTCAlarm」 example from:
“File” -> “Examples” -> “RTC” -> “RTCAlarm”
:
In the example, the RTC time is set at 16:00:00 and an alarm is set at 16:00:10. Upon successfully upload the sample code and press the reset button. When the alarm time (10 seconds) is reached the attached interrupt function will print the following information: “Alarm Matched!” showing in this figure below.
Watchdog Timer Simple Example
Preparation
AmebaD RTL8722CSM/RTL8722DM/RTL8722DM MINI Board x 1
Example
In this example, we will use this simple watchdog timer example runs on the Ameba RTL8722 module to illustrate how to use the watchdog API. Before we get into the details of the example, let’s briefly go through the definition of Watchdog as well as it’s working principles.
Watchdog
Watchdog Timer (WDT) is a hardware timer that is used to detect the occurrence of a software fault, then automatically generates a system reset or a watchdog interrupt on the expiry of a programmed period.
In layman terms, imagine in the situation while your micro-controller is confused in an infinity loop, or any case like the micro-controller hang while performing some tasks. The normal troubleshooting method would be to press the reset button and jump out of the infinity loop. However, is it practically impossible to do press on the button all time, therefore, the watchdog timer that embedded inside the micro-controller would help with this situation.
Feed the Dog
“Tools” -> “Board” -> “RTL8722CSM/RTL8722DM” (or “RTL8722DM MINI”)
.
Then open the “Watchdog Timer” example in “File” -> “Examples” -> “AmebaWatchdog” ->
“Watchdog Timer”
:Audio Codec – Basic Input Output
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Potentiometer x 1
Analog microphone x 1 (e.g., Adafruit 1063 / 1064)
3.5mm TRS/TRRS breakout x 1 (e.g., Adafruit 2791 / Sparkfun 11570)
Example
Open the example, "Files" -> "Examples" -> “AmebaAudioCodec” ->
“BasicInputOutput”
.
Upload the code and press the reset button on Ameba once the upload is finished.
Connect a pair of wired headphones to the 3.5mm audio jack, blow at the microphone, and you should hear the sounds picked-up by the microphone replayed in the headphones. Adjust the potentiometer and the output volume will change as well. Note: if you are using a microphone with an amplifier included, such as Adafruit 1063, the amplifier can lead to the microphone picking up more noise.
Audio Codec - FFT
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
"Files" -> "Examples" -> “AmebaAudioCodec” -> “FFT”
.Audio Codec - Input FFT
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Analog microphone x 1 (e.g., Adafruit 1063 / 1064)
Example
Next, open the example, "Files" -> "Examples" -> “AmebaAudioCodec” ->
“InputFFT”
.
Audio Codec – Output Sine Wave
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
3.5mm TRS/TRRS breakout x 1 (e.g., Adafruit 2791 / Sparkfun 11570)
Example
Procedure
Open the example, "Files" -> "Examples" -> “AmebaAudioCodec” ->
“OutputSineWave”
.
Audio Codec – Play and Record Wav Files
Materials
AmebaD [RTL8722DM MINI] x 1
MicroSD card
Example
Procedure
As RTL8722DM MINI have a built in microphone on the board, there is no need for any external microphone. Copy a sample wav file into the MicroSD card for demo. (In this example, the sample name is “Test_Audio_48khz_16bit_stereo.wav”. ) Then insert the MicroSD card into the adapter at the back of the board.
Example 01 PlaybackWavFile
Open the example, “Files” -> “Examples” -> “AmebaAudioCodec” -> “PlaybackWavFile”
.
Upload the code and press the reset button on Ameba once the upload is finished. Insert earphone/speaker into the onboard jack for playing the sample sound.
Example 02 RecordWavFile
Open the example, “Files” -> “Examples” -> “AmebaAudioCodec” -> “RecordWavFile”
.
Example 03 RecordPlaybackWav
Open the example, “Files” -> “Examples” -> “AmebaAudioCodec” -> “RecordPlaybackWav”
.
FatfsSDIO – File system in SD card
Materials
Ameba D [RTL8722DM MINI] x 1
MicroSD card
Example
Procedure
Insert a MicroSD card into the onboard SD card reader of RTL8722DM MINI board.
Example 01 create_folder
Open the example, "Files" -> "Examples" -> “AmebaFatfsSDIO” -> “create_folder”
.
Next, insert SD card into card reader, and check whether the operations succeeded.
Example 02 file_read_write
"Files" -> "Examples" -> “AmebaFatfsSDIO” ->
“file_read_write”
.Next, insert SD card into card reader, and check whether the operations succeeded.
Example 03 get_file_attribute
"Files" -> "Examples" -> “AmebaFatfsSDIO” ->
“get_file_attribute”
.Example 04 last_modified_time
"Files" -> "Examples" -> “AmebaFatfsSDIO” ->
“last_modified_time”
.Next, insert SD card into card reader, and check whether the operations succeeded.
Example 05 list_root_files
"Files" -> "Examples" -> “AmebaFatfsSDIO” ->
“list_root_files”
.Next, insert SD card into card reader, and check whether the operations succeeded. In this case, we already know the root files folder “testdir” and text file “test.txt”by refer the above pictures.
FatfsSDIO – Read And Open HTML File From SD Card
Materials
AmebaD [RTL8722DM MINI] x 1
MicroSD card
Example
Insert the MicroSD card into your computer and copy the HTML file to your SD card (Note: put the file at outside and do not put it inside of any folder in the SD card). Here is a HTML sample for testing, “Web_test.html”.
“Files” -> “Examples” -> “AmebaFatfsSDIO” -> “read_html_from_SD_card”
Next, open the address stated in serial monitor in the browser of your laptop or cell phone under the same WiFi domain. You will see the following display in your browser:
Now you have successfully read and opened the html file saved in your SD card.
TensorFlow Lite - Hello World
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
LED x 1
Example
Procedure
Download the Ameba customized version of TensorFlow Lite for Microcontrollers library at https://github.com/ambiot/ambd_arduino/tree/master/Arduino_zip_libraries. Follow the instructions at https://www.arduino.cc/en/guide/libraries to install it. Ensure that the patch files found at https://github.com/ambiot/ambd_arduino/tree/master/Ameba_misc/ are also installed.
Open the example, "Files" -> "Examples" -> “TensorFlowLite_Ameba” ->
“hello_world”
.
Code Reference
More information on TensorFlow Lite for Microcontrollers can be found at: https://www.tensorflow.org/lite/microcontrollers
TensorFlow Lite - Magic Wand
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Adafruit LSM9DS1 accelerometer
LED x 2
Example
Procedure
"Files" -> "Examples" -> “TensorFlowLite_Ameba” ->
“magic_wand”
.Code Reference
More information on TensorFlow Lite for Microcontrollers can be found at: https://www.tensorflow.org/lite/microcontrollers
TensorFlow Lite - Micro Speech
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Adafruit PDM MEMS microphone
LED x 4
Example
Procedure
"Files" -> "Examples" -> “TensorFlowLite_Ameba” ->
“micro_speech”
.If you are having trouble in getting the words recognized, here are some tips:
Ensure that your surroundings are quiet with minimal noise.
Experiment with varying the distance of the microphone, starting with it at an arm’s length.
Experiment with different tones and volume when saying the words.
Depending on how you pronounce the words, the characteristics of the microphone used, getting one keyword recognized may be easier than the other.
Code Reference
More information on TensorFlow Lite for Microcontrollers can be found at: https://www.tensorflow.org/lite/microcontrollers
TensorFlow Lite - Person Detection
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Arducam Mini 2MP Plus OV2640 SPI Camera Module x 1
LED x 3
Example
Procedure
Arduino/libraries/JPEGDecoder/src/User_Config.h
#define LOAD_SD_LIBRARY
and #define
LOAD_SDFAT_LIBRARY
are commented out, as shown in this excerpt from the
file://#define LOAD_SD_LIBRARY // Default SD Card library
//#define LOAD_SDFAT_LIBRARY // Use SdFat library instead, so SD Card SPI can be bit bashed
Open the example, "Files" -> "Examples" -> “TensorFlowLite_Ameba” ->
“person_detection”
.
Code Reference
More information on TensorFlow Lite for Microcontrollers can be found at: https://www.tensorflow.org/lite/microcontrollers
Download
Release History
Version 3.1.1 - 2021/12/25
Feature:
Add BLE HID and examples
BLEHIDGamepad, BLEHIDKeyboard, and BLEHIDMouse
Update PowerSave examples
Support RTL8722DM MINI and RTL8720DN/BW16
Enable LwIP hostname edit
API Updates:
Update API for PowerSave
Update ameba_d_tools 1.0.7 for all 3 platforms
Support RTL8720DN/BW16 and RTL8722DM MINI
Add more Aon wake up pins
Update API for IR
Removed requirement to define both IR TX and RX pins in IRDevice::begin
Removed previous limit on number of time durations IRDevice::send can accept
Update GPIO Int
Enable INPUT_IRQ_CHANGE
Add definition inside wiring_constants.h and wiring_digital.c, also complete the TODO part for attachInterrupt() as well
Update UART, for RTL8720DN/BW16 not showing log issue
Fix wrong attribute permissions for characteristic CCCD descriptor. Remove unused variable warnings
Update GTimer, for the internal timer ID validation test
Updated SPI connection for RTL8720DN/BW16
Update Google_Cloud_IoT example with new Google TLS cert
Update Analog Pin remove A0 and A1
Update Platform.txt for Windows OS with User Name having a space in between
Update all libs
Misc:
Update AmebaEink.zip, SPI connection for RTL8720DN/BW16
Add Autoflash_patch folder
Update the Fritzing of RTL8720DN/BW16, remove A0 and A1
Version 3.1.0 - 2021/11/05
Feature:
Support board RTL8720DN(BW16)
Add WiFiControlCar example
Add Arduboy zip library
Add WPA3 support
Add Amebad_HMI_MQTT zip library
Add support for IPV6 wiht 4 examples
WLAN lib update
Minor bug fix
API Updates:
Support Microsoft Azure IoT cloud
Enable “strnlen” from rom
Add “#define yield” for compilation
Update PubSubClient lib
Update APIs for RTL8720DN(BW16) (SPI, I2C, Fatfs, Audiocodec and UART
Update jtag enable functions
Update wifi security option
Remove the unused libs lib_wifi_fw.a lib_wifi_ucps_fw.a
Update watchdog
Update AudioCodec
Pin mapping updates
Remove unused marcos
RTL8720DN(BW16) related naming update for all examples
Update PowerSave
Misc
Add RTL8720DN_BW16 frizting folder
Move RTL8720DN_BW16 frizting files to correct folder
Rename folder name to short the length of path
Add Offline_SDK_installation_tool (Windows, Linux and MacOS)
Update linux tools for compatibility issue
Update RTL8722DM MINI and RTL8720DN(BW16) Fritzing and Pinmux
Update ameba_d_tools V1.0.6
Add Image_Releated folder
Correct the core from Cortex-M4 to Cortex-M33
Version 3.0.11 - 2021/10/26
Feature:
Add example, FatfsSDIO - Read and open HTML file from SD card
API Updates:
RTL8720DN/BW16 related compatibility update for all examples
Misc
Update RTL8722DM MINI and RTL8720DN Fritzing and Pinmux
Version 3.0.10 - 2021/09/22
Feature:
Add AudioCodec wav examples
API Updates:
Pin mapping updates for RTL8722DM MINI
Remove unused marcos
Update platform.txt for bin files process
rollback for “wifi.h” update
Minor bug fix patch
Version 3.0.9 - 2021/09/13
API Updates:
Pin mapping updates
Remove unused marcos
“wifi.h” related files change to “Amebawifi.h”
Version 3.0.8 - 2021/05/06
Feature:
Add RTL8722DM_mini board
Add fatfs for SD card
Add AudioCodec
Add TensorFlow lite support with examples
Add zip libraries for TensorFlow lite support
Update SDK for supporting Arduino IDE 2.0
Update wlan lib
API Updates:
Update zip libraries of Eink
ADC updates, Change calculation method to use EFUSE calibration parameters and SDK formula to improve accuracy
writing_analog updates, minor bug fix and support for mini board
SPI updates, minor bug fix and support for mini board
I2S updates, minor bug fix and support for mini board
IRDevice updates, minor bug fix
Version 3.0.7 - 2020/11/19
Feature:
Add AmebaIRDevice example IRSendSONY
Update Ameba Arduino IRDevice API
Update Ameba Arduino SSL related API
Update Ameba Arduino Wlan API to support static IP function
Version 3.0.6 - 2020/10/28
Feature:
Add Ameba RTC support
Add AmebaRTC example RTC and RTCAlarm
Add Ameba Watchdog support
Add AmebaWatchdog example WatchdogTimer
Update Ameba BLE support
Add AmebaBLE example BLEUartService, DHT_over_BLEUart
Update Ameba Wlan library
Update Ameba Wlan SDK structure, add AP mode hidden SSID support
Version 3.0.5 - 2020/09/09
Feature:
Build in tool updates V1.0.4
Add zip lib AmebaEink
Add AmebaEink example EinkDisplayImage, EinkDisplayQR, and EinkDisplayText
Add google cloud examples
Update Amazon AWS related examples
Add power save support
Add AmebaPowerSave example TicklessMode, DeepSleepMode, DeepSleep_DHT_LCD_Example, and DeepSleep_DHT_Eink_Example
Version 3.0.4 - 2020/07/27
Feature:
Update BLE library. Add example BLEBatteryClient and BLEWIfiConfig
Update from polarssl to mbedtls 2.4.0
Version 3.0.3 - 2020/07/03
Feature:
Build in Image tool updates V1.0.3
Upload log clean up
Version 3.0.2 - 2020/06/30
Feature:
Windows, Linux and macOS X support
Build in Image tool updates
Version 3.0.1 - 2020/05/15
Feature:
Official release of AmebaD Arduino SDK
warning cleaning
I2C lib updates
Version 3.0.0 - 2020/05/01
Feature:
Support Boards Manager and Arduino IDE development
WiFi scan AP, connect to AP, TCP Server/Client, including 5G
Bluetooth, BLE
GPIO digital in/out and interrupt
ADC analog in/out (0 ~ 3.3V)
PWM getting analog results with digital means
SPI master and slave mode
UART 1 for log, 2 for customize usage
I2C master mode
Board HDK
API Documents
RTL8722DM ARDUINO Online API Documents
Analog
Class AmebaServo
Description
Defines a class of manipulating servo motors connected to Arduino pins.
Syntax
class AmebaServo
Members
Public Constructors |
|
---|---|
AmebaServo::AmebaServo |
Constructs an AmebaServo object. |
Public Methods |
|
AmebaServo::attach |
Attach the given pin to the next free channel. |
AmebaServo::detach |
Detach the servo. |
AmebaServo::write |
Write value, if the value is < 200 it’s treated as an angle, otherwise as pulse-width in microseconds. |
AmebaServo::writeMicroseconds |
Write pulse width in microseconds. |
AmebaServo::read |
Output current pulse width as an angle between 0 and 180 degrees. |
AmebaServo::readMicroseconds |
Output current pulse width in microseconds for this servo. |
AmebaServo::attached |
Check if the servo is attached. |
Description
Attach the given pin to the next free channel, sets pinMode (including minimum and maximum values for writes), returns channel number, or 0 if failure.
Syntax
uint8_t attach(int pin);
uint8_t attach(int pin, int min, int max);
Parameters
pin: The Arduino pin number to be attached.
min: Minimum values for writes.
max: Maximum values for writes.
Returns
The function returns channel number or 0
Example Code
Example: ServoSweep
The code demos servo motor sweeping from 0 degrees to 180 degrees then sweep back to 0 degrees in the step of 1 degree.
1 /* Sweep
2 by BARRAGAN < http://barraganstudio.com >
3 This example code is in the public domain.
4 modified 8 Nov 2013
5 by Scott Fitzgerald
6 http://www.arduino.cc/en/Tutorial/Sweep
7 refined 2016/03/18 by Realtek
8 */
9
10 #include "AmebaServo.h"
11
12 // create servo object to control a servo
13 // 4 servo objects can be created correspond to PWM pins
14
15 AmebaServo myservo;
16
17 // variable to store the servo position
18 int pos = 0;
19
20 void setup() {
21 #if defined(BOARD_RTL8195A)
22 // attaches the servo on pin 9 to the servo object
23 myservo.attach(9);
24 #elif defined(BOARD_RTL8710)
25 // attaches the servo on pin 13 to the servo object
26 myservo.attach(13);
27 #elif defined(BOARD_RTL8721D)
28 // attaches the servo on pin 8 to the servo object
29 myservo.attach(8);
30 #else
31 // attaches the servo on pin 9 to the servo object
32 myservo.attach(9);
33 #endif
34 }
35
36 void loop() {
37 // goes from 0 degrees to 180 degrees in steps of 1 degree
38 for (pos = 0; pos <= 180; pos += 1) {
39 // tell servo to go to position in variable 'pos'
40 myservo.write(pos);
41 // waits 15ms for the servo to reach the position
42 delay(15);
43 }
44 // goes from 180 degrees to 0 degrees
45 for (pos = 180; pos >= 0; pos -= 1) {
46 // tell servo to go to position in variable 'pos'
47 myservo.write(pos);
48 // waits 15ms for the servo to reach the position
49 delay(15);
50 }
51 }
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
Description
Detach the servo.
Syntax
void AmebaServo::detach(void);
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AmebaServo::write
Description
Write an integer value to the function, if the value is < 200, it’s being treated as an angle, otherwise as pulse-width in microseconds.
Syntax
void AmebaServo::write(int value);
Parameters
value: The value < 200 its treated as an angle; otherwise as pulse width in microseconds.
Returns
The function returns nothing.
Example Code
Example: ServoSweep
The code demos servo motor sweeping from 0 degrees to 180 degrees then sweep back to 0 degrees in the step of 1 degree. Please refer to code in “AmebaServo:: attach” section.
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AmebaServo::writeMicroseconds
Description
Write pulse width to the servo in microseconds.
Syntax
void AmebaServo::writeMicroseconds(int value);
Parameters
value: Write value the pulse width in microseconds.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AmebaServo::read
Description
The function reads current pulse width and returns as an angle between 0 and 180 degrees.
Syntax
int AmebaServo::read(void);
Parameters
The function requires no input parameter.
Returns
The pulse width as an angle between 0 ~ 180 degrees.
Example Code
NA
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AmebaServo::readMicroseconds
Description
The function returns a Boolean value “true” if this servo is attached, otherwise returns “false”.
Syntax
int AmebaServo::readMicroseconds(void);
Parameters
The function requires no input parameter.
Returns
The function returns current servo pulse width in microseconds.
Example Code
NA
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AmebaServo::attached
Description
It returns true if this servo is attached, otherwise false.
Syntax
bool AmebaServo::attached(void);
Parameters
The function requires no input parameter.
Returns
The function returns a Boolean value as true or false.
Example Code
Example: ServoSweep
The code demos servo motor sweeping from 0 degrees to 180 degrees then sweep back to 0 degrees in the step of 1 degree. Please refer to code in “AmebaServo:: attach” section.
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AudioCodec
Class AudioCodec
Description
A class used for general control and management of the hardware audio codec functions.
Syntax
class AudioCodec
Members
Public Constructors
The public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named Codec.
Public Methods
AudioCodec::begin |
Configure and start the audio codec for transmit and receive operation |
---|---|
AudioCodec::end |
Stop all audio codec operation |
AudioCodec::getBufferPageSize |
Get the byte size of a single page of the audio codec buffer |
AudioCodec::setSampleRate |
Configure the audio codec transmit and receive sampling rate |
AudioCodec::setBitDepth |
Configure the audio codec transmit and receive bit depth (bits per sample) |
AudioCodec::setChannelCount |
Configure the audio codec transmit and receive channel count |
AudioCodec::setInputMicType |
Configure for analog or digital input microphone type |
AudioCodec::setInputLRMux |
Configure input left right channel multiplexing |
AudioCodec::setDMicBoost |
Configure boost gain for digital microphone input |
AudioCodec::setAMicBoost |
Configure boost gain for analog microphone input |
AudioCodec::setADCGain |
Configure gain of ADC used to acquire analog input |
AudioCodec::muteInput |
Mute input audio data stream |
AudioCodec::setOutputVolume |
Configure output audio volume |
AudioCodec::muteOutput |
Mute output audio |
AudioCodec::writeAvaliable |
Check for free buffer page available for data write |
AudioCodec::writeDataPage |
Write audio data to an available buffer page |
AudioCodec::readAvaliable |
Check for buffer page with new data available for read |
AudioCodec::readDataPage |
Read audio data from a ready buffer page |
AudioCodec::setWriteCallback |
Set a callback function to be notified when a free buffer page is available for write |
AudioCodec::setReadCallback |
Set a callback function to be notified when a buffer page with new data is available for read |
AudioCodec::begin
Description
Configure and start the audio codec for transmit and receive operation.
Syntax
void begin(bool input, bool output);
Parameters
input: enable audio codec data input
output: enable audio codec data output
Returns
The function returns nothing.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::end
Description
Stop all audio codec operation.
Syntax
void end();
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
AudioCodec::getBufferPageSize
Description
Get the byte size of a single page of the audio codec buffer.
Syntax
uint32_t getBufferPageSize();
Parameters
The function requires no input parameter.
Returns
The size of a audio codec buffer page, in number of bytes.
Example Code
NA
Notes and Warnings
The AudioCodec class includes a transmit and receive buffer to store audio sample data while transferring to and from the DAC output and ADC input. The buffer is divided into pages of fixed size, and audio data can be read and written one page at a time. Depending on the configured bit depth (bits per audio sample) and channel count, a buffer page may contain a different number of audio samples.
AudioCodec::setSampleRate
Description
Configure the audio codec transmit and receive sampling rate.
Syntax
void setSampleRate(uint32_t sampleRate);
Parameters
sampleRate: desired audio codec sampling rate in Hz. Default value of 48000. Supported values: 8000, 16000, 32000, 44100, 48000, 88200, 96000.
Returns
The function returns nothing.
Example Code
Example: BasicInputOutput
Notes and Warnings
High sample rates above 48000Hz will require frequent buffer reads and writes to keep up with the large amount of data input and output. If there is insufficient processing time dedicated to this task, audio quality will be degraded.
AudioCodec::setBitDepth
Description
Configure the audio codec transmit and receive bit depth (bits per sample).
Syntax
void setBitDepth(uint8_t bitDepth);
Parameters
bitDepth: desired number of bits per sample. Default value of 16. Supported values: 8, 16, 24.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Setting a bit depth of 24 bits per sample will require 32 bits (4 bytes) of buffer space for storing each sample, with the most significant byte ignored.
AudioCodec::setChannelCount
Description
Configure the audio codec transmit and receive channel count.
Syntax
void setChannelCount(uint8_t monoStereo);
Parameters
monoStereo: number of channels. Default value of 1. Supported values: 1, 2.
Returns
The function returns nothing.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::setInputMicType
Description
Configure for analog or digital input microphone type.
Syntax
Void setInputMicType(Mic_Type micType);
Parameters
micType: Input microphone type. Default value ANALOGMIC. Valid values:
ANALOGMIC – microphone with an analog output
PDMMIC – digital microphone with a PDM output
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
For analog single-ended output, connect to PA_4 for the left channel and PA_2 for the right channel.
For digital PDM output, connect the PDM clock to PB_1 and PDM data to PB_2.
AudioCodec::setInputLRMux
Description
Configure input left right channel multiplexing.
Syntax
void setInputLRMux(uint32_t mux);
Parameters
mux: desired left right audio channel multiplexing setting. Default value RX_CH_LR. Valid values:
RX_CH_LR
RX_CH_RL
RX_CH_LL
RX_CH_RR
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
In mono channel mode, both RX_CH_LR and RX_CH_LL will result in the audio codec sampling input data from the left channel microphone. Similarly, both RX_CH_RL and RX_CH_RR will result in the audio codec sampling input data from the right channel microphone.
In stereo channel mode, RX_CH_RL will switch the positions of input data sampled from the microphones. RX_CH_RR and RX_CH_LL will result in duplicated samples from the right and left microphones respectively.** **
AudioCodec::setDMicBoost
Description
Configure boost gain for digital microphone input.
Syntax
void setDMicBoost(uint32_t leftBoost, uint32_t rightBoost);
Parameters
leftBoost: boost gain for left channel digital microphone input
rightBoost: boost gain for right channel digital microphone input
Valid boost gain values:
0 : 0dB
1 : 12dB
2 : 24dB
3 : 36dB
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
AudioCodec::setAMicBoost
Description
Configure boost gain for analog microphone input.
Syntax
void setAMicBoost(uint32_t leftBoost, uint32_t rightBoost);
Parameters
leftBoost: boost gain for left channel analog microphone input
rightBoost: boost gain for right channel analog microphone input
Valid boost gain values:
0 : 0dB
1 : 20dB
2 : 30dB
3 : 40dB
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Only use this function if additional gain is required after using setADCGain function.
AudioCodec::setADCGain
Description
Configure gain of ADC used to acquire analog input.
Syntax
void setADCGain(uint32_t leftGain, uint32_t rightGain);
Parameters
leftGain: Gain for left channel ADC
rightGain: Gain for right channel ADC
Valid value range is from 0x00 to 0x7f. Gain increases by 0.375dB for every increment in value:
0x00 : -17.625dB
0x01 : -17.25dB
0x2f : 0dB
0x30 : 0.375dB
0x7f : 30dB
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
AudioCodec::muteInput
Description
Mute input audio data stream.
Syntax
void muteInput(uint8_t leftMute, uint8_t rightMute);
Parameters
leftMute: 1 to mute left channel input, 0 to unmute
rightMute: 1 to mute right channel input, 0 to unmute
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
AudioCodec::setOutputVolume
Description
Configure output audio volume.
Syntax
void setOutputVolume(uint8_t leftVol, uint8_t rightVol);
Parameters
leftVol: left channel output volume
rightVol: right channel output volume
Valid value ranges from 0 to 100, corresponding to a volume of -65.625dB to 0dB.
Returns
The function returns nothing.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::muteOutput
Description
Mute output audio.
Syntax
void muteOutput(uint8_t leftMute, uint8_t rightMute);
Parameters
leftMute: 1 to mute left channel output, 0 to unmute
rightMute: 1 to mute right channel output, 0 to unmute
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
AudioCodec::writeAvaliable
Description
Check for free buffer page available for data write.
Syntax
bool writeAvaliable();
Parameters
The function requires no input parameter.
Returns
Returns true if there is a buffer page that is available for writing data into. Returns false if all buffer pages are full.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::writeDataPage
Description
Write audio data to an available buffer page.
Syntax
uint32_t writeDataPage(int8_t* src, uint32_t len);
uint32_t writeDataPage(int16_t* src, uint32_t len);
Parameters
src: pointer to array containing audio samples to write to audio codec.
len: number of audio samples in array.
Returns
The function returns the number of audio samples written to the audio codec.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::readAvaliable
Description
Check for buffer page with new data available for read.
Syntax
bool readAvaliable();
Parameters
The function requires no input parameter.
Returns
Returns true if there is a buffer page with new data that is ready for reading data from. Returns false if all buffer pages are empty.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::readDataPage
Description
Read audio data from a ready buffer page.
Syntax
uint32_t readDataPage(int8_t* dst, uint32_t len);
uint32_t readDataPage(int16_t* dst, uint32_t len);
Parameters
dst: pointer to array to contain audio samples read from audio codec.
len: number of audio samples to read.
Returns
The function returns the number of audio samples read from the audio codec.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::setWriteCallback
Description
Set a callback function to be notified when a free buffer page is available for write.
Syntax
void setWriteCallback(void (writeCB)(**void*));
Parameters
writeCB: function to be called when a buffer page becomes available for data write. Takes no arguments and returns nothing
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
After starting the audio codec with AudioCodec::begin(), the callback function will be called each time the audio codec finishes outputting the data in a buffer page.
AudioCodec::setReadCallback
Description
Set a callback function to be notified when a buffer page with new data is available for read.
Syntax
void setReadCallback(void (readCB)(**void*));
Parameters
readCB: function to be called when a buffer page with new data becomes available for data read. Takes no arguments and returns nothing
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
After starting the audio codec with AudioCodec::begin(), the callback function will be called each time the audio codec fills up a buffer page with newly acquired audio samples.
Class FFT
Description
A class used for performing FFT calculations with real-number inputs and outputs.
Syntax
class FFT
Members
Public Constructors
FFT::FFT |
Create an instance of the FFT class |
Public Methods
FFT::setWindow |
Configure the window function used in FFT calculations |
---|---|
FFT::calculate |
Calculate FFT for an input array of values |
FFT::getFrequencyBins |
Get the FFT output frequency bins |
FFT::getFFTSize |
Get the size of FFT output for a given input size |
FFT::FFT
Description
Create a FFT class object.
Syntax
void FFT();
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
Example: FFT
Notes and Warnings
FFT::setWindow
Description
Configure the window function used in FFT calculations.
Syntax
void setWindow(FFTWindow_t window, uint16_t sampleCount);
Parameters
window: The window function to be used in FFT calculations. Valid values: None, Hann, Hamming.
sampleCount: Number of sample datapoints in the input.
Returns
The function returns nothing.
Example Code
Example: FFT
Notes and Warnings
The window function is used to reduce the effects of discontinuities that occur when the input signal has frequencies that do not fit an integer number of periods in the sample datapoints.
More information on FFTs and window functions can be seen at:
https://download.ni.com/evaluation/pxi/Understanding%20FFTs%20and%20Windowing.pdf
https://en.wikipedia.org/wiki/Window_function
FFT::Calculate
Description
Calculate FFT for an input array of values.
Syntax
void calculate(float* inputBuf, float* outputBuf, uint16_t sampleCount);
void calculate(int16_t* inputBuf, float* outputBuf, uint16_t sampleCount);
Parameters
inputBuf: pointer to an array of sampleCount size, containing input sample datapoints, in float or uint16_t format.
outputBuf: pointer to a float array of sampleCount/2 size, for containing FFT output.
sampleCount: number of sample datapoints in the input array, valid values: 16, 32, 64, 128, 256, 512, 1024, 2048.
Returns
The function returns nothing.
Example Code
Example:FFT
Notes and Warnings
Large sample counts will require a longer time for FFT calculations, but will also return a result with higher frequency resolution.
FFT::getFrequencyBins
Description
Get the FFT output frequency bins.
Syntax
void getFrequencyBins(uint16_t* outputBuf, uint16_t sampleCount, uint32_t sampleRate);
Parameters
outputBuf: pointer to a uint16_t array of sampleCount/2 size, for containing the calculated center frequency of each FFT output element.
Returns
The function returns nothing.
Example Code
Example: FFT
Notes and Warnings NA
—
FFT::getFFTSize
Description
Get the size of FFT output for a given input size.
Syntax
uint16_t getFFTSize(uint16_t sampleCount);
Parameters
sampleCount: number of input sample datapoints.
Returns
The function returns the FFT output size for the given sampleCount, which is sampleCount/2.
Example Code
NA
Notes and Warnings NA
Class PlaybackWav
Description
A class used for control and playback of .wav file format audio data.
Syntax
class PlaybackWav
Members
Public Constructors
PlaybackWav::PlaybackWav |
Create an instance of the PlaybackWav class |
Public Methods
PlaybackWav::openFile |
Open a .wav file for playback |
PlaybackWav::closeFile |
Close a previously opened file |
PlaybackWav::fileOpened |
Check if a .wav file is already opened |
PlaybackWav::getSampleRate |
Get the sample rate of the .wav file |
PlaybackWav::getChannelCount |
Get the number of audio channels in the .wav file |
PlaybackWav::getBitDepth |
Get the bit depth of each sample in the .wav file |
PlaybackWav::getLengthMillis |
Get the playback length of the .wav file in milliseconds |
PlaybackWav::getPositionMillis |
Get the current playback position in milliseconds |
PlaybackWav::setPositionMillis |
Set the current playback position in milliseconds |
PlaybackWav::millisToBytes |
Convert a playback duration to equivalent number of bytes |
PlaybackWav::bytesToMillis |
Convert number of bytes to an equivalent playback duration |
PlaybackWav::readAudioData |
Read audio data from the .wav file |
PlaybackWav::PlaybackWav
Description
Create a PlaybackWav class object.
Syntax
void PlaybackWav(void);
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
PlaybackWav::fileOpened
Description
Check if a .wav file is already opened.
Syntax
bool fileOpened(void);
Parameters
The function requires no input parameter.
Returns
The function returns true if a .wav file is already open, false otherwise.
Example Code
Example: RecordPlaybackWav
Notes and Warnings
NA
PlaybackWav::getSampleRate
Description
Get the sample rate of the .wav file.
Syntax
uint32_t getSampleRate(void);
Parameters
The function requires no input parameter.
Returns
The function returns sampling rate encoded in the .wav file header.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
PlaybackWav::getChannelCount
Description
Get the number of audio channels in the .wav file.
Syntax
uint16_t getChannelCount(void);
Parameters
The function requires no input parameter.
Returns
The function returns channel count encoded in the .wav file header.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
PlaybackWav::getBitDepth
Description
Get the bit depth of each sample in the .wav file.
Syntax
uint16_t getBitDepth(void);
Parameters
The function requires no input parameter.
Returns
The function returns bit depth encoded in the .wav file header.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
PlaybackWav::getLengthMillis
Description
Get the playback length of the .wav file in milliseconds.
Syntax
uint32_t getLengthMillis(void);
Parameters
The function requires no input parameter.
Returns
The function returns the total playback length of the currently open .wav file in milliseconds.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
PlaybackWav::getPositionMillis
Description
Get the current playback position in milliseconds.
Syntax
uint32_t getPositionMillis(void);
Parameters
The function requires no input parameter.
Returns
The function returns the current playback position of the currently open .wav file in milliseconds.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
PlaybackWav::setPositionMillis
Description
Set the current playback position in milliseconds.
Syntax
void setPositionMillis(uint32_t pos);
Parameters
pos: The desired playback position expressed in milliseconds.
Returns
The function returns nothing.
Example Code
Example: PlaybackWavFile
Notes and Warnings
Any changes to playback position will only take effect on the next call to PlaybackWav::readAudioData. If the desired playback position is beyond the total playback length of the file, the playback position will be set to the end of file, and no audio data will be output on subsequent data reads.
PlaybackWav::millisToBytes
Description
Convert a playback duration to equivalent number of bytes.
Syntax
uint32_t millisToBytes(uint32_t ms);
Parameters
ms: playback duration in milliseconds.
Returns
The function returns the number of bytes that is equivalent to the input playback duration, converted using the current sample rate, number of channels and bit depth.
Example Code
NA
Notes and Warnings
NA
PlaybackWav::bytesToMillis
Description
Convert number of bytes to an equivalent playback duration.
Syntax
uint32_t bytesToMillis(uint32_t bytes);
Parameters
bytes: playback duration in number of bytes.
Returns
The function returns the time duration in milliseconds that is equivalent to the input number of bytes, converted using the current sample rate, number of channels and bit depth.
Example Code
NA
Notes and Warnings
NA
PlaybackWav::readAudioData
Description
Read audio data from the .wav file.
Syntax
uint32_t readAudioData(int8_t* dst, uint32_t len);
uint32_t readAudioData(int16_t* dst, uint32_t len);
Parameters
dst
: pointer to array to store data read from .wav file.
len
: number of audio samples to read from .wav file.
Returns
The function returns number of audio samples read.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
Class RecordWav
Description
A class used for control and recording of .wav file format audio data.
Syntax
class RecordWav
Members
Public Constructors
RecordWav:: RecordWav |
Create an instance of the RecordWav class |
Public Methods
RecordWav::openFile |
Open a .wav file for playback |
RecordWav::closeFile |
Close a previously opened file |
RecordWav::fileOpened |
Check if a .wav file is already opened |
RecordWav::setSampleRate |
Get the sample rate of the .wav file |
RecordWav::setChannelCount |
Set the number of audio channels in the .wav file |
RecordWav::setBitDepth |
Set the bit depth of each sample in the .wav file |
RecordWav::getLengthMillis |
Get the current record length of the .wav file in milliseconds |
RecordWav::millisToBytes |
Convert a playback duration to equivalent number of bytes |
RecordWav::bytesToMillis |
Convert number of bytes to an equivalent playback duration |
RecordWav::writeAudioData |
Write audio data to the .wav file |
RecordWav::RecordWav
Description
Create a RecordWav class object.
Syntax
void RecordWav(void);
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
Example: RecordWavFile
Notes and Warnings
NA
RecordWav::openFile
Description
Open a .wav file for recording.
Syntax
void openFile(const char* absFilepath);
Parameters
absFilepath: the filepath of the .wav file to open.
Returns
The function returns nothing.
Example Code
Example: RecordWavFile
Notes and Warnings
NA
RecordWav::closeFile
Description
Close a previously opened file.
Syntax
void closeFile(void);
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
Example: RecordWavFile
Notes and Warnings
Any open .wav files should be closed after recording is complete, otherwise, loss of recorded audio data may occur.
RecordWav::fileOpened
Description
Check if a .wav file is already opened.
Syntax
bool fileOpened(void);
Parameters
The function requires no input parameter.
Returns
The function returns true if a .wav file is already open, false otherwise.
Example Code
Example: RecordWavFile
Notes and Warnings
NA
RecordWav::setSampleRate
Description
Set the recording sample rate of the .wav file.
Syntax
void setSampleRate(uint32_t sampleRate);
Parameters
sampleRate: The desired recording sample rate.
Returns
The function returns nothing.
Example Code
Example: RecordWavFile
Notes and Warnings
NA
RecordWav::setChannelCount
Description
Set the number of recording audio channels in the .wav file.
Syntax
void setChannelCount(uint16_t channelCount);
Parameters
channelCount: number of recording audio channels.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
RecordWav::setBitDepth
Description
Set the recording bit depth of each sample in the .wav file.
Syntax
void setBitDepth(uint16_t bitDepth);
Parameters
bitDepth: number of bits per sample.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
RecordWav::getLengthMillis
Description
Get the current recorded length of the .wav file in milliseconds.
Syntax
uint32_t getLengthMillis(void);
Parameters
The function requires no input parameter.
Returns
The function returns the current recorded length of the currently open .wav file in milliseconds.
Example Code
NA
Notes and Warnings
NA
RecordWav::millisToBytes
Description
Convert a playback duration to equivalent number of bytes.
Syntax
uint32_t millisToBytes(uint32_t ms);
Parameters
ms: playback duration in milliseconds.
Returns
The function returns the number of bytes that is equivalent to the input playback duration, converted using the current sample rate, number of channels and bit depth.
Example Code
NA
Notes and Warnings
NA
RecordWav::bytesToMillis
Description
Convert number of bytes to an equivalent playback duration.
Syntax
uint32_t bytesToMillis(uint32_t bytes);
Parameters
bytes: playback duration in number of bytes.
Returns
The function returns the time duration in milliseconds that is equivalent to the input number of bytes, converted using the current sample rate, number of channels and bit depth.
Example Code
NA
Notes and Warnings
NA
RecordWav::writeAudioData
Description
Write audio data to the .wav file.
Syntax
uint32_t writeAudioData(int8_t* src, uint32_t len); uint32_t writeAudioData(int16_t* src, uint32_t len);
Parameters
src: pointer to array containing data to write to .wav file. len: number of audio samples to write to .wav file.
Returns
The function returns number of audio samples written.
Example Code
Example: RecordWavFile
Notes and Warnings
NA
BLE
Class BLEAddr
BLEAddr Class
Description
A class used for managing Bluetooth addresses.
Members
Public Constructors |
|
---|---|
BLEAddr::BLEAddr |
Constructs a BLEAddr object |
Public Methods |
|
BLEAddr::str |
Get the Bluetooth address represented as a formatted string |
BLEAddr::data |
Get the Bluetooth address represented as an integer array |
BLEAddr::BLEAddr
BLEAddr::str
BLEAddr::data
Class BLEAdvert
BLEAdvert Class
Members
Public Constructors |
---|
No public constructor is available as this class is intended to be a singleton class. You can get a pointer to this class using BLEDevice::configAdvert(). |
Public Methods |
|
---|---|
BLEAdvert::updateAdvertParams |
Update the current BLE advertisement settings to the lower Bluetooth stack |
BLEAdvert::startAdv |
Start BLE advertising |
BLEAdvert::stopAdv |
Stop BLE advertising |
BLEAdvert::setAdvType |
Set the BLE advertising type |
BLEAdvert::setMinInterval |
Set the BLE advertising minimum interval |
BLEAdvert::setMaxInterval |
Set the BLE advertising maximum interval |
BLEAdvert::setAdvData |
Set BLE advertising data |
BLEAdvert::setScanRspData |
Set BLE scan response data |
BLEAdvert::updateAdvertParams
BLEAdvert::startAdv
BLEAdvert::stopAdv
BLEAdvert::setAdvType
BLEAdvert::setMinInterval
BLEAdvert::setMaxInterval
BLEAdvert::setAdvData
BLEAdvert::setScanRspData
Class BLEAdvertData
BLEAdvertData Class
Members
Public Constructors |
|
---|---|
BLEAdvertData::BLEAdvertData |
Constructs a BLEAdvertData object |
Public Methods |
|
---|---|
BLEAdvertData::clear |
Clear all advertising data |
BLEAdvertData::addData |
Add binary advertising data |
BLEAdvertData::addFlags |
Add flags to advertising data |
B LEAdvertData::addPartialServices |
Add partial services to advertising data |
BL EAdvertData::addCompleteServices |
Add complete services to advertising data |
BLEAdvertData::addAppearance |
Add device appearance to advertising data |
BLEAdvertData::addShortName |
Add short device name to advertising data |
BLEAdvertData::addCompleteName |
Add complete device name to advertising data |
BLEAdvertData::parseScanInfo |
Parse advertising data received from a scan |
BLEAdvertData::hasFlags |
Check if received data includes advertising flags |
BLEAdvertData::hasUUID |
Check if received data includes UUIDs |
BLEAdvertData::hasName |
Check if received data includes device name |
BLEAdvertData::hasManufacturer |
Check if received data includes manufacturer data |
BLEAdvertData::getAdvType |
Get advertising type of received data |
BLEAdvertData::getAddrType |
Get Bluetooth address type of received data |
BLEAdvertData::getAddr |
Get Bluetooth address of received data |
BLEAdvertData::getRSSI |
Get RSSI of received data |
BLEAdvertData::getFlags |
Get advertising flags of received data |
BLEAdvertData::getServiceCount |
Get number of advertised services in received data |
BLEAdvertData::getServiceList |
Get array of advertised services in received data |
BLEAdvertData::getName |
Get advertised device name in received data |
BLEAdvertData::getTxPower |
Get advertised transmission power in received data |
BLEAdvertData::getAppearance |
Get advertised device appearance in received data |
BLEAdvertData::getManufacturer |
Get advertised manufacturer in received data |
BLEAdver tData::getManufacturerDataLength |
Get length of manufacturer data in received data |
BL EAdvertData::getManufacturerData |
Get advertised manufacturer data in received data |
BLEAdvertData::BLEAdvertData
BLEAdvertData::clear
BLEAdvertData::addData
BLEAdvertData::addFlags
BLEAdvertData::addPartialServices
BLEAdvertData::addCompleteServices
BLEAdvertData::addAppearance
BLEAdvertData::addShortName
BLEAdvertData::addCompleteName
BLEAdvertData::parseScanInfo
BLEAdvertData::hasFlags
BLEAdvertData::hasUUID
BLEAdvertData::hasName
BLEAdvertData::hasManufacturer
BLEAdvertData::getAdvType
BLEAdvertData::getAddrType
BLEAdvertData::getRSSI
BLEAdvertData::getFlags
BLEAdvertData::getServiceCount
BLEAdvertData::getServiceList
BLEAdvertData::getName
BLEAdvertData::getTxPower
BLEAdvertData::getAppearance
BLEAdvertData::getManufacturer
BLEAdvertData::getManufacturerDataLength
BLEAdvertData::getManufacturerData
Class BLEBeacon
iBeacon Class
Members
Public Constructors |
|
---|---|
iBeacon::iBeacon |
Create an instance of iBeacon advertising data |
Public Methods |
|
iBeacon::getManufacturerId |
Get current manufacturer ID value |
iBeacon::getUUID |
Get current UUID value |
iBeacon::getMajor |
Get current Major value |
iBeacon::getMinor |
Get current Minor value |
iBeacon::getRSSI |
Get current RSSI value |
iBeacon::setManufacturerId |
Set manufacturer ID value |
iBeacon::setUUID |
Set UUID value |
iBeacon::setMajor |
Set Major value |
iBeacon::setMinor |
Set Minor value |
iBeacon::setRSSI |
Set RSSI value |
iBeacon::getAdvData |
Get current advertising data |
iBeacon::getScanRsp |
Get current scan response data |
altBeacon Class
Members
Public Constructors |
|
---|---|
altBeacon::altBeacon |
Create an instance of altBeacon advertising data |
Public Methods |
|
altBeacon::getManufacturerId |
Get current manufacturer ID value |
altBeacon::getUUID |
Get current UUID value |
altBeacon::getMajor |
Get current Major value |
altBeacon::getMinor |
Get current Minor value |
altBeacon::getRSSI |
Get current RSSI value |
altBeacon::getRSVD |
Get current Reserved value |
altBeacon::setManufacturerId |
Set manufacturer ID value |
altBeacon::setUUID |
Set UUID value |
altBeacon::setMajor |
Set Major value |
altBeacon::setMinor |
Set Minor value |
altBeacon::setRSSI |
Set RSSI value |
altBeacon::setRSVD |
Set Reserved value |
altBeacon::getAdvData |
Get current advertising data |
altBeacon::getScanRsp |
Get current scan response data |
iBeacon::iBeacon
altBeacon::altBeacon
iBeacon::getManufacturerId
altBeacon::getManufacturerId
iBeacon::getUUID
altBeacon::getUUID
iBeacon::getMajor
altBeacon::getMajor
iBeacon::getMinor
altBeacon::getMinor
iBeacon::getRSSI
altBeacon::getRSSI
iBeacon::setManufacturerId
altBeacon::setManufacturerId
iBeacon::setUUID
altBeacon::setUUID
iBeacon::setMajor
altBeacon::setMajor
iBeacon::setMinor
altBeacon::setMinor
iBeacon::setRSSI
altBeacon::setRSSI
iBeacon::getAdvData
altBeacon::getAdvData
iBeacon::getScanRsp
altBeacon::getScanRsp
altBeacon::getRSVD
altBeacon::setRSVD
Class BLECharacteristic
BLECharacteristic Class
Description
A class used for creating and managing BLE GATT characteristics.
Members
Public Constructors |
|
---|---|
BLEC haracteristic::BLECharacteristic |
Constructs a BLECharacteristic object |
Public Methods |
|
BLECharacteristic::setUUID |
Set the characteristic UUID |
BLECharacteristic::getUUID |
Get the characteristic UUID |
BLECharacteristic::setBufferLen |
Set the size of the internal data buffer |
BLECharacteristic::getBufferLen |
Get the current size of the internal data buffer |
BL ECharacteristic::setReadProperty |
Get the current size of the internal data bufferSet the characteristic read property |
BLE Characteristic::setWriteProperty |
Set the characteristic write property |
BLEC haracteristic::setNotifyProperty |
Set the characteristic notify property |
BLECha racteristic::setIndicateProperty |
Set the characteristic indicate property |
BLECharacteristic::setProperties |
Set the characteristic properties |
BLECharacteristic::getProperties |
Get the characteristic properties |
BLECharacteristic::readString |
Read the characteristic data buffer as a String object |
BLECharacteristic::readData8 |
Read the characteristic data buffer as an unsigned 8-bit integer |
BLECharacteristic::readData16 |
Read the characteristic data buffer as an unsigned 16-bit integer |
BLECharacteristic::readData32 |
Read the characteristic data buffer as an unsigned 32-bit integer |
BLECharacteristic::writeString |
Write data to the characteristic data buffer as a String object or character array |
BLECharacteristic::writeData8 |
Write data to the characteristic data buffer as an unsigned 8-bit integer |
BLECharacteristic::writeData16 |
Write data to the characteristic data buffer as an unsigned 16-bit integer |
BLECharacteristic::writeData32 |
Write data to the characteristic data buffer as an unsigned 16-bit integer |
BLECharacteristic::setData |
Write data to the characteristic data buffer |
BLECharacteristic::getData |
Read data from the characteristic data buffer |
BLECharacteristic::getDataBuff |
Get a pointer to the characteristic data buffer |
BLECharacteristic::getDataLen |
Get the number of bytes of data in the characteristic data buffer |
BLECharacteristic::notify |
Send a notification to a connected device |
BLECharacteristic::indicate |
Send an indication to a connected device |
BLEC haracteristic::setUserDescriptor |
Add a user description descriptor to characteristic |
BLECha racteristic::setFormatDescriptor |
Add a data format descriptor to characteristic |
BLECharacteristic::Add a data format descriptor to characteristic |
Set a user function as a read callback |
BLE Characteristic::setWriteCallback |
Set a user function as a write callback |
BL ECharacteristic::setCCCDCallback |
Set a user function as a CCCD write callback |
BLECharacteristic::BLECharacteristic
BLECharacteristic::setUUID
BLECharacteristic::getUUID
BLECharacteristic::setBufferLen
BLECharacteristic::getBufferLen
BLECharacteristic::setReadProperty
BLECharacteristic::setWriteProperty
BLECharacteristic::setNotifyProperty
BLECharacteristic::setIndicateProperty
BLECharacteristic::setProperties
BLECharacteristic::getProperties
BLECharacteristic::readString
BLECharacteristic::readData8
BLECharacteristic::readData16
BLECharacteristic::readData32
BLECharacteristic::readData32
BLECharacteristic::writeData8
BLECharacteristic::writeData16
BLECharacteristic::writeData32
BLECharacteristic::setData
BLECharacteristic::getData
BLECharacteristic::getDataBuff
BLECharacteristic::getDataLen
BLECharacteristic::notify
BLECharacteristic::indicate
BLECharacteristic::setUserDescriptor
BLECharacteristic::setFormatDescriptor
BLECharacteristic::setReadCallback
BLECharacteristic::setWriteCallback
BLECharacteristic::setCCCDCallback
Class BLEClient
BLEClient Class
Members
Public Constructors |
---|
No public constructor is available for this class. You can get a pointer to an instance of this class using BLEDevice::addClient(). |
Public Methods |
|
---|---|
BLEClient::connected |
Check if the corresponding remote device for the client is connected |
BLEClient::discoverServices |
Start service discovery process for connected device |
BLEClient::discoveryDone |
Determine if service discovery process has been completed |
BLEClient::printServices |
Format and print discovered services to serial port |
BLEClient::getService |
Get a specific service on the remote device |
BLEClient::getConnId |
|
BLEClient::getClientId |
Get corresponding client ID |
BLEClient::setDisconnectCallback |
Set a user function to be called when the remote device is disconnected |
BLEClient::connected
BLEClient::discoverServices
BLEClient::discoveryDone
BLEClient::printServices
BLEClient::getService
BLEClient::getConnId
BLEClient::getClientId
BLEClient::setDisconnectCallback
Class BLEConnect
BLEConnect Class
Members
Public Constructors |
---|
No public constructor is available as this class is intended to be a singleton class. You can get a pointer to this class using BLEDevice::configConnection. |
Public Methods |
|
---|---|
BLEConnect::connect |
Connect to a target BLE device |
BLEConnect::disconnect |
Disconnect from a target BLE device |
BLEConnect::setScanInterval |
Set the BLE scanning interval when connecting |
BLEConnect::setScanWindow |
Set the BLE scanning window when connecting |
BLEConnect::setConnInterval |
Set the BLE connection interval duration |
BLEConnect::setConnLatency |
Set the BLE connection slave latency |
BLEConnect::setConnTimeout |
Set the BLE connection timeout value |
BLEConnect::updateConnParams |
Send new BLE connection parameters to a connected device |
BLEConnect::getConnInfo |
Get connection information |
BLEConnect::getConnAddr |
Get the Bluetooth address for a certain connection |
BLEConnect::getConnId |
Get the connection ID for a certain device |
BLEConnect::connect
BLEConnect::disconnect
BLEConnect::setScanInterval
BLEConnect::setScanWindow
BLEConnect::setConnInterval
BLEConnect::setConnLatency
BLEConnect::setConnTimeout
BLEConnect::updateConnParams
BLEConnect::getConnInfo
BLEConnect::getConnAddr
BLEConnect::getConnId
Class BLEDevice
BLEDevice Class
Members
Public Constructors |
---|
The public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named BLE. |
Public Methods |
|
---|---|
BLEDevice::init |
Allocate resources required for BLE functionality |
BLEDevice::deinit |
Free resources used by BLE functionality |
BLEDevice::connected |
Check if a BLE device is connected |
BLEDevice::setDeviceName |
Set BLE GAP device name |
BLEDevice::setDeviceAppearance |
Set BLE GAP device appearance |
BLEDevice::configAdvert |
Configure BLE advertising parameters |
BLEDevice::configScan |
Configure BLE scan parameters |
BLEDevice::setScanCallback |
Set callback function for BLE scans |
BLEDevice::beginCentral |
Start BLE stack in central mode |
BLEDevice::beginPeripheral |
Start BLE stack in peripheral mode |
BLEDevice::end |
Stop BLE stack |
BLEDevice::configServer |
Configure BLE stack for services |
BLEDevice::addService |
Add a service to the BLE stack |
BLEDevice::configClient |
Configure BLE stack for clients |
BLEDevice::addClient |
Add a client to the BLE stack |
BLEDevice::getLocalAddr |
Get local device Bluetooth address |
BLEDevice::init
BLEDevice::deinit
BLEDevice::connected
BLEDevice::setDeviceName
BLEDevice::setDeviceAppearance
BLEDevice::configAdvert
BLEDevice::configScan
#include 「BLEDevice.h」
#include 「BLEScan.h」
int dataCount = 0;
void scanFunction(T_LE_CB_DATA* p_data) {
printf(」rnScan Data %drn」, ++dataCount);
BLE.configScan()->printScanInfo(p_data);
}
void setup() {
BLE.init();
BLE.configScan()->setScanMode(GAP_SCAN_MODE_ACTIVE);
BLE.configScan()->setScanInterval(500); // Start a scan every 500ms
BLE.configScan()->setScanWindow(250); // Each scan lasts for 250ms
// Provide a callback function to process scan data.
// If no function is provided, default BLEScan::printScanInfo is used
BLE.setScanCallback(scanFunction);
BLE.beginCentral(0);
BLE.configScan()->startScan(5000); // Repeat scans for 5 seconds, then stop
}
void loop() {
}
BLEDevice::setScanCallback
BLEDevice::beginCentral
BLEDevice::beginPeripheral
BLEDevice::end
BLEDevice::configServer
BLEDevice::addService
BLEDevice::configClient
BLEDevice::addClient
BLEDevice::getLocalAddr
Class BLEHIDDevice
BLEHIDDevice Class
Description
A class used for creating and managing HID over GATT Profile (HOGP) services.
Members
Public Constructors |
---|
The public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named BLEHIDDev. |
Public Methods |
|
---|---|
BLEHIDDevice::init |
Initialize the HID Device Profile by creating the required services |
BLEHIDD evice::setNumOutputReport |
Configure the number of HID output reports |
BLEHID Device::setNumInputReport |
Configure the number of HID input reports |
B LEHIDDevice::setReportMap |
Configure the HID report map |
BLEHIDDevice::inputReport |
Send a HID input report |
BLEHIDDevice ::setOutputReportCallback |
Set a user callback function for receiving HID output reports |
BLEHIDD evice::bootKeyboardReport |
Send a HID boot keyboard input report |
BLEHIDDevice::setHidInfo |
Set HID info of the HID service |
B LEHIDDevice::setBattLevel |
Set battery level info of the Battery service |
BLEHIDDevice::setPNPInfo |
Set PNP information of the Device Information service |
BLEHIDDevi ce::setManufacturerString |
Set manufacturer information of the Device Information service |
BLE HIDDevice::setModelString |
Set model information of the Device Information service |
BLEHIDDevice::hidService |
Get reference to HID service |
BLE HIDDevice::devInfoService |
Get reference to Device Information service |
BLEHIDDevice::battService |
Get reference to Battery service |
BLEHIDDevice::init
BLEHIDDevice::setNumOutputReport
BLEHIDDevice::setNumInputReport
BLEHIDDevice::setReportMap
BLEHIDDevice::inputReport
BLEHIDDevice::setOutputReportCallback
BLEHIDDevice::bootKeyboardReport
BLEHIDDevice::setHidInfo
BLEHIDDevice::setBattLevel
BLEHIDDevice::setPNPInfo
BLEHIDDevice::setManufacturerString
BLEHIDDevice::setModelString
BLEHIDDevice::hidService
BLEHIDDevice::devInfoService
BLEHIDDevice::battService
Class BLEHIDGamepad
BLEHIDGamepad Class
Description
A class used for creating and managing a BLE HID Gamepad.
Members
Public Constructors |
|
---|---|
BLEHIDGame pad::BLEHIDGamepad |
Constructs a BLEHIDGamepad object |
Public Methods |
|
BLEHIDGa mepad::setReportID |
Set HID report ID for the HID Gamepad |
BLEHIDGame pad::gamepadReport |
Send a HID Gamepad report |
BLEHIDGa mepad::buttonPress |
Send a HID Gamepad report indicating buttons pressed |
BLEHIDGame pad::buttonRelease |
Send a HID Gamepad report indicating buttons released |
BLEHIDGamepad ::buttonReleaseAll |
Send a HID Gamepad report indicating no buttons pressed |
BLE HIDGamepad::setHat |
Send a HID Gamepad report indicating hat switch position |
BLEH IDGamepad::setAxes |
Send a HID Gamepad report indicating position of all axes |
BLEHIDGam epad::setLeftStick |
Send a HID Gamepad report indicating position of axes corresponding to left analog stick |
BLEHIDGame pad::setRightStick |
Send a HID Gamepad report indicating position of axes corresponding to right analog stick |
BLEHIDGa mepad::setTriggers |
Send a HID Gamepad report indicating position of axes corresponding to triggers |
Class BLEHIDKeyboard
BLEHIDKeyboard Class
Description
A class used for creating and managing a BLE HID Keyboard.
Members
Public Constructors |
|
---|---|
BLEHIDKeybo ard::BLEHIDKeyboard |
Constructs a BLEHIDKeyboard object |
Public Methods |
|
BLEHIDKe yboard::setReportID |
Set HID report ID for the HID Keyboard and HID consumer control |
BLEHIDKeybo ard::consumerReport |
Send a HID Consumer report |
BLEHIDKeybo ard::keyboardReport |
Send a HID Keyboard report |
BLEHIDKeyb oard::consumerPress |
Send a HID Consumer report indicating button pressed |
BLEHIDKeyboa rd::consumerRelease |
Send a HID Consumer report indicating button released |
BLEHI DKeyboard::keypress |
Send a HID Keyboard report indicating keys pressed |
BLEHIDK eyboard::keyRelease |
Send a HID Keyboard report indicating keys released |
BLEHIDKeyb oard::keyReleaseAll |
Send a HID Keyboard report indicating no keys pressed |
BLEHIDKey board::keyCharPress |
Send a HID Keyboard report indicating keys pressed to output an ASCII character |
BLEHIDKe yboard::keySequence |
Send a HID Keyboard report indicating keys pressed to output an ASCII string |
Class BLEHIDMouse
BLEHIDMouse Class
Description
A class used for creating and managing a BLE HID Mouse.
Members
Public Constructors |
|
---|---|
BLE HIDMouse::BLEHIDMouse |
Constructs a BLEHIDMouse object |
Public Methods |
|
BLE HIDMouse::setReportID |
Set HID report ID for the HID Mouse |
BLE HIDMouse::mouseReport |
Send a HID Mouse report |
BL EHIDMouse::mousePress |
Send a HID Mouse report indicating buttons pressed |
BLEH IDMouse::mouseRelease |
Send a HID Mouse report indicating buttons released |
BLEHIDM ouse::mouseReleaseAll |
Send a HID Mouse report indicating no buttons pressed |
B LEHIDMouse::mouseMove |
Send a HID Mouse report indicating mouse movement |
BLE HIDMouse::mouseScroll |
Send a HID Mouse report indicating mouse scroll wheel movement |
Class BLERemoteCharacteristic
BLERemoteCharacteristic Class
Members
Public Constructors |
---|
No public constructor is available for this class. You can get a pointer to an instance of this class using BLERemoteService::getCharacteristic(). |
Public Methods |
|
---|---|
BLERem oteCharacteristic::getDescriptor |
Get a specific descriptor on the remote device |
BLERemoteCharacteristic::getUUID |
Get the characteristic UUID |
BLERe moteCharacteristic::setBufferLen |
Set the size of the internal data buffer |
BLERe moteCharacteristic::getBufferLen |
Get the current size of the internal data buffer |
BLERemoteCharacteristic::canRead |
Determine if characteristic has read property enabled |
B LERemoteCharacteristic::canWrite |
Determine if characteristic has write property enabled |
BL ERemoteCharacteristic::canNotify |
Determine if characteristic has notify property enabled |
BLER emoteCharacteristic::canIndicate |
Determine if characteristic has indicate property enabled |
BLERem oteCharacteristic::getProperties |
Get the characteristic properties |
BLE RemoteCharacteristic::readString |
Read the characteristic data buffer as a String object |
BL ERemoteCharacteristic::readData8 |
Read the characteristic data buffer as an unsigned 8-bit integer |
BLE RemoteCharacteristic::readData16 |
Read the characteristic data buffer as an unsigned 16-bit integer |
BLE RemoteCharacteristic::readData32 |
Read the characteristic data buffer as an unsigned 32-bit integer |
BLER emoteCharacteristic::writeString |
Write data to the characteristic as a String object or character array |
BLE RemoteCharacteristic::writeData8 |
Write data to the characteristic as an unsigned 8-bit integer |
BLER emoteCharacteristic::writeData16 |
Write data to the characteristic as an unsigned 16-bit integer |
BLER emoteCharacteristic::writeData32 |
Write data to the characteristic as an unsigned 16-bit integer |
BLERemoteCharacteristic::setData |
Write data to the characteristic |
BLERemoteCharacteristic::getData |
Read data from the characteristic |
BLERemoteChar acteristic::enableNotifyIndicate |
Enable notification or indication for the characteristic |
BLERemoteChara cteristic::disableNotifyIndicate |
Disable notification and indication for the characteristic |
BLERemoteC haracteristic::setNotifyCallback |
Set a user function as a notification callback |
BLERemoteCharacteristic::getDescriptor
BLERemoteCharacteristic::getUUID
BLERemoteCharacteristic::setBufferLen
BLERemoteCharacteristic::getBufferLen
BLERemoteCharacteristic::canRead
BLERemoteCharacteristic::canWrite
BLERemoteCharacteristic::canNotify
BLERemoteCharacteristic::canIndicate
BLERemoteCharacteristic::getProperties
BLERemoteCharacteristic::readString
BLERemoteCharacteristic::readData8
BLERemoteCharacteristic::readData16
BLERemoteCharacteristic::readData32
BLERemoteCharacteristic::writeString
BLERemoteCharacteristic::writeData8
BLERemoteCharacteristic::writeData16
BLERemoteCharacteristic::writeData32
BLERemoteCharacteristic::setData
BLERemoteCharacteristic::getData
BLERemoteCharacteristic::enableNotifyIndicate
BLERemoteCharacteristic::disableNotifyIndicate
BLERemoteCharacteristic::setNotifyCallback
Class BLERemoteDescriptor
BLERemoteDescriptor Class
Members
Public Constructors |
---|
No public constructor is available for this class. You can get a pointer to an instance of this class using BLERemoteCharacteristic::getDescriptor(). |
Public Methods |
|
---|---|
BLERemoteDescriptor::getUUID |
Get the descriptor UUID |
B LERemoteDescriptor::setBufferLen |
Set the size of the internal data buffer |
B LERemoteDescriptor::getBufferLen |
Get the current size of the internal data buffer |
BLERemoteDescriptor::readString |
Read the descriptor data buffer as a String object |
BLERemoteDescriptor::readData8 |
Read the descriptor data buffer as an unsigned 8-bit integer |
BLERemoteDescriptor::readData16 |
Read the descriptor data buffer as an unsigned 16-bit integer |
BLERemoteDescriptor::readData32 |
Read the descriptor data buffer as an unsigned 32-bit integer |
BLERemoteDescriptor::writeString |
Write data to the descriptor as a String object or character array |
BLERemoteDescriptor::writeData8 |
Write data to the descriptor as an unsigned 8-bit integer |
BLERemoteDescriptor::writeData16 |
Write data to the descriptor as an unsigned 16-bit integer |
BLERemoteDescriptor::writeData32 |
Write data to the descriptor as an unsigned 16-bit integer |
BLERemoteDescriptor::setData |
Write data to the descriptor |
BLERemoteDescriptor::getData |
Read data from the descriptor |
BLERemoteDescriptor::getUUID
BLERemoteDescriptor::setBufferLen
BLERemoteDescriptor::getBufferLen
BLERemoteDescriptor::readString
BLERemoteDescriptor::readData8
BLERemoteDescriptor::readData16
BLERemoteDescriptor::readData32
BLERemoteDescriptor::writeString
BLERemoteDescriptor::writeData8
BLERemoteDescriptor::writeData16
BLERemoteDescriptor::writeData32
BLERemoteDescriptor::setData
BLERemoteDescriptor::getData
Class BLERemoteService
BLERemoteService Class
Members
Public Constructors |
---|
No public constructor is available for this class. You can get a pointer to an instance of this class using BLEClient::getService(). |
Public Methods |
|
---|---|
BLERemoteService::getUUID |
Get the service UUID |
BLE RemoteService::getCharacteristic |
Get a specific characteristic on the remote device |
BLERemoteService::getUUID
BLERemoteService::getCharacteristic
Class BLEScan
BLEScan Class
Members
Public Constructors |
---|
No public constructor is available as this class is intended to be a singleton class. You can get a pointer to this class using BLEDevice::configScan |
Public Methods |
|
---|---|
BLEScan::updateScanParams |
Update the current BLE advertisement settings to the lower Bluetooth stack |
BLEScan::startScan |
Start a BLE scan |
BLEScan::stopScan |
Stop a BLE scan |
BLEScan::setScanMode |
Set the BLE scanning mode |
BLEScan::setScanInterval |
Set the BLE scanning interval |
BLEScan::setScanWindow |
Set the BLE scanning window |
BLEScan::setScanDuplicateFilter |
Set the BLE scan duplicate filter |
BLEScan::scanInProgress |
Check if a scan is currently in progress |
BLEScan::printScanInfo |
Print out scanned information |
BLEScan::updateScanParams
BLEScan::startScan
BLEScan::stopScan
BLEScan::setScanMode
BLEScan::setScanInterval
BLEScan::setScanWindow
BLEScan::setScanDuplicateFilter
BLEScan::scanInProgress
BLEScan::printScanInfo
Class BLEService
BLEService Class
Members
Public Constructors |
|
---|---|
BLEService::BLEService |
Constructs a BLEService object |
Public Methods |
|
BLEService::setUUID |
Set service UUID |
BLEService::getUUID |
Get service UUID |
BLEService::addCharacteristic |
Add a characteristic to service |
BLEService::getCharacteristic |
Get a previously added characteristic |
BLEService::BLEService
BLEService::setUUID
BLEService::getUUID
BLEService::addCharacteristic
BLEService::getCharacteristic
Class BLEUUID
BLEUUID Class
Members
Public Constructors |
|
---|---|
BLEUUID::BLEUUID |
Create a UUID object |
Public Methods |
|
BLEUUID::str |
Get the character string representation of UUID |
BLEUUID::data |
Get the binary representation of UUID |
BLEUUID::length |
Get the length of UUID |
BLEUUID::BLEUUID
BLEUUID::str
BLEUUID::data
BLEUUID::length
Class BLEWifiConfigService
BLEWifiConfigService Class
Members
Public Constructors |
|
---|---|
BLEWifiCon figService::BLEWifiConfigService |
Only one instance of this class should be created |
Public Methods |
|
---|---|
BLEWifiConfigService::begin |
Start background thread to process WiFi configuration commands |
BLEWifiConfigService::end |
Stop background thread processing WiFi configuration commands |
BLEWifiConfigService::addService |
Add the service to the BLE stack |
BLEWifiConfigService::advData |
Get advertising data correctly formatted for WiFi configuration service |
BLEWifiConfigService::BLEWifiConfigService
BLEWifiConfigService::begin
BLEWifiConfigService::end
BLEWifiConfigService::addService
BLEWifiConfigService::advData
EPDIF
Class EpdIF
EpdIf Class
Members
Public Constructors |
---|
A public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named EpdIf. |
Public Methods |
|
---|---|
EpdIf::EPD_Dis_Part |
Put an image buffer to the frame memory, but not updating the display |
EpdIf::EPD_SetFrame |
Put display data to the frame memory, usually used for setup text display functions |
EpdIf::EPD_SetRAMValue_BaseMap |
To read image data stored in the RAM, but not display on the screen |
EpdIf::EPD_SetFrameMemory |
To read image data stored in the buffer, but not display on the screen |
EpdIf::EPD_UpdateDisplay |
Update the display |
EpdIf::EPD_ClearScreen_White |
Clear the frame memory with the White color, but not updating the display |
EpdIf::EPD_ClearScreen_Black |
Clear the frame memory with the Black color, but not updating the display |
EpdIf::EPD_Busy |
Wait until the Busy pin goes to low, which is the idle state |
EpdIf::EPD_Reset |
Used for the Epaper module reset. Often used to awaken the module in deep sleep |
EpdIf::EPD_Sleep |
After this command is transmitted, the chip would enter the deep-sleep mode to save power |
EpdIf:: EPD_Dis_Part
EpdIf:: EPD_SetFrame
EpdIf:: EPD_SetRAMValue_BaseMap
EpdIf:: EPD_SetFrameMemory
EpdIf:: EPD_UpdateDisplay
EpdIf:: EPD_ClearScreen_White
EpdIf:: EPD_ClearScreen_Black
EpdIf:: EPD_Busy
EpdIf:: EPD_Reset
EpdIf::EPD_Sleep
FatfsSDCard
Class SdFatFs
Description
Defines a class of SD FAT File system.
Syntax
class SdFatFs
Members
Public Constructors
SdFatFs::SdFatFs Constructs a SdFatFs object
SdFatFs::~SdFatFs Destructs a SdFatFs object
Public Methods
SdFatFs::begin |
Initialize SD FAT File System |
---|---|
SdFatFs::end |
Deinitialize SD FAT File System |
SdFatFs::*getRootPath |
Get the root path of the SD FAT File System |
SdFatFs::readDir |
List items under a specific folder |
SdFatFs::mkdir |
Create folder |
SdFatFs::rm |
Remove folder or file |
SdFatFs::isDir |
Check if a specific path is a directory |
SdFatFs::isFile |
Check if a specific path is a file |
SdFatFs::getLastModTime |
Get the last modified time for a file or directory |
SdFatFs::setLastModTime |
Set the last modified time for a file or directory |
SdFatFs::status |
Return the current status of SD |
SdFatFs::open |
Open a file |
SdFatFs::begin
SdFatFs::end
SdFatFs::*getRootPath
SdFatFs::readDir
SdFatFs::mkdir
SdFatFs::rm
SdFatFs::isDir
SdFatFs::isFile
SdFatFs::getLastModTime
SdFatFs::setLastModTime
SdFatFs::open
SdFatFs::status
Class SdFatFile
Description
Defines a class of SD FAT File.
Members
Public Constructors |
|
---|---|
SdFatFile::SdFatFile |
Constructs a SdFatFile object |
SdFatFile::~SdFatFile |
Destructs a SdFatFile object |
Public Methods |
|
SdFatFile::write |
Write 1 byte/bytes to file |
SdFatFile::read |
Read 1 byte/bytes from the file |
SdFatFile::peek |
Read 1 byte from file without move curser |
SdFatFile::available |
Check if the cursor is at EOF (End-Of-File) |
SdFatFile::bool |
Check if file is opened |
SdFatFile::seek |
Change cursor to a specific position |
SdFatFile::close |
Close file |
SdFatFile::write
SdFatFile:: read
Example Code
#include 「FatFs_SD.h」
char dirname[] = 「testdir」;
char filename[] = 「test.txt」;
char write_content[] = 「hello world!」;
FatFsSD fs;
void setup() {
char buf[128];
char absolute_filename[128];
fs.begin();
sprintf(absolute_filename, 「%s%s」, fs.getRootPath(), dirname);
fs.mkdir(absolute_filename);
printf(「create dir at \」%s"rn」, absolute_filename);
sprintf(absolute_filename, 「%s%s/%s」, fs.getRootPath(), dirname, filename);
SdFatFile file = fs.open(absolute_filename);
file.println(write_content);
file.close();
printf(「create file at \」%s"rn」, absolute_filename);
printf(「read back from \」%s"rn」, absolute_filename);
file = fs.open(absolute_filename);
memset(buf, 0, sizeof(buf));
file.read(buf, sizeof(buf));
file.close();
printf(「==== content ====rn」);
printf(「%s」, buf);
printf(「==== end ====rn」);
fs.end();
}
void loop() {
delay(1000);
}
#include 「FatFs_SD.h」
char filename[] = 「test.txt」;
char write_content[] = 「hello world!」;
FatFsSD fs;
void setup() {
char buf[128];
char absolute_filename[128];
fs.begin();
printf(「write something to \」%s"rn」, filename);
sprintf(absolute_filename, 「%s%s」, fs.getRootPath(), filename);
SdFatFile file = fs.open(absolute_filename);
file.println(write_content);
file.close();
printf(「write finishrnrn」);
printf(「read back from \」%s"rn」, filename);
file = fs.open(absolute_filename);
memset(buf, 0, sizeof(buf));
file.read(buf, sizeof(buf));
file.close();
printf(「==== content ====rn」);
printf(「%s」, buf);
printf(「==== end ====rn」);
fs.end();
}
void loop() {
delay(1000);
}
SdFatFile:: peek
SdFatFile:: available
SdFatFile:: flush
SdFatFile:: seek
SdFatFile:: close
#include <FatFs_SD.h>
FatFsSD fs;
char filename[] = 「test.txt」;
void setup() {
char absolute_filename[128];
uint16_t year = 2021;
uint16_t month = 4;
uint16_t date = 4;
uint16_t hour = 12;
uint16_t minute = 12;
uint16_t second = 12;
fs.begin();
sprintf(absolute_filename, 「%s%s」, fs.getRootPath(), filename);
SdFatFile file = fs.open(absolute_filename);
file.close();
fs.setLastModTime(absolute_filename, year, month, date, hour, minute, second);
fs.getLastModTime(absolute_filename, &year, &month, &date, &hour, &minute, &second);
printf(「filename:"%s"rn」, absolute_filename);
printf(「time mod:%04d/%02d/%02d %02d:%02d:%02drn」, year, month, date, hour, minute, second);
fs.end();
}
void loop() {
delay(1000);
}
FlashMemory
Class EpdIF
FlashMemoryClass Class
Members
Public Constructors |
|
---|---|
Fl ashMemoryClass::FlashMemoryClass |
Constructs a FlashMemoryClass object |
Fla shMemoryClass::~FlashMemoryClass |
Deconstructs a FlashMemoryClass object |
Public Methods |
|
FlashMemoryClass::begin |
Initialize/Re-initialize the base address and size |
FlashMemoryClass::read |
Read the content to buf |
FlashMemoryClass::update |
Write buf back to flash memory |
FlashMemoryClass::readWord |
Read 4 bytes from flash memory |
FlashMemoryClass::writeWord |
Write 4 bytes into flash memory |
FlashMemoryClass::buf_size |
The buf size |
FlashMemoryClass::*buf |
The buf to be operated |
FlashMemoryClass::FlashMemoryClass
#include <FlashMemory.h>
void setup() {
FlashMemory.read();
if (FlashMemory.buf[0] == 0xFF) {
FlashMemory.buf[0] = 0x00;
FlashMemory.update();
Serial.println(「write count to 0」);
} else {
FlashMemory.buf[0]++;
FlashMemory.update();
Serial.print(「Boot count: 「);
Serial.println(FlashMemory.buf[0]);
}
}
void loop() {
delay(1000);
}
#include <FlashMemory.h>
void setup() {
unsigned int value;
/* request flash size 0x4000 from 0xFC000 */
FlashMemory.begin(0xFC000, 0x4000);
/* read one word (32-bit) from 0xFC000 plus offset 0x3F00 */
value = FlashMemory.readWord(0x3F00);
printf(「value is 0x%08Xrn」, value);
if (value == 0xFFFFFFFF) {
value = 0;
} else {
value++;
}
/* write one word (32-bit) to 0xFC000 plus offset 0x3F00 */
FlashMemory.writeWord(0x3F00, value);
}
void loop() {
// put your main code here, to run repeatedly:
}
FlashMemoryClass::begin
FlashMemoryClass::read
FlashMemoryClass::update
FlashMemoryClass::readWord
FlashMemoryClass::writeWord
FlashMemoryClass::buf_size
FlashMemoryClass::*buf
GPIO
Class DHT
DHT Class
Members
Public Constructors |
|
---|---|
DHT::DHT |
Constructs a DHT object |
Public Methods |
|
DHT::begin |
Initialize the DHT sensor |
DHT::readTemperature |
Read temperature(Fahrenheit or Celcius) from the DHT sensor |
DHT::convertCtoF |
Convert a value from Celcius to Fahrenheit |
DHT::convertFtoC |
Convert a value from Fahrenheit to Celcius |
DHT::readHumidity |
Read humidity(%) from the DHT sensor |
DHT::computeHeatIndex |
Compute the HeatIndex from the readings (Using both Rothfusz and Steadman’s equations) |
DHT::read |
Check if the sensor is readable |
DHT::DHT
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain
#include 「DHT.h」
// The digital pin we’re connected to.
#define DHTPIN 8
// 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(115200);
Serial.println(「DHTxx test!」);
dht.begin();
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 『old』 (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(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(」 *Ft」);
Serial.print(「Heat index: 「);
Serial.print(hic);
Serial.print(」 *C 「);
Serial.print(hif);
Serial.println(」 *F」);
}
DHT::begin
DHT::readTemperature
DHT::convertCtoF
DHT::convertFtoC
DHT::computeHeatIndex
DHT::readHumidity
DHT::read
Class HttpClient
InterruptLock Class
Members
Public Constructors |
|
---|---|
InterruptLock::InterruptLock |
Constructs a InterruptLock object |
InterruptLock::~ InterruptLock |
Deconstructs a InterruptLock object |
GTimer
Class EpdIF
GTimerClass Class
Members
Public Constructors |
|
---|---|
GTimerClass::GTimerClass |
Constructs a GTimerClass object |
Public Methods |
|
GTimerClass::begin |
Initialize a timer and start it immediately |
GTimerClass::stop |
Stop a specific timer |
GTimerClass::reload |
Reload a specific timer |
GTimerClass::read_us |
Read current countdown value |
GTimerClass::begin
/*
This sketch shows how to use several hardware timers in invoke handler only once for each timer.
*/
#include <GTimer.h>
void myhandler(uint32_t data) {
Serial.print(「I am timer!」);
Serial.println(data);
}
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// timerid 0, period 1s, invoke myhandler, invoke only once, user data is 0
GTimer.begin(0, 1 * 1000 * 1000, myhandler, false, 0);
// timerid 1, period 2s, invoke myhandler, invoke only once, user data is 1
GTimer.begin(1, 2 * 1000 * 1000, myhandler, false, 1);
GTimer.begin(2, 3 * 1000 * 1000, myhandler, false, 2);
GTimer.begin(3, 4 * 1000 * 1000, myhandler, false, 3);
}
void loop() {
delay(1000);
}
Example: TimerPeriodical
/*
This sketch shows how to use hardware timer and invoke interrupt handler periodically
*/
#include <GTimer.h>
int counter = 0;
void myhandler(uint32_t data) {
counter++;
Serial.print(「counter: 「);
Serial.println(counter);
if (counter >= 10) {
Serial.println(「stop timer」);
GTimer.stop(0);
}
}
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// timerid 0, period 1s, invoke myhander
GTimer.begin(0, (1 * 1000 * 1000), myhandler);
}
void loop() {
delay(1000);
}
GTimerClass::stop
GTimerClass::reload
GTimerClass::read_us
Http
Class HttpClient
HttpClient Class
Members
Public Constructors |
|
---|---|
HttpClient::HttpClient |
Constructs a HttpClient object |
Public Methods |
|
HttpClient::beginRequest |
Start a more complex request |
HttpClient::endRequest |
End a more complex request |
HttpClient::get |
Connect to the server and start to send a GET request |
HttpClient::post |
Connect to the server and start to send a POST request |
HttpClient::put |
Connect to the server and start to send a PUT request |
HttpClient::startRequest |
Connect to the server and start to send the request |
HttpClient::sendHeader |
Send an additional header line |
HttpClient::sendBasicAuth |
Send a basic authentication header |
HttpClient::finishRequest |
Finish sending the HTTP request |
HttpClient::responseStatusCode |
Get the HTTP status code contained in the response |
HttpClient::readHeader |
Read the next character of the response headers |
HttpClient::skipResponseHeaders |
Skip any response headers to get to the body |
HttpClient::endOfHeadersReached |
Test whether all of the response headers have been consumed |
HttpClient::endOfBodyReached |
Test whether the end of the body has been reached |
HttpClient::contentLength |
Return the length of the body |
HttpClient::HttpClient
#include <HttpClient.h>
#include <WiFi.h>
#include <WiFiClient.h>
char ssid[] = 「YourNetwork」; // your network SSID (name)
char pass[] = 「password」; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
// Name of the server we want to connect to
const char kHostname[] = 「www.google.com」;
const char kPath[] = 「/」;
// Number of milliseconds to wait without receiving any data before we give up
const int kNetworkTimeout = 30*1000;
// Number of milliseconds to wait if no data is available before trying again
const int kNetworkDelay = 1000;
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600);
while ( status != WL_CONNECTED) {
Serial.print(「Attempting to connect to SSID: 「);
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(「Connected to wifi」);
printWifiStatus();
}
void loop() {
int err =0;
WiFiClient c;
HttpClient http(c);
err = http.get(kHostname, kPath);
if (err == 0)
{
Serial.println(「startedRequest ok」);
err = http.responseStatusCode();
if (err >= 0)
{
Serial.print(「Got status code: 「);
Serial.println(err);
// Usually you’d check that the response code is 200 or a
// similar 「success」 code (200-299) before carrying on,
// but we’ll print out whatever response we get
err = http.skipResponseHeaders();
if (err >= 0)
{
int bodyLen = http.contentLength();
Serial.print(「Content length is: 「);
Serial.println(bodyLen);
Serial.println();
Serial.println(「Body returned follows:」);
// Now we’ve got to the body, so we can print it out
unsigned long timeoutStart = millis();
char c;
// Whilst we haven’t timed out & haven’t reached the end of the body
while ( (http.connected() || http.available()) &&
((millis() - timeoutStart) < kNetworkTimeout) )
{
if (http.available())
{
c = http.read();
// Print out this character
Serial.print(c);
bodyLen–;
// We read something, reset the timeout counter
timeoutStart = millis();
}
else
{
// We haven’t got any data, so let’s pause to allow some to arrive
delay(kNetworkDelay);
}
}
}
else
{
Serial.print(「Failed to skip response headers: 「);
Serial.println(err);
}
}
else
{
Serial.print(「Getting response failed: 「);
Serial.println(err);
}
}
else
{
Serial.print(「Connect failed: 「);
Serial.println(err);
}
http.stop();
// And just stop, now that we’ve tried a download
while(1);
}
void printWifiStatus() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.print(rssi);
Serial.println(」 dBm」);
}
HttpClient::beginRequest
HttpClient::endRequest
HttpClient::get
HttpClient::post
HttpClient::put
HttpClient::startRequest
HttpClient::sendHeader
HttpClient::sendBasicAuth
HttpClient::finishRequest
HttpClient::responseStatusCode
HttpClient::readHeader
HttpClient::skipResponseHeaders
HttpClient::endOfHeadersReached
HttpClient::endOfBodyReached
HttpClient::contentLength
IRDevice
Class HttpClient
IRDevice Class
Members
Public Constructors |
|
---|---|
A public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named IR. |
Public Methods |
|
---|---|
IRDevice::getFreq |
Get the current IR modulation frequency |
IRDevice::begin |
Allocate resources and start the IR device with a custom frequency |
IRDevice::end |
Stop the IR device operations and free up resources |
IRDevice::send |
Send IR raw data |
IRDevice::beginNEC |
Allocate resources and start the IR device with a frequency suitable for the NEC protocol |
IRDevice::sendNEC |
Send data using the NEC protocol |
IRDevice::recvNEC |
Receive data using the NEC protocol |
IRDevice::getFreq
IRDevice::begin
IRDevice::end
IRDevice::send
Example Code
#include 「IRDevice.h」
// User defined txPin, rxPin and carrier frequency
#define IR_RX_PIN 8
#define IR_TX_PIN 9
#define CARRIER_FREQ 38000
unsigned int irRawSignal[] = {
9000, 4500, // starting bit
560, 560, 560, 560, 560, 1690, 560, 560, 560, 560, 560, 560, 560, 560, 560, 560, // address 00100000 : 4
560, 1690, 560, 1690, 560, 560, 560, 1690, 560, 1690, 560, 1690, 560, 1690, 560, 1690, // ~ address 11011111
560, 560, 560, 560, 560, 560, 560, 1690, 560, 560, 560, 560, 560, 560, 560, 560, // data 00010000 : 8
560, 1690, 560, 1690, 560, 1690, 560, 560, 560, 1690, 560, 1690, 560, 1690, 560, 1690, //~ data 11101111
560 // stoping bit
};
int DataLen = sizeof(irRawSignal) / sizeof(irRawSignal[0]); // 284/ 4 = 71
void setup()
{
Serial.begin(115200);
IR.begin(IR_RX_PIN, IR_TX_PIN, IR_MODE_TX, CARRIER_FREQ);
}
void loop()
{
IR.send(irRawSignal, DataLen);
Serial.println(「Finished Sending NEC Raw Data….」);
delay(3000);
}
IRDevice::beginNEC
#include 「IRDevice.h」
uint8_t adr = 0;
uint8_t cmd = 0;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
IR.beginNEC(8, 9, IR_MODE_RX); // configure for NEC IR protocol
}
void loop() {
if (IR.recvNEC(adr, cmd, 1000)) {
Serial.print(「Received 「);
Serial.print(adr);
Serial.print(cmd);
Serial.println();
} else {
Serial.println(「Received nothing, timed out」);
}
//IR.end();
}
IRDevice::sendNEC
#include 「IRDevice.h」
uint8_t adr = 0;
uint8_t cmd = 0;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
IR.beginNEC(8, 9, IR_MODE_TX); // configure for NEC IR protocol
}
void loop() {
if (cmd++ >=255) {
adr++;
}
IR.sendNEC(adr, cmd);
Serial.print(「Sent 「);
Serial.print(adr);
Serial.print(cmd);
Serial.println();
//IR.end(); // Call this method to stop IR device and free up the pins for other uses
}
IRDevice::recvNEC
MDNS
Class HttpClient
MDNSClass Class
Members
Public Constructors |
|
---|---|
The public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named MDNS. |
Public Methods |
|
---|---|
MDNSClass::begin |
Start MDNS operations |
MDNSClass::end |
Stop MDNS operations |
MDNSClass::registerService |
Add a service record |
MDNSClass::deregisterService |
Remove service record |
MDNSClass::updateService |
Update service record |
MDNSClass::begin
#include <WiFi.h>
#include <AmebaMDNS.h>
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「secretPassword」; // your network password
MDNSService service(「MyAmeba」, 「_arduino._tcp」, 「local」, 5000);
void setup() {
printf(「Try to connect to %srn」, ssid);
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
printf(「Failed. Wait 1s and retry…rn」);
delay(1000);
}
printf(「Connected to %srn」, ssid);
service.addTxtRecord(「board」, strlen(「ameba_rtl8195a」), 「ameba_rtl8195a」);
service.addTxtRecord(「auth_upload」, strlen(「no」), 「no」);
service.addTxtRecord(「tcp_check」, strlen(「no」), 「no」);
service.addTxtRecord(「ssh_upload」, strlen(「no」), 「no」);
printf(「Start mDNS servicern」);
MDNS.begin();
printf(「register mDNS servicern」);
MDNS.registerService(service);
}
void loop() {
// put your main code here, to run repeatedly:
delay(1000);
}
MDNSClass::end
MDNSClass::registerService
MDNSClass::deregisterService
MDNSClass::updateService
Class HttpClient
MDNSService Class
Members
Public Constructors |
|
---|---|
MDNSService::MDNSService |
Create a MDNS service record |
Public Methods |
|
MDNSService::addTxtRecord |
Add text to MDNS service record |
MDNSService::MDNSService
MDNSService::addTxtRecord
MQTTClient
Class PMUClass
PubSubClient Class
Members
Public Constructors |
|
---|---|
PubSubClient::PubSubClient |
Constructs a PubSubClient object |
Public Methods |
|
PubSubClient::setServer |
Set MQTT server address and port |
PubSubClient::setCallback |
Set callback function |
PubSubClient::setClient |
Set WiFi client |
PubSubClient::setStream |
Set data stream |
PubSubClient::connect |
Attempt to connect to server |
PubSubClient::disconnect |
Disconnect from current session |
PubSubClient::publish |
Publish a message to server |
PubSubClient::publish_P |
Same as above |
PubSubClient::subscribe |
Subscribe to a topic |
PubSubClient::unsubscribe |
Unsubscribe to a topic |
PubSubClient::loop |
Keep MQTT session alive and process any queuing tasks |
PubSubClient::connected |
Check if client still connected |
PubSubClient::state |
Return connection state |
PubSubClient::PubSubClient
#include <WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「secretPassword」; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio’s status
char mqttServer[] = 「test.mosquitto.org」;
char clientId[] = 「amebaClient」;
char publishTopic[] = 「outTopic」;
char publishPayload[] = 「hello world」;
char subscribeTopic[] = 「inTopic」;
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print(「Message arrived [「);
Serial.print(topic);
Serial.print(」] 「);
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
WiFiClient wifiClient;
PubSubClient client(wifiClient);
void reconnect() {
// Loop until we’re reconnected
while (!client.connected()) {
Serial.print(「Attempting MQTT connection…」);
// Attempt to connect
if (client.connect(clientId)) {
Serial.println(「connected」);
// Once connected, publish an announcement…
client.publish(publishTopic, publishPayload);
// … and resubscribe
client.subscribe(subscribeTopic);
} else {
Serial.print(「failed, rc=」);
Serial.print(client.state());
Serial.println(」 try again in 5 seconds」);
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
Serial.begin(38400);
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to SSID: 「);
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
client.setServer(mqttServer, 1883);
client.setCallback(callback);
// Allow the hardware to sort itself out
delay(1500);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
}
PubSubClient::setServer
PubSubClient::setCallback
PubSubClient::setClient
PubSubClient::setStream
PubSubClient::connect
PubSubClient::disconnect
PubSubClient::publish
PubSubClient::publish_P
PubSubClient::subscribe
PubSubClient::unsubscribe
PubSubClient::loop
PubSubClient::connected
PubSubClient::state
Readme
PubSubClient.cpp
PubSubClient.h
These libraries are under MIT License.
NTPClient
Readme
NTPClient.cpp
NTPClient.h
These libraries are licensed under MIT License.
PowerSave
Class PMUClass
PMUClass Class
Members
Public Constructors |
|
---|---|
PMUClass::PMUClass |
Constructs a PMUClass object |
Public Methods |
|
PMUCLASS::begin |
Initialize the PMUCLASS and select sleep mode |
PMUCLASS::AONTimerDuration |
Set the duration of AON Timer |
PMUCLASS::AONTimerCmd |
Disable the AON Timer for power save usage |
PMUCLASS::RTCWakeSetup |
Set up RTC Timer for power save usage |
PMUCLASS::enable |
Enable power save deep sleep mode |
PMUCLASS::AONWakeReason |
Check AON wakeup source |
PMUCLASS::WakePinCheck |
Check AON GPIO pin wakeup source |
PMUCLASS::AONWakeClear |
Clear all the AON wakeup source |
PMUCLASS::DsleepWakeStatusGet |
Check if deepsleep mode is set |
PMUCLASS::TL_sysactive_time |
Tickless mode system active time |
PMUCLASS::TL_wakelock |
Tickless mode wake lock, select acquire of release |
PMUCLASS::DS_AON_TIMER_WAKEUP |
Return the Wakeup source |
PMUCLASS::DS_RTC_WAKEUP |
Return the Wakeup source |
PMUCLASS::TL_UART_WAKEUP |
Return the Wakeup source |
PMUCLASS::TL_RTC_WAKEUP |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA12 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA13 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA14 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA15 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA16 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA17 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA18 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA19 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA20 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA21 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA25 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA26 |
Return the Wakeup source |
RTC
Class RTC
RTC Class
Members
Public Constructors |
|
---|---|
A public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named RTC. |
Public Methods |
|
---|---|
RTC:: Init |
Initializes the RTC device, including the Clock, the RTC registers, and other functions |
RTC:: DeInit |
Deinitialize the RTC device |
RTC:: Write |
Set the specified timestamp in seconds to RTC |
RTC:: Read |
Get the current timestamp in seconds from RTC |
RTC:: Wait |
Wait for 1 second |
RTC:: SetEpoch |
Convert human-readable time to epoch time |
RTC::Init
/*
* This function describes how to use the RTC API.
* The RTC function is implemented by an independent BCD timer/counter.
* This example will print out the time information every second.
*/
#include <stdio.h>
#include <time.h>
#include 「rtc.h」
#define YEAR 2020
#define MONTH 9
#define DAY 10
#define HOUR 20
#define MIN 30
#define SEC 40
/* Create an rtc object */
RTC rtc;
int32_t seconds;
struct tm *timeinfo;
void setup() {
Serial.begin(115200);
rtc.Init(); // initialize RTC
}
void loop() {
// step 1: convert user time to epoch
int epochTime = humanReadableToEpoch(YEAR, MONTH, DAY, HOUR, MIN, SEC);
// step 2: write epoch time to rtc
rtc.Write(epochTime);
while (1) {
seconds = rtc.Read();
printf(「Epoch Time (in s) since January 1, 1970 = %dsn」, seconds);
printf(「Time as a basic string = %s」, ctime(&seconds));
timeinfo = localtime(&seconds);
printf(「Time as a custom formatted string = %d-%d-%d %d:%d:%dn」,
(timeinfo->tm_year + 1900), (timeinfo->tm_mon + 1), timeinfo->tm_mday, timeinfo->tm_hour,
timeinfo->tm_min, timeinfo->tm_sec);
Serial.println();
rtc.wait(1);
}
}
// convert human readable time to epoch time
int humanReadableToEpoch(int year, int month, int day, int hour, int min, int sec) {
struct tm t;
time_t t_of_day;
t.tm_year = year - 1900; // Year - 1970
t.tm_mon = month - 1; // Month, where 0 = jan
t.tm_mday = day; // Day of the month
t.tm_hour = hour;
t.tm_min = min;
t.tm_sec = sec;
t.tm_isdst = -1; // Is DST on? 1 = yes, 0 = no, -1 = unknown
t_of_day = mktime(&t);
// printf(「seconds since the Epoch: %dn」, (long)t_of_day);
return t_of_day;
}
RTC::DeInit
RTC:: Write
RTC::Read
RTC:: Wait
RTC:: SetEpoch
SoftwareSerial
Class Adafruit_GPS
Adafruit_GPS Class
Members
Public Constructors |
|
---|---|
Adafruit_GPS::Adafruit_GPS |
Constructs an Adafruit_GPS object |
Public Methods |
|
Adafruit_GPS::begin |
Initialize serial communication |
*Adafruit_GPS:: lastNMEA |
Returns the last NMEA line received and unsets the received flag |
Adafruit_GPS:: newNMEAreceived |
Check to see if a new NMEA line has been received |
Adafruit_GPS:: common_init |
Initialization code used by all constructor types |
Adafruit_GPS:: sendCommand |
Send a command to the GPS device |
Adafruit_GPS:: pause |
Pause/unpause receiving new data |
Adafruit_GPS:: parseHex |
Read a Hex value and return the decimal equivalent |
Adafruit_GPS:: read |
Read one character from the GPS device |
Adafruit_GPS:: parse |
Parse an NMEA string |
Adafruit_GPS:: wakeup |
Wake the sensor up |
Adafruit_GPS:: standby |
Standby Mode Switches |
Adafruit_GPS::waitForSentence |
Wait for a specified sentence from the device |
Adafruit_GPS::LOCUS_StartLogger |
Start the LOCUS logger |
Adafruit_GPS::LOCUS_StopLogger |
Stop the LOCUS logger |
Adafruit_GPS::LOCUS_ReadStatus |
Read the logger status |
Adafruit_GPS::Adafruit_GPS
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>
// If you’re using a GPS module:
// Connect the GPS Power pin to 3.3V
// Connect the GPS Ground pin to ground
// Connect the GPS TX (transmit) pin to Digital 0
// Connect the GPS RX (receive) pin to Digital 1
#if defined(BOARD_RTL8195A)
SoftwareSerial mySerial(0, 1);
#elif defined(BOARD_RTL8710)
SoftwareSerial mySerial(17, 5); // RTL8710 need change GPS TX/RX to pin 17 and 5
#else
SoftwareSerial mySerial(0, 1);
#endif
Adafruit_GPS GPS(&mySerial);
// Set GPSECHO to 『false』 to turn off echoing the GPS data to the Serial console
// Set to 『true』 if you want to debug and listen to the raw GPS sentences.
#define GPSECHO false
void setup()
{
Serial.begin(38400);
Serial.println(「Adafruit GPS library basic test!」);
// 9600 NMEA is the default baud rate for Adafruit MTK GPS’s- some use 4800
GPS.begin(9600);
// uncomment this line to turn on RMC (recommended minimum) and GGA (fix data) including altitude
GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
// uncomment this line to turn on only the 「minimum recommended」 data
//GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCONLY);
// For parsing data, we don’t suggest using anything but either RMC only or RMC+GGA since
// the parser doesn’t care about other sentences at this time
// Set the update rate
GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ); // 1 Hz update rate
// For the parsing code to work nicely and have time to sort thru the data, and
// print it out we don’t suggest using anything higher than 1 Hz
// Request updates on antenna status, comment out to keep quiet
GPS.sendCommand(PGCMD_ANTENNA);
delay(1000);
// Ask for firmware version
mySerial.println(PMTK_Q_RELEASE);
}
uint32_t timer = millis();
void loop() // run over and over again
{
// in case you are not using the interrupt above, you’ll
// need to 『hand query』 the GPS, not suggested :(
// read data from the GPS in the 『main loop』
char c = GPS.read();
// if you want to debug, this is a good time to do it!
if (GPSECHO)
if (c) Serial.print(c);
// if a sentence is received, we can check the checksum, parse it…
if (GPS.newNMEAreceived()) {
// a tricky thing here is if we print the NMEA sentence, or data
// we end up not listening and catching other sentences!
// so be very wary if using OUTPUT_ALLDATA and trytng to print out data
//Serial.println(GPS.lastNMEA()); // this also sets the newNMEAreceived() flag to false
if (!GPS.parse(GPS.lastNMEA())) // this also sets the newNMEAreceived() flag to false
return; // we can fail to parse a sentence in which case we should just wait for another
}
// if millis() or timer wraps around, we’ll just reset it
if (timer > millis()) timer = millis();
// approximately every 2 seconds or so, print out the current stats
if (millis() - timer > 2000) {
timer = millis(); // reset the timer
Serial.print(」nTime: 「);
Serial.print(GPS.hour, DEC); Serial.print(『:』);
Serial.print(GPS.minute, DEC); Serial.print(『:』);
Serial.print(GPS.seconds, DEC); Serial.print(『.』);
Serial.println(GPS.milliseconds);
Serial.print(「Date: 「);
Serial.print(GPS.day, DEC); Serial.print(『/』);
Serial.print(GPS.month, DEC); Serial.print(「/20」);
Serial.println(GPS.year, DEC);
Serial.print(「Fix: 「); Serial.print((int)GPS.fix);
Serial.print(」 quality: 「); Serial.println((int)GPS.fixquality);
if (GPS.fix) {
Serial.print(「Location: 「);
Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
Serial.print(」, 「);
Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
Serial.print(「Location (in degrees, works with Google Maps): 「);
Serial.print(GPS.latitudeDegrees, 4);
Serial.print(」, 「);
Serial.println(GPS.longitudeDegrees, 4);
Serial.print(「Speed (knots): 「); Serial.println(GPS.speed);
Serial.print(「Angle: 「); Serial.println(GPS.angle);
Serial.print(「Altitude: 「); Serial.println(GPS.altitude);
Serial.print(「Satellites: 「); Serial.println((int)GPS.satellites);
}
}
}
Adafruit_GPS::begin
*Adafruit_GPS::lastNMEA
Adafruit_GPS::newNMEAreceived
Adafruit_GPS::common_init
Adafruit_GPS::sendCommand
Adafruit_GPS::pause
Adafruit_GPS::parseHex
Adafruit_GPS::read
Adafruit_GPS::parse
Adafruit_GPS::wakeup
Adafruit_GPS::standby
Adafruit_GPS::waitForSentence
Adafruit_GPS::LOCUS_StartLogger
Adafruit_GPS::LOCUS_StopLogger
Adafruit_GPS::LOCUS_ReadStatus
Class HttpClient
PMS3003 Class
Members
Public Constructors |
|
---|---|
PMS3003::PMS3003 |
Constructs a PMS3003 object |
Public Methods |
|
PMS3003::begin |
Initialize hardware UART |
PMS3003::end |
Free allocated space thus stopping UART |
PMS3003::get_pm1p0_cf1 |
Get PM1.0 under correction factor = 1 |
PMS3003:: get_pm2p5_cf1 |
Get PM2.5 under correction factor = 1 |
PMS3003:: get_pm10_cf1 |
Get PM10 under correction factor = 1 |
PMS3003:: get_pm1p0_air |
Get PM1.0 air quality |
PMS3003:: get_pm2p5_air |
Get PM2.5 air quality |
PMS3003:: get_pm10_air |
Get PM10 air quality |
PMS3003:update_cache |
Updates the cache memory |
PMS3003::pms3003_handle_interrupt |
Set up the serial event handler |
PMS3003::PMS3003
PMS3003::begin
PMS3003::end
PMS3003::get_pm1p0_cf1
PMS3003::get_pm2p5_cf1
PMS3003::get_pm10_cf1
PMS3003::get_pm1p0_air
PMS3003::get_pm2p5_air
PMS3003::get_pm10_air
PMS3003::pms3003_handle_interrupt
PMS3003::update_cache
Class SoftwareSerial
SoftwareSerial Class
Members
Public Constructors |
|
---|---|
SoftwareSerial::SoftwareSerial |
Constructs a SoftwareSerial object |
Public Methods |
|
SoftwareSerial::begin |
Sets the speed (baud rate) for the serial communication |
SoftwareSerial::listen |
Enables the selected software serial port to listen |
SoftwareSerial::end |
Same as stopListening |
SoftwareSerial::stopListening |
Stop listening on the port |
SoftwareSerial::peek |
Return a character that was received on the RX pin of the software serial port |
SoftwareSerial::write |
Prints data to the transmit pin of the software serial port as raw bytes |
SoftwareSerial::read |
Return a character that was received on the RX pin of the software serial port |
SoftwareSerial::available |
Get the number of bytes (characters) available for reading from a software serial port |
SoftwareSerial::flush |
Flush the received buffer |
SoftwareSerial::setBufferSize |
Set buffer size |
Soft wareSerial::setAvailableCallback |
Set available callback |
SoftwareSerial::handle_interrupt |
Private methods handles interrupt |
SoftwareSerial::SoftwareSerial
/*
The circuit: (BOARD RTL8195A)
* RX is digital pin 0 (connect to TX of other devices)
* TX is digital pin 1 (connect to RX of other devices)
*/
#include <SoftwareSerial.h>
#if defined(BOARD_RTL8195A)
SoftwareSerial mySerial(0, 1); // RX, TX
#elif defined(BOARD_RTL8710)
SoftwareSerial mySerial(17, 5); // RX, TX
#else
SoftwareSerial mySerial(0, 1); // RX, TX
#endif
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(57600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println(「Goodnight moon!」);
// set the data rate for the SoftwareSerial port
mySerial.begin(4800);
mySerial.println(「Hello, world?」);
}
void loop() { // run over and over
if (mySerial.available()) {
mySerial.write(mySerial.read());
}
}
SoftwareSerial::begin
SoftwareSerial::listen
SoftwareSerial::end
SoftwareSerial::isListening
SoftwareSerial::stopListening
SoftwareSerial::peek
SoftwareSerial::write
SoftwareSerial::read
SoftwareSerial::available
SoftwareSerial::flush
SoftwareSerial::setBufferSize
SoftwareSerial::setAvailableCallback
/*
The circuit: (BOARD RTL8195A)
RX is digital pin 0 (connect to TX of other devices)
TX is digital pin 1 (connect to RX of other devices)
*/
#include <SoftwareSerial.h>
#if defined(BOARD_RTL8195A)
SoftwareSerial mySerial(0, 1); // RX, TX
#elif defined(BOARD_RTL8710)
SoftwareSerial mySerial(17, 5); // RX, TX
#else
SoftwareSerial mySerial(0, 1); // RX, TX
#endif
uint32_t semaID;
// The callback is hooking at UART IRQ handler and please don’t do heavy task here.
void mySerialCallback(char c)
{
/* The parameter c is only for peeking. The actual data is
* still in the buffer of SoftwareSerial.
*/
if (c == 『r』 || c == 『n』) {
os_semaphore_release(semaID);
}
}
void setup() {
// use 1 count for binary semaphore
semaID = os_semaphore_create(1);
// There is a token in the semaphore, clear it.
os_semaphore_wait(semaID, 0xFFFFFFFF);
// set the data rate for the SoftwareSerial port
mySerial.begin(38400);
mySerial.setAvailableCallback(mySerialCallback);
}
void loop() { // run over and over
// wait semaphore for 5s timeout
if (os_semaphore_wait(semaID, 5 * 1000)) {
// we got data before timeout
while(mySerial.available()) {
mySerial.print((char)mySerial.read());
}
mySerial.println();
} else {
mySerial.println(「No data comes in.」);
}
}
SoftwareSerial::handle_interrupt
Readme
NewSoftSerial.h
by Mikal Hart
(http://arduiniana.org/libraries/newsoftserial).
SoftwareSerial.cpp
SoftwareSerial.h
These libraries are under GNU Lesser General Public License.
Adafruit_GPS.cpp
Adafruit_GPS.h
These libraries are under BSD License.
SPI
Class AmebaILI9341
AmebaILI9341 Class
Description
Defines a class to use ILI9341 TFT SPI display for Ameba.
Syntax
class AmebaILI9341
Members
Public Constructors |
|
---|---|
AmebaILI9341::AmebaILI9341 |
Constructs an AmebaILI9341 object |
Public Methods |
|
AmebaILI9341::begin |
Initialize SPI, pin mapping and screen configuration |
AmebaILI9341::setAddress |
Initialize image size and position |
AmebaILI9341::writecommand |
SPI transfer a command |
AmebaILI9341::writedata |
SPI transfer a piece of data |
AmebaILI9341::setRotation |
Set screen orientation |
AmebaILI9341::fillScreen |
Fill the screen with a color |
AmebaILI9341::clr |
Clear screen |
AmebaILI9341::fillRectangle |
Fill a rectangular space with a color |
AmebaILI9341::drawPixel |
Turn on a pixel on the screen |
AmebaILI9341::drawChar |
To print a character on the screen |
AmebaILI9341::drawLine |
Draw line on the screen |
AmebaILI9341::drawRectangle |
Draw a rectangle on the screen |
AmebaILI9341::drawCircle |
Draw a circle on the screen |
AmebaILI9341::write |
Same as drawChar |
AmebaILI9341::getWidth |
Return the width 240 |
AmebaILI9341::getHeight |
Return the height 320 |
AmebaILI9341::setCursor |
Set cursor to the desired position |
AmebaILI9341::setForeground |
Set foreground color |
AmebaILI9341::setBackground |
Set background color |
AmebaILI9341::setFontSize |
Set character font size |
AmebaILI9341::reset |
Reset pin to High or Low |
AmebaILI9341::AmebaILI9341
Description
Constructs an AmebaILI9341 object and set CS, DC and RESET pins .
Syntax
AmebaILI9341::AmebaILI9341(int csPin, int dcPin, int resetPin)
Parameters
csPin: pin for Chip Select dcPin: pin for Data/Command resetPin: pin for Reset
Returns
The function returns nothing.
Example Code
Example: : PM25_ON_ILI9341_TFT_LCD
This example demonstrates how to read pm2.5 value on PMS 3003 air-condition sensor and display it on ILI9341 TFT LCD.
/*
PMS 3003 pin map is as follow:
PIN1 :VCC, connect to 5V
PIN2 :GND
PIN3 :SET, 0:Standby mode, 1:operating mode
PIN4 :RXD :Serial RX
PIN5 :TXD :Serial TX
PIN6 :RESET
PIN7 :NC
PIN8 :NC
In this example, we only use Serial to get PM 2.5 value.
The circuit:
* RX is digital pin 0 (connect to TX of PMS 3003)
* TX is digital pin 1 (connect to RX of PMS 3003)
For RTL8195A ILI9341 TFT LCD with SPI interface has these pins:
D/C : connect to pin 9
CS : connect to pin 10
MOSI : connect to pin 11
MISO : connect to pin 12
CLK : connect to pin 13
VCC : connect to 3V3
GND : connect to GND
*/
#include 「SoftwareSerial.h」
#include 「SPI.h」
#include 「AmebaILI9341.h」
#if defined(BOARD_RTL8195A)
SoftwareSerial mySerial(0, 1); // RX, TX
#define TFT_RESET 8
#define TFT_DC 9
#define TFT_CS 10
#elif defined(BOARD_RTL8710)
SoftwareSerial mySerial(17, 5); // RX, TX
// IMPORTANT: Due to limit pin, we do not connect TFT_RESET pin.
#define TFT_RESET 0xFFFFFFFF
#define TFT_DC 2
#define TFT_CS 10
#endif
AmebaILI9341 tft = AmebaILI9341(TFT_CS, TFT_DC, TFT_RESET);
#define ILI9341_SPI_FREQUENCY 20000000
#define pmsDataLen 32
uint8_t buf[pmsDataLen];
int idx = 0;
int pm10 = 0;
int last_pm25 = 0;
int pm25 = 0;
int pm100 = 0;
uint16_t pm25color[] = {
0x9FF3,
0x37E0,
0x3660,
0xFFE0,
0xFE60,
0xFCC0,
0xFB2C,
0xF800,
0x9800,
0xC99F
};
void setup() {
Serial.begin(57600);
mySerial.begin(9600); // PMS 3003 UART has baud rate 9600
SPI.setDefaultFrequency(ILI9341_SPI_FREQUENCY);
tft.begin();
drawPictureFrames();
}
void loop() { // run over and over
uint8_t c;
idx = 0;
memset(buf, 0, pmsDataLen);
while (true) {
while (c != 0x42) {
while (!mySerial.available());
c = mySerial.read();
}
while (!mySerial.available());
c = mySerial.read();
if (c == 0x4d) {
// now we got a correct header)
buf[idx++] = 0x42;
buf[idx++] = 0x4d;
break;
}
}
while (idx != pmsDataLen) {
while(!mySerial.available());
buf[idx++] = mySerial.read();
}
pm10 = ( buf[10] << 8 ) | buf[11];
last_pm25 = pm25;
pm25 = ( buf[12] << 8 ) | buf[13];
pm100 = ( buf[14] << 8 ) | buf[15];
updateValueToTftScreen();
}
void drawPictureFrames() {
tft.setRotation(1);
tft.clr();
tft.setFontSize(1);
// Upper title
tft.setFontSize(1);
tft.setCursor(20,20);
tft.print(「PM2.5 DETECTOR」);
// PM 2.5 Circle Frame
tft.drawCircle(100,130,60, ILI9341_BLUE);
tft.drawCircle(100,130,61, ILI9341_BLUE);
tft.setFontSize(1);
tft.setCursor(90,85);
tft.print(「PM2.5」);
tft.setFontSize(1);
tft.setCursor(90,170);
tft.print(「um/m3」);
// PM 10 Circle Frame
tft.drawCircle(220,70,40, ILI9341_BLUE);
tft.setFontSize(1);
tft.setCursor(210,40);
tft.print(「PM10」);
tft.setFontSize(1);
tft.setCursor(205,95);
tft.print(「um/m3」);
// PM 1.0 Circle Frame
tft.drawCircle(220,170,40, ILI9341_BLUE);
tft.setFontSize(1);
tft.setCursor(205,140);
tft.print(「PM1.0」);
tft.setFontSize(1);
tft.setCursor(205,195);
tft.print(「um/m3」);
// right side bar, referenced from: http://taqm.epa.gov.tw/taqm/tw/
tft.fillRectangle(290, 30+ 0*2, 10, 12*2, pm25color[0]); // 0~11
tft.fillRectangle(290, 30+12*2, 10, 12*2, pm25color[1]); // 12-23
tft.fillRectangle(290, 30+24*2, 10, 12*2, pm25color[2]); // 24-35
tft.fillRectangle(290, 30+36*2, 10, 6*2, pm25color[3]); // 36-41
tft.fillRectangle(290, 30+42*2, 10, 6*2, pm25color[4]); // 42-47
tft.fillRectangle(290, 30+48*2, 10, 6*2, pm25color[5]); // 48-53
tft.fillRectangle(290, 30+54*2, 10, 6*2, pm25color[6]); // 54-58
tft.fillRectangle(290, 30+59*2, 10, 6*2, pm25color[7]); // 59-64
tft.fillRectangle(290, 30+65*2, 10, 6*2, pm25color[8]); // 65-70
tft.fillRectangle(290, 30+71*2, 10, 10*2, pm25color[9]); // >=71
tft.setCursor(302, 30);
tft.setFontSize(1);
tft.print(「0」);
tft.setCursor(302, 30+36*2);
tft.print(「36」);
tft.setCursor(302, 30+54*2);
tft.print(「54」);
tft.setCursor(302, 30+71*2);
tft.print(「71」);
// bottom right text
tft.setCursor(210,230);
tft.setFontSize(1);
tft.print(「Powered by Realtek」);
updateValueToTftScreen();
}
void updateValueToTftScreen() {
tft.setCursor(60, 111);
tft.setFontSize(5);
tft.setForeground( getPm25Color(pm25) );
if (pm25 < 10) {
tft.print(」 「);
} else if (pm25 < 100) {
tft.print(」 「);
}
tft.print(pm25);
tft.setCursor(195,60);
tft.setFontSize(3);
if (pm100 < 10) {
tft.print(」 「);
} else if (pm100 < 100) {
tft.print(」 「);
}
tft.print(pm100);
tft.setCursor(198,160);
if (pm10 < 10) {
tft.print(」 「);
} else if (pm10 < 100) {
tft.print(」 「);
}
tft.print(pm10);
tft.setFontSize(1);
tft.setForeground(ILI9341_WHITE);
if (last_pm25 > 80) {
tft.fillRectangle(275, 80*2+30-3, 12, 8, ILI9341_BLACK);
} else {
tft.fillRectangle(275, last_pm25*2+30-3, 12, 8, ILI9341_BLACK);
}
if (pm25 > 80) {
tft.setCursor(275, 80*2+30-3);
} else {
tft.setCursor(275, pm25*2+30-3);
}
tft.print(「=>」);
}
uint16_t getPm25Color(int v) {
if (v < 12) {
return pm25color[0];
} else if (v < 24) {
return pm25color[1];
} else if (v < 36) {
return pm25color[2];
} else if (v < 42) {
return pm25color[3];
} else if (v < 48) {
return pm25color[4];
} else if (v < 54) {
return pm25color[5];
} else if (v < 59) {
return pm25color[6];
} else if (v < 65) {
return pm25color[7];
} else if (v < 71) {
return pm25color[8];
} else {
return pm25color[9];
}
}
Notes and Warnings
NA
AmebaILI9341::begin
Description
Initialize hardware SPI, pin mapping and screen configuration
Syntax
void AmebaILI9341::begin(void)
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
This method is required to run first before other operations on the display.
AmebaILI9341::setAddress
Description
Initialize image size and positioning on the display
Syntax
void AmebaILI9341::setAddress(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1)
Parameters
x0: leftmost coordinate of the image y0: top coordinate of the image x1: rightmost coordinate of the image y1: bottom coordinate of the image
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Do not use this to set the cursor, use the “setCursor” method instead.
AmebaILI9341::writecommand
Description
Write a single-byte command to display
Syntax
void AmebaILI9341::writecommand(uint8_t command)
Parameters
command: a single byte command
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::writedata
Description
Write 1 byte of data to display
Syntax
void AmebaILI9341::writedata(uint8_t data)
Parameters
data: 1 byte data
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Only use this method to write 1 byte at a time.
AmebaILI9341::setRotation
Description
Setting screen orientation, “0” for no rotation, “1” for 90 degrees rotation and so on so forth.
Syntax
void AmebaILI9341::setRotation(uint8_t m)/span> Parameters
m: one of the 4 rotation modes -> “0” for no rotation, “1” for 90⁰, “2” for 180⁰, “3” for 270⁰
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
if m=4, it’s equivalent to mode 0, and m=5 for mode 1, m=6 for mode 2 so on so forth.
AmebaILI9341::fillScreen
Description
Fill the entire screen with one color
Syntax
void AmebaILI9341::fillScreen(uint16_t color)
Parameters
color: a 16-bit color reference defined in AmebaILI9341.h
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Refer to AmebaILI9341.h for available colors.
AmebaILI9341::clr
Description
Fill the entire screen with a certain background-color
Syntax
void AmebaILI9341::clr(void)
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341
Notes and Warnings
background-color can be set by calling setBackground method.
AmebaILI9341::fillRectangle
Description
Fill a rectangular space with a color on the screen
Syntax
void AmebaILI9341::fillRectangle(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color)
Parameters
x: leftmost coordinate of the image y: top coordinate of the image w: width of the image h: height of the image color: the color of the image
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
NA
AmebaILI9341::drawPixel
Description
Turn on a pixel on the screen
Syntax
void AmebaILI9341::drawPixel(int16_t x, int16_t y, uint16_t color)
Parameters
x: leftmost coordinate of the image y: top coordinate of the image color: the color of the image
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::drawChar
Description
Draw character on the screen
Syntax
void AmebaILI9341::drawChar(unsigned char c) void AmebaILI9341::drawChar(int16_t x, int16_t y, unsigned char c, uint16_t _fontcolor, uint16_t _background, uint8_t _fontsize)
Parameters
x: leftmost coordinate of the image y: top coordinate of the image c: a character _fontcolor: font color _background: background color _fontsize: font size
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
In the actual example, the Print method is used to print a string of character on the screen instead of using this method.
AmebaILI9341::drawLine
Description
Draw a straight line on the screen
Syntax
void AmebaILI9341::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1) void AmebaILI9341::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t color)
Parameters
x0: leftmost coordinate of the image y0: top coordinate of the image x1: leftmost coordinate of the image y1: top coordinate of the image color: the color of the image
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::drawRectangle
Description
Draw a rectangular shape on the screen
Syntax
void AmebaILI9341::drawRectangle(int16_t x, int16_t y, int16_t w, int16_t h) void AmebaILI9341::drawRectangle(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color)
Parameters
x: leftmost coordinate of the image y: top coordinate of the image w: width of the image h: height of the image color: the color of the image
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::drawCircle
Description
Draw a circular shape on the screen
Syntax
void AmebaILI9341::drawCircle(int16_t x0, int16_t y0, int16_t r) void AmebaILI9341::drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color)
Parameters
x0: leftmost coordinate of the image y0: top coordinate of the image r: radius of the image color: the color of the image
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Include “AmebaServo.h” to use the class function.
AmebaILI9341::write
Description
Same as drawChar, write a character on the screen
Syntax
size_t AmebaILI9341::write(uint8_t c)
Parameters
c: a character to be written on the screen
Returns
Number of bytes written
Example Code
NA
Notes and Warnings
This an inherited method from Print class and is seldom used.
AmebaILI9341::getWidth
Description
Get the width of the image
Syntax
int16_t AmebaILI9341::getWidth(void)
Parameters
The function requires no input parameter.
Returns
Width of the image
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::getHeight
Description
Get the height of the image
Syntax
int16_t AmebaILI9341::getHeight(void)
Parameters
The function requires no input parameter.
Returns
Height of the image
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::setCursor
Description
Set the cursor to a specific position on the screen
Syntax
void AmebaILI9341::setCursor(int16_t x, int16_t y)
Parameters
x: coordinate on the x-axis y: coordinate on the y-axis
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
NA
AmebaILI9341::setForeground
Description
Set foreground color
Syntax
void AmebaILI9341::setForeground(uint16_t color)
Parameters
color: one of the colors available in AmebaILI9341.h
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
NA
AmebaILI9341::setBackground
Description
Set background color
Syntax
void AmebaILI9341::setBackground(uint16_t _background)
Parameters
_background: one of the colors available in AmebaILI9341.h
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
NA
AmebaILI9341::setFontSize
Description
Set the font size of the characters printed on the screen.
Syntax
void AmebaILI9341::setFontSize(uint8_t size)
Parameters
size: font size, default 1 for smallest, 5 for largest font size
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
NA
AmebaILI9341::reset
Description
Reset the pin to High or Low
Syntax
void AmebaILI9341::reset(void)
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
Class SPISettings_SPIClass
SPISettings Class
Members
Public Constructors |
|
---|---|
SPISettings::SPISettings |
Create a SPISettings object and set SPI clock speed, bit order and data mode |
SPISettings::SPISettings
SPIClass Class
Members
Public Constructors |
|
---|---|
SPIClass::SPIClass |
Constructs an SPI object |
Public Methods |
|
SPIClass::transfer |
Transfer data through SPI |
SPIClass::transfer16 |
Transfer a 16-bits data through SPI |
SPIClass::beginTransaction |
Set slave select pin and SPI initial settings |
SPIClass::endTransaction |
Stop SPI transaction |
SPIClass::begin |
Associate each SPI pin to Ameba pin using ameba HAL APIs |
SPIClass::end |
Stop SPI master mode |
SPIClass::setBitOrder |
Set MSB first or LSB first |
SPIClass::setDataMode |
Set to one of the four data modes |
SPIClass::setClockDivider |
Set to correct clock speed (no effect on Ameba) |
SPIClass::setDefaultFrequency |
Set default SPI frequency |
SPIClass::SPIClass
SPIClass::transfer
SPIClass::transfer16
SPIClass::beginTransaction
SPIClass::endTransaction
SPIClass::begin
SPIClass::end
SPIClass::setBitOrder
SPIClass::setDataMode
SPIClass::setClockDivider
SPIClass::setDefaultFrequency
Readme
The Ameba SPI related APIs and examples are works based on SPI Master library for arduino written by Cristian Maglie <c.maglie@arduino.cc> and Paul Stoffregen <paul@pjrc.com> (Transaction API).
These libraries are under GNU Lesser General Public License, version 2.1.
Sys
Wiring_OS_API
Wiring OS API
Members
Public Methods |
|
---|---|
os_thread_create_arduino |
Create a thread and add it to Active Threads and set it to state READY |
os_thread_get_id_arduino |
Return the thread ID of the current running thread |
os_thread_terminate_arduino |
Terminate execution of a thread and remove it from Active Threads |
os_thread_yield_arduino |
Pass control to next thread that is in state READY |
os_thread_set_priority_arduino |
Change priority of an active thread |
os_thread_get_priority_arduino |
Get current priority of an active thread |
os_signal_set_arduino |
Set the specified Signal Flags of an active thread |
os_signal_clear_arduino |
Clear the specified Signal Flags of an active thread |
os_signal_wait_arduino |
Wait for one or more Signal Flags to become signaled for the current RUNNING thread |
os_timer_create_arduino |
Create a timer |
os_timer_start_arduino |
Start or restart a timer |
os_timer_stop_arduino |
Stop the timer |
os_timer_delete_arduino |
Delete a timer that was created by os_timer_create |
os_semaphore_create_arduino |
Create and Initialize a Semaphore object used for managing resources |
os_semaphore_wait_arduino |
Wait until a Semaphore token becomes available |
os_semaphore_release_arduino |
Release a Semaphore token |
os_semaphore_delete_arduino |
Delete a Semaphore that was created by os_semaphore_create |
os_get_free_heap_size_arduino |
Return the available heap memory space when called |
os_thread_create_arduino
os_thread_get_id_arduino
os_thread_terminate_arduino
os_thread_yield_arduino
os_thread_set_priority_arduino
os_thread_get_priority_arduino
os_signal_set_arduino
os_signal_clear_arduino
os_signal_wait_arduino
os_timer_create_arduino
os_timer_start_arduino
os_timer_stop_arduino
os_timer_delete_arduino
os_semaphore_create_arduino
os_semaphore_wait_arduino
os_semaphore_release_arduino
os_semaphore_delete_arduino
os_get_free_heap_size_arduino
WDT
Class WDT
WDT Class
Members
Public Constructors |
|
---|---|
A public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named WDT. |
Public Methods |
|
---|---|
WDT:: InitWatchdog |
Initializes the watchdog, include time setting, and mode register |
WDT:: StartWatchdog |
Start the watchdog counting |
WDT:: StopWatchdog |
Stop the watchdog counting |
WDT:: RefreshWatchdog |
Refresh the watchdog counting to prevent WDT timeout |
WDT:: InitWatchdogIRQ |
Switch the watchdog timer to interrupt mode and register a watchdog timer timeout interrupt handler |
WDT:: InitWatchdog
/*
* This example describes how to use watchdog api.
* In this example, watchdog is setup to 5s timeout.
* Watchdog won’t bark if we refresh it before timeout in smallTask.
* The timer is also reloaded after refresh.
* Otherwise, while running bigTask, watchdog will restart system in default or call callback function if registered.
*/
#include 「wdt.h」
#define RUN_CALLBACK_IF_WATCHDOG_BARKS (0)
WDT wdt;
void setup() {
Serial.begin(115200);
wdt.InitWatchdog(5000); // setup 5s watchdog
#if RUN_CALLBACK_IF_WATCHDOG_BARKS
wdt.InitWatchdogIRQ(my_watchdog_irq_handler, 0);
#else
// system would restart in default when watchdog barks
#endif
wdt.StartWatchdog(); // enable watchdog timer
successfulTask();
failedTask();
while (1)
;
}
void loop() {
}
void successfulTask(void) {
Serial.println(」……doing small task……」);
for (int i = 0; i < 50000000; i++) // dummy task
asm(」 nop」);
Serial.println(「refresh watchdogrn」);
wdt.RefreshWatchdog();
}
/*
* Doing this task will lead to failed refresh the
* watchdog timer within the time limits of 5 seconds
*/
void failedTask(void) {
Serial.println(」……doing big task……」);
for (int i = 0; i < 10; i++) {
Serial.print(「doing dummy task #」);
Serial.println(i, DEC);
for (int j = 0; j < 50000000; j++) // dummy task
asm(」 nop」);
}
Serial.println(「refresh watchdogrn」);
wdt.RefreshWatchdog();
}
void my_watchdog_irq_handler(uint32_t id) {
printf(「watchdog barks!!!rn」);
WDG_Cmd(DISABLE);
}
WDT:: StartWatchdog
WDT:: StopWatchdog
WDT:: RefreshWatchdog
WDT:: InitWatchdogIRQ
WiFi
Class WiFi
WiFiClass Class
Members
Public Constructors |
|
---|---|
WiFiClass::WiFiClass |
Constructs a WiFiClass object and initializes the WiFi libraries and network settings |
Public Methods |
|
WiFiClass::firmwareVersion |
Get firmware version |
WiFiClass:: begin |
Start Wifi connection for OPEN networks |
WiFiClass:: config |
Configure network IP settings |
WiFiClass:: setDNS |
Set the DNS server IP address to use |
WiFiClass:: disconnect |
Disconnect from the network |
WiFiClass:: macAddress |
Get the interface MAC address |
WiFiClass:: localIP |
Get the interface IP address |
WiFiClass:: subnetMask |
Get the interface subnet mask address |
WiFiClass:: gatewayIP |
Get the gateway IP address |
WiFiClass:: SSID |
Return the current SSID associated with the network |
WiFiClass:: BSSID |
Return the current BSSID associated with the network |
WiFiClass:: RSSI |
Return the current RSSI (Received Signal Strength in dBm) associated with the network |
WiFiClass:: encryptionType |
Return the Encryption Type associated with the network |
WiFiClass:: scanNetworks |
Start scan WiFi networks available |
WiFiClass:: SSID |
Return the SSID discovered during the network scan |
WiFiClass:: encryptionType |
Return the encryption type of the networks discovered during the scanNetworks |
WiFiClass:: encryptionTypeEx |
Return the security type and encryption type of the networks discovered during the scanNetworks |
WiFiClass:: RSSI |
Return the RSSI of the networks discovered during the scanNetworks |
WiFiClass:: status |
Return Connection status |
WiFiClass:: hostByName |
Resolve the given hostname to an IP address |
WiFiClass:: apbegin |
Start AP mode |
WiFiClass:: disablePowerSave |
Disable power-saving mode |
WiFiClass::WiFiClass
WiFiClass::firmwareVersion
#include <WiFi.h>
// char ssid[] = 「yourNetwork」; // your network SSID (name)
// char pass[] = 「secretPassword」; // your network password
char ssid[] = 「SINGTEL-D45F」; // your network SSID (name)
char pass[] = 「mooxuteeth」; // your network key
int status = WL_IDLE_STATUS; // the Wifi radio’s status
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to WPA SSID: 「);
Serial.println(ssid);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// you’re connected now, so print out the data:
Serial.print(「You’re connected to the network」);
printCurrentNet();
printWifiData();
}
void loop() {
// check the network connection once every 10 seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print(「MAC address: 「);
Serial.print(mac[0], HEX);
Serial.print(「:」);
Serial.print(mac[1], HEX);
Serial.print(「:」);
Serial.print(mac[2], HEX);
Serial.print(「:」);
Serial.print(mac[3], HEX);
Serial.print(「:」);
Serial.print(mac[4], HEX);
Serial.print(「:」);
Serial.println(mac[5], HEX);
}
void printCurrentNet() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print the MAC address of the router you’re attached to:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print(「BSSID: 「);
Serial.print(bssid[5], HEX);
Serial.print(「:」);
Serial.print(bssid[4], HEX);
Serial.print(「:」);
Serial.print(bssid[3], HEX);
Serial.print(「:」);
Serial.print(bssid[2], HEX);
Serial.print(「:」);
Serial.print(bssid[1], HEX);
Serial.print(「:」);
Serial.println(bssid[0], HEX);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.println(rssi);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print(「Encryption Type:」);
Serial.println(encryption, HEX);
Serial.println();
}
WiFiClass::begin
WiFiClass::config
WiFiClass::setDNS
WiFiClass::disconnect
WiFiClass::macAddress
WiFiClass::localIP
WiFiClass::subnetMask
#include <WiFi.h>
char ssid[] = 「SINGTEL-D45F_5G」; // the name of your network
int status = WL_IDLE_STATUS; // the Wifi radio’s status
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to open SSID: 「);
Serial.println(ssid);
status = WiFi.begin(ssid);
// wait 10 seconds for connection:
delay(10000);
}
// you’re connected now, so print out the data:
Serial.print(「You’re connected to the network」);
printCurrentNet();
printWifiData();
}
void loop() {
// check the network connection once every 10 seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print(「MAC address: 「);
Serial.print(mac[0], HEX);
Serial.print(「:」);
Serial.print(mac[1], HEX);
Serial.print(「:」);
Serial.print(mac[2], HEX);
Serial.print(「:」);
Serial.print(mac[3], HEX);
Serial.print(「:」);
Serial.print(mac[4], HEX);
Serial.print(「:」);
Serial.println(mac[5], HEX);
// print your subnet mask:
IPAddress subnet = WiFi.subnetMask();
Serial.print(「NetMask: 「);
Serial.println(subnet);
// print your gateway address:
IPAddress gateway = WiFi.gatewayIP();
Serial.print(「Gateway: 「);
Serial.println(gateway);
}
void printCurrentNet() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print the MAC address of the router you’re attached to:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print(「BSSID: 「);
Serial.print(bssid[5], HEX);
Serial.print(「:」);
Serial.print(bssid[4], HEX);
Serial.print(「:」);
Serial.print(bssid[3], HEX);
Serial.print(「:」);
Serial.print(bssid[2], HEX);
Serial.print(「:」);
Serial.print(bssid[1], HEX);
Serial.print(「:」);
Serial.println(bssid[0], HEX);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.println(rssi);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print(「Encryption Type:」);
Serial.println(encryption, HEX);
}
WiFiClass::gatewayIP
WiFiClass::SSID
WiFiClass::BSSID
WiFiClass::RSSI
WiFiClass::encryptionType
WiFiClass::scanNetworks
#include <WiFi.h>
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// Print WiFi MAC address:
printMacAddress();
}
void loop() {
// scan for existing networks:
Serial.println(「Scanning available networks…」);
listNetworks();
delay(10000);
}
void printMacAddress() {
// the MAC address of your Wifi shield
byte mac[6];
// print your MAC address:
WiFi.macAddress(mac);
Serial.print(「MAC: 「);
Serial.print(mac[0], HEX);
Serial.print(「:」);
Serial.print(mac[1], HEX);
Serial.print(「:」);
Serial.print(mac[2], HEX);
Serial.print(「:」);
Serial.print(mac[3], HEX);
Serial.print(「:」);
Serial.print(mac[4], HEX);
Serial.print(「:」);
Serial.println(mac[5], HEX);
}
void listNetworks() {
// scan for nearby networks:
Serial.println(」* Scan Networks *」);
int numSsid = WiFi.scanNetworks();
if (numSsid == -1) {
Serial.println(「Couldn’t get a wifi connection」);
while (true);
}
// print the list of networks seen:
Serial.print(「number of available networks:」);
Serial.println(numSsid);
// print the network number and name for each network found:
for (int thisNet = 0; thisNet < numSsid; thisNet++) {
Serial.print(thisNet);
Serial.print(」) 「);
Serial.print(WiFi.SSID(thisNet));
Serial.print(」tSignal: 「);
Serial.print(WiFi.RSSI(thisNet));
Serial.print(」 dBm」);
Serial.print(」tEncryptionRaw: 「);
printEncryptionTypeEx(WiFi.encryptionTypeEx(thisNet));
Serial.print(」tEncryption: 「);
printEncryptionType(WiFi.encryptionType(thisNet));
}
}
void printEncryptionTypeEx(uint32_t thisType) {
/* Arduino wifi api use encryption type to mapping to security type.
* This function demonstrate how to get more richful information of security type.
*/
switch (thisType) {
case SECURITY_OPEN:
Serial.print(「Open」);
break;
case SECURITY_WEP_PSK:
Serial.print(「WEP」);
break;
case SECURITY_WPA_TKIP_PSK:
Serial.print(「WPA TKIP」);
break;
case SECURITY_WPA_AES_PSK:
Serial.print(「WPA AES」);
break;
case SECURITY_WPA2_AES_PSK:
Serial.print(「WPA2 AES」);
break;
case SECURITY_WPA2_TKIP_PSK:
Serial.print(「WPA2 TKIP」);
break;
case SECURITY_WPA2_MIXED_PSK:
Serial.print(「WPA2 Mixed」);
break;
case SECURITY_WPA_WPA2_MIXED:
Serial.print(「WPA/WPA2 AES」);
break;
}
}
void printEncryptionType(int thisType) {
// read the encryption type and print out the name:
switch (thisType) {
case ENC_TYPE_WEP:
Serial.println(「WEP」);
break;
case ENC_TYPE_TKIP:
Serial.println(「WPA」);
break;
case ENC_TYPE_CCMP:
Serial.println(「WPA2」);
break;
case ENC_TYPE_NONE:
Serial.println(「None」);
break;
case ENC_TYPE_AUTO:
Serial.println(「Auto」);
break;
}
}
WiFiClass::SSID
WiFiClass::encryptionType
WiFiClass::encryptionTypeEx
WiFiClass::RSSI
WiFiClass::status
WiFiClass::hostByName
WiFiClass::apbegin
#include
char ssid[] = 「yourNetwork」; //Set the AP’s SSID
char pass[] = 「Password」; //Set the AP’s password
char channel[] = 「1」; //Set the AP’s channel
int status = WL_IDLE_STATUS; // the Wifi radio’s status
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// attempt to start AP:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to start AP with SSID: 「);
Serial.println(ssid);
status = WiFi.apbegin(ssid, pass, channel);
delay(10000);
}
//AP MODE already started:
Serial.println(「AP mode already started」);
Serial.println();
printWifiData();
printCurrentNet();
}
void loop() {
// check the network connection once every 10 seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print your subnet mask:
IPAddress subnet = WiFi.subnetMask();
Serial.print(「NetMask: 「);
Serial.println(subnet);
// print your gateway address:
IPAddress gateway = WiFi.gatewayIP();
Serial.print(「Gateway: 「);
Serial.println(gateway);
Serial.println();
}
void printCurrentNet() {
// print the SSID of the AP:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print the MAC address of AP:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print(「BSSID: 「);
Serial.print(bssid[0], HEX);
Serial.print(「:」);
Serial.print(bssid[1], HEX);
Serial.print(「:」);
Serial.print(bssid[2], HEX);
Serial.print(「:」);
Serial.print(bssid[3], HEX);
Serial.print(「:」);
Serial.print(bssid[4], HEX);
Serial.print(「:」);
Serial.println(bssid[5], HEX);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print(「Encryption Type:」);
Serial.println(encryption, HEX);
Serial.println();
}
WiFiClass::disablePowerSave
Class WiFiClient
WiFiClient Class
Members
Public Constructors |
|
---|---|
WiFiClient::WiFiClient |
Constructs a WiFiClient instance that connects to the specified IP address and port. |
Public Methods |
|
WiFiClient::connect |
Connect to the IP address and port |
WiFiClient::write |
Write a single byte into the packet |
WiFiClient::available |
Number of bytes remaining in the current packet |
WiFiClient::read |
Read a single byte from the current packet |
WiFiClient:: peek |
Return the next byte from the current packet without moving on to the next byte |
WiFiClient:: flush |
Finish reading the current packet |
WiFiClient::stop |
Stop client connection |
WiFiClient::connected |
Check if client is connected, return 1 if connected, 0 if not |
WiFiClient::setRecvTimeout |
Set receiving timeout |
WiFiClient::WiFiClient
#include <WiFi.h>
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「password」; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
//IPAddress server(64,233,189,94); // numeric IP for Google (no DNS)
char server[] = 「www.google.com」; // name address for Google (using DNS)
WiFiClient client;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
;
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to SSID: 「);
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(「Connected to wifi」);
printWifiStatus();
Serial.println(」nStarting connection to server…」);
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println(「connected to server」);
// Make a HTTP request:
client.println(「GET /search?q=ameba HTTP/1.1」);
client.println(「Host: www.google.com」);
client.println(「Connection: close」);
client.println();
}
}
void loop() {
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// if the server’s disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println(「disconnecting from server.」);
client.stop();
// do nothing forevermore:
while (true);
}
}
void printWifiStatus() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.print(rssi);
Serial.println(」 dBm」);
}
WiFiClient::connect
WiFiClient::write
WiFiClient::available
WiFiClient::read
WiFiClient::peek
WiFiClient::flush
WiFiClient::stop
WiFiClient::connected
WiFiClient::setRecvTimeout
Class WiFiServer
WiFiServer Class
Members
Public Constructors |
|
---|---|
WiFiServer::WiFiServer |
Constructs a WiFiServer object and creates a server that listens for incoming connections on the specified port |
Public Methods |
|
WiFiServer::available |
Gets a client that is connected to the server and has data available for reading. The connection persists when the returned client object goes out of scope; you can close it by calling the client.stop() |
WiFiServer::begin |
Tells the server to begin listening for incoming connections |
WiFiServer::write |
Write data to all the clients connected to a server |
WiFiServer::WiFiServer
#include <WiFi.h>
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「secretPassword」; // your network password
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(5000);
void setup() {
Serial.begin(9600); // initialize serial communication
pinMode(9, OUTPUT); // set the LED pin mode
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
while (true); // don’t continue
}
String fv = WiFi.firmwareVersion();
if ( fv != 「1.1.0」 )
Serial.println(「Please upgrade the firmware」);
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print(「Attempting to connect to Network named: 「);
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
server.begin(); // start the tcp server on port 5000
printWifiStatus(); // you’re connected now, so print out the status
}
char buffer[256];
void loop() {
WiFiClient client = server.available();
while (client.connected()) {
memset(buffer, 0, 256);
int n = client.read((uint8_t*)(&buffer[0]), sizeof(buffer));
if (n > 0) {
for (int i=0; i<n; i++) {
Serial.print(buffer[i]);
}
n = client.write(buffer, n);
if (n <= 0) break;
}
}
client.stop();
}
void printWifiStatus() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.print(rssi);
Serial.println(」 dBm」);
}
WiFiServer::available
WiFiServer::begin
WiFiServer::write
Class WiFiSSLClient
WiFiSSLClient Class
Members
Public Constructors |
|
---|---|
WiFiSSLClient::WiFiSSLClient |
Constructs a WiFiSSLClient instance that always connects in SSL to the specified IP address and port |
Public Methods |
|
WiFiSSLClient::connect |
Connect to the IP address and port |
WiFiSSLClient::write |
Write a single byte into the packet |
WiFiSSLClient::available |
Number of bytes remaining in the current packet |
WiFiSSLClient::read |
Read a single byte from the current packet |
WiFiSSLClient:: peek |
Return the next byte from the current packet without moving on to the next byte |
WiFiSSLClient:: flush |
Finish reading the current packet |
WiFiSSLClient::stop |
Stop SSL client connection |
WiFiSSLClient::connected |
Check if SSL client is connected, return 1 if connected, 0 if not |
WiFiSSLClient:: setRootCA |
Set Root CA for authentication |
WiFiSSLClient:: setClientCertificate |
Set certificate of the client |
WiFiSSLClient::setRecvTimeout |
Set receiving timeout |
WiFiSSLClient::setPreSharedKey |
Set the pre shared key (PSK) to use for authentication |
WiFiSSLClient::WiFiSSLClient
#include
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「secretPassword」;// your network password (use for WPA, or WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
char server[] = 「www.google.com」; // name address for Google (using DNS)
//unsigned char test_client_key[] = 「」; //For the usage of verifying client
//unsigned char test_client_cert[] = 「」; //For the usage of verifying client
//unsigned char test_ca_cert[] = 「」; //For the usage of verifying server
WiFiSSLClient client;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to SSID: 「);
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid,pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(「Connected to wifi」);
printWifiStatus();
Serial.println(」nStarting connection to server…」);
// if you get a connection, report back via serial:
if (client.connect(server, 443)) { //client.connect(server, 443, test_ca_cert, test_client_cert, test_client_key)
Serial.println(「connected to server」);
// Make a HTTP request:
client.println(「GET /search?q=realtek HTTP/1.0」);
client.println(「Host: www.google.com」);
client.println(「Connection: close」);
client.println();
}
else
Serial.println(「connected to server failed」);
}
void loop() {
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// if the server’s disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println(「disconnecting from server.」);
client.stop();
// do nothing forevermore:
while (true);
}
}
void printWifiStatus() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print(「MAC address: 「);
Serial.print(mac[0], HEX);
Serial.print(「:」);
Serial.print(mac[1], HEX);
Serial.print(「:」);
Serial.print(mac[2], HEX);
Serial.print(「:」);
Serial.print(mac[3], HEX);
Serial.print(「:」);
Serial.print(mac[4], HEX);
Serial.print(「:」);
Serial.println(mac[5], HEX);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.print(rssi);
Serial.println(」 dBm」);
}
WiFiSSLClient::connect
WiFiSSLClient::write
WiFiSSLClient::available
WiFiSSLClient::read
WiFiSSLClient::peek
WiFiSSLClient::flush
WiFiSSLClient::stop
WiFiSSLClient::connected
WiFiSSLClient::setRootCA
WiFiSSLClient::setClientCertificate
WiFiSSLClient::setRecvTimeout
WiFiSSLClient::setPreSharedKey
Class WiFiUdp
WiFiUDP Class
Members
Public Constructors |
|
---|---|
WiFiUDP::WiFiUDP |
Constructs a WiFiUDP instance of the WiFi UDP class that can send and receive UDP messages |
Public Methods |
|
WiFiUDP:: begin |
initialize, start listening on the specified port. Returns 1 if successful, 0 if there are no sockets available to use |
WiFiUDP:: stop |
Finish with the UDP socket |
WiFiUDP:: beginPacket |
Start building up a packet to send to the remote host-specific in IP and port |
WiFiUDP:: endPacket |
Finish off this packet and send it |
WiFiUDP:: write |
Write a single byte into the packet |
WiFiUDP:: writeImmediately |
Send packet immediately from the buffer |
WiFiUDP:: parsePacket |
Start processing the next available incoming packet |
WiFiUDP::available |
Number of bytes remaining in the current packet |
WiFiUDP::read |
Read a single byte from the current packet |
WiFiUDP:: peek |
Return the next byte from the current packet without moving on to the next byte |
WiFiUDP:: flush |
Finish reading the current packet |
WiFiUDP:: remoteIP |
Return the IP address of the host who sent the current incoming packet |
WiFiUDP:: remotePort |
Return the port of the host who sent the current incoming packet |
WiFiUDP:: setRecvTimeout |
Set receiving timeout |
WiFiUDP::WiFiUDP
#include <WiFi.h>
#include <WiFiUdp.h>
int status = WL_IDLE_STATUS;
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「secretPassword」; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
unsigned int localPort = 2390; // local port to listen on
char packetBuffer[255]; //buffer to hold incoming packet
char ReplyBuffer[] = 「acknowledged」; // a string to send back
WiFiUDP Udp;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to SSID: 「);
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid,pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(「Connected to wifi」);
printWifiStatus();
Serial.println(」nStarting connection to server…」);
// if you get a connection, report back via serial:
Udp.begin(localPort);
}
void loop() {
// if there’s data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize) {
Serial.print(「Received packet of size 「);
Serial.println(packetSize);
Serial.print(「From 「);
IPAddress remoteIp = Udp.remoteIP();
Serial.print(remoteIp);
Serial.print(」, port 「);
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
int len = Udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
}
Serial.println(「Contents:」);
Serial.println(packetBuffer);
// send a reply, to the IP address and port that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
}
}
void printWifiStatus() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.print(rssi);
Serial.println(」 dBm」);
}
WiFiUDP::begin
WiFiUDP::stop
WiFiUDP::beginPacket
WiFiUDP::endPacket
WiFiUDP::write
WiFiUDP::writeImmediately
WiFiUDP::parsePacket
WiFiUDP::available
WiFiUDP::read
WiFiUDP::peek
WiFiUDP::flush
WiFiUDP::remoteIP
WiFiUDP::remotePort
WiFiUDP::setRecvTimeout
Readme
WiFi.cpp
WiFi.h
WiFiServer.cpp
WiFiServer.h
WiFiUdp.cpp
WiFiUdp.h
Wire
Class TwoWire
TwoWire Class
Members
Public Constructors |
|
---|---|
TwoWire::TwoWire |
Constructs a TwoWire object |
Public Methods |
|
TwoWire::begin |
Initialize I2C master/slave |
TwoWire::setClock |
Set I2C frequency |
TwoWire::beginTransmission |
Begin I2C transmission |
TwoWire::endTransmission |
End I2C transmission |
TwoWire::requestFrom |
Set I2C requestFrom |
TwoWire::write |
Write data to I2C |
TwoWire::available |
Check if I2C is available |
TwoWire::read |
Read data from I2C |
TwoWire::peek |
Read peek from I2C |
TwoWire::flush |
Do nothing, use, and transmission(..) to force data transfer |
TwoWire::onReceive |
Callback function when I2C on receive |
TwoWire::onRequest |
Callback function when I2C on request |
TwoWire::TwoWire
#include <Wire.h>
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
}
byte x = 0;
void loop() {
Wire.beginTransmission(8); // transmit to device #8
Wire.write(「x is 「); // sends five bytes
Wire.write(x); // sends one byte
Wire.endTransmission(); // stop transmitting
x++;
delay(500);
}
Example: MasterReader
#include <Wire.h>
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output
}
void loop() {
Wire.requestFrom(8, 6); // request 6 bytes from slave device #8
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);
}
This example demonstrates the use of the wire library reads data from an I2C/TWI slave device.
TwoWire::begin
TwoWire::setClock
TwoWire::beginTransmission
TwoWire::endTransmission
WARNING: Nothing in the library keeps track of whether the bus tenure has been properly ended with a STOP. It is very possible to leave the bus in a hung state if no call to endTransmission(true) is made. Some I2C devices will behave oddly if they do not see a STOP.
If the input parameter is void, this provides backward compatibility with the original definition, and expected behavior, of endTransmission.
TwoWire::requestFrom
TwoWire::write
TwoWire::available
TwoWire::read
TwoWire::peek
TwoWire::flush
TwoWire::onReceive
TwoWire::onRequest
Wire_Readme
The Ameba LCD related api and example are works based on “New LiquidCrystal library” (https://bitbucket.org/fmalpartida/new-liquidcrystal/).
These include,
These files inherit the licence of “New LiquidCrystal Library” which are under a Creative Commons Attribution-ShareAlike 3.0 Unported License. CC BY-SA 3.0.
Resources
Links
支援
常見問題
如何購買 Ameba RTL8722DM Board?
請參考 購買連結。
RTL8722CSM/RTL8722DM 支持哪些藍牙標準?
兩者皆支援 BLE 5.0。 Classic Bluetooth (BR/EDR) 則不支援。
支持哪些BLE設備?
RTL8722CSM/RTL8722DM 可當作 BLE Central 或 BLE Peripheral 設備。
RTL8722CSM /RTL8722DM上的所有接腳都可用嗎?
不,標有“NC”的未連接到任何接腳,因此無法使用。
RTL8722CSM/RTL8722DM 有支援 XIP (execute in place)嗎?
有支援。
RTL8722CSM 有支援 5G WiFi 嗎?
不,只有 RTL8722DM 支援雙頻 2.4G + 5G WiFi。 RTL8722CSM 只有支援單頻 2.4G WiFi。
如何進入下載模式?
按住UART DOWNLOAD按鈕,然後按下RESET按鈕並放開UART DOWNLOAD和RESET按鈕。
故障排除
無法找到藍牙裝置RTL8722CSM/RTL8722DM
請確保天線連接正確。 檢查您的程式碼有確認正確的藍牙配置。
程式碼操作不如預期
嘗試使用``printf()`` 和
Serial.print()
語法除錯。 如果問題仍然存在,您可以在論壇尋求幫助
連接到RTL8722CSM / RTL8722DM UART後,為什麼串行終端上沒有輸出?
RTL8722CSM / RTL8722DM 默認配置為115200波特率,請檢查串行終端是否配置為115200。
程序無法下載到RTL8722CSM / RTL8722DM中
- 請按照以下步驟正確下載。
請進入下載模式。 進入下載模式時,開發版綠色LED指示燈將閃爍。
下載過程中,開發版紅色LED指示燈將閃爍。
下載成功後,Arduino IDE會出現通知。
WiFi有時信號較弱
RTL8722CSM / RTL8722DM 的預設天線使用I-Pex連接器。 請更換/連接I-Pex連接器天線。
為什麼開發版無法上電?
請確認已連接電阻R43旁的連接器J38。 該連接器用於將電源鏈接到IC。
遇到開發板連接到電腦的驅動程式問題?
請參考下列USB 驅動程式 https://ftdichip.com/drivers /。
BW16 (by Ai-Thinker)
Welcome to BW16 (by Ai-Thinker) online documentation.
Getting Started
Ameba ARDUINO: Getting Started with BW16
Required Environment
RTL8720DN Dual-Band Wi-Fi board currently supports Windows XP/7/8/10 32-bits and 64-bits operating systems. In this documentation, please use Arduino IDE with version 1.8.15 or later.
Introduction to BW16
Realtek RTL8720DN is a Wi-Fi and Bluetooth IC that supports 2.4GHz and 5GHz dual bands for Wi-Fi communication, and Bluetooth Low Energy (BLE) 5.0. BW16 is a module manufactured by B&T, this module is a highly integrated Wi-Fi and Bluetooth module with the RTL8720DN as the main SoC (System on Chip), it can be regarded as an SoC for the Wi-Fi and Bluetooth application with typical SBCs.
RTL8720DN (BW16) has a smaller size than AmebaD and AmebaD MINI as shown in the above figure. It uses Micro USB to supply power, which is common in many smart devices. Please refer to the following figure and table for the pin diagram and function of RTL8720DN (BW16).
# |
PIN name |
GPIO |
ADC |
PWM |
UART |
SPI |
I2C |
---|---|---|---|---|---|---|---|
D0(PA7) |
GPIOA_7 |
✓ |
UART_LOG_TX |
||||
D1(PA8) |
GPIOA_8 |
✓ |
UART_LOG_RX |
||||
D2(PA27) |
GPIOA_27 |
✓ |
|||||
D3(PA30) |
GPIOA_30 |
✓ |
|||||
D4(PB1) |
GPIOB_1 |
✓ |
Serial_TX |
||||
D5(PB2) |
GPIOB_2 |
✓ |
Serial_RX |
||||
D6(PB3) |
GPIOB_3 |
✓ |
A2 |
||||
D7(PA25) |
GPIOA_25 |
✓ |
I2C0_CLK |
||||
D8(PA26) |
GPIOA_26 |
✓ |
✓ |
I2C0_SDA |
|||
D9(PA15) |
GPIOA_15 |
✓ |
SPI_CS |
||||
D10(PA14) |
GPIOA_14 |
✓ |
SPI_CLK |
||||
D11(PA13) |
GPIOA_13 |
✓ |
✓ |
SPI_MISO |
|||
D12(PA12) |
GPIOA_12 |
✓ |
✓ |
SPI_MOSI |
Setting up Development Environment
Step 1. Installing the Driver
Step 2. Set up Arduino IDE
From version 1.6.5, Arduino IDE supports third-party hardware. TTherefore, we can use Arduino IDE to develop applications on RTL8720DN (BW16), and the basic examples of Arduino can run on RTL8720DN (BW16) too. Refer to the Basic Examples.
Arduino IDE can be downloaded in the Arduino website.
When the installation is finished, open Arduino IDE. To set up RTL8722DM correctly in Arduino IDE, go to “File” -> “Preferences”.
And paste the following URL into “Additional Boards Manager URLs” field:
https://github.com/ambiot/ambd_arduino/raw/master/Arduino_package/package_realtek.com_amebad_index.json
RTL8720DN (BW16) will be supported from v3.0.8 officially.
Next, go to “Tools” -> “Board” -> “Boards Manager”:
The “Boards Manager” requires about 10~20 seconds to refresh all hardware files (if the network is in bad condition, it may take longer). Every time the new hardware is connected, we need to reopen the Board Manager. So, we close the “Boards Manager”, and then open it again. Find “Realtek AmebaD Boards (32-bits ARM Cortex-M4 @200MHz)” in the list, click “Install”, then the Arduino IDE starts to download required files for RTL8722DM.
“AmebaD_Arduino_patch1_SDK”, please select at least 1 of the SDKs. There are 5 latest released SDK options.
“AmebaD_Arduino_patch2_Tools”, please select according to your operation system. There are Windows, Linux and MacOS.
“AmebaD_Arduino_Source_Code”, this section is optional download only wants to refer the latest source code.
Download the files selected, then unzip (patch1 and patch2 are compulsory). There are “Install.doc”/“Install.pdf” for you to refer installation steps. According to your system, please run the installation tool in the “Offline_SDK_installation_tool” folder.
After the installation tool running successfully, you may open Arduino IDE and proceed to “Tools” -> “Board“ -> “Boards Manager…”. Try to find “Realtek AmebaD Boards (32-bits ARM Cortex-M4 @200MHz)”` in the list, click “Install”, then the Arduino IDE starts to download required files for AmebaD.
Finally, we select RTL8722DM as current connected board in “Tools” -> “Board” -> “Ameba ARM (32-bits) Boards” ->” RTL8722DM”:
How to upload firmware into BW16
Uploading Solution
Method 1: Use AmebaD Image Tool to erase flash
In the “Chip Select” option, choose “AmebaD(8721D)” which is also suitable for RTL8720DN chip.
Select correct COM Port that you are using.
Set the Baudrate to “115200”.
Then key in the Flash Erase starting position from Memory Address of 0x0800 0000.
The size to be 2048 KB.
Set the module to “Download mode” first, then click the “Erase” button.
Optional Uploading Solution
Ai-Thinker is providing a guide for OTA firmware upload in Section 6.1 of B&T “RTL8720D AT Command User Manual” of which can be retrieved from this link here.
Try the First Example
Step 1. Compile & Upload
LED_BUILTIN
is a green onboard LED.
Change LED_BUILTIN
to LED_B
or LED_R
for different colors such as blue and red.
Here we use LED_B
for demonstration purpose.Step 2.Run the Blink example
References
Introduction of RTL8720DN on Instructable: https://www.instructables.com/RTL8720DN/
Load Arduino image into BW16: How to load BW16 program with Arduino – #13
RTL8720DN (BW16) IMG2 SIGN Invalid Solution: RTL8720DN(BW16) IMG2 SIGN Invalid Solution
FTDI Driver Download from here: https://ftdichip.com/wp-content/uploads/2021/02/CDM21228_Setup.zip
(End)
備註
If you face any issue, please refer to the FAQ and Trouble shooting sections on 支援 page.
Download
Peripherals & Examples
Basic Examples
Ameba ARDUINO: [RTL8722CSM][RTL8722DM] Supported ARDUINO built-in example list
There are many built-in examples in Arduino. In the table below, we list all examples that are compatible with Ameba.
Category |
Name |
Comment |
---|---|---|
01.Basics |
AnalogReadSerial |
Connect potentiometer to 3.3V |
BareMinimum |
||
Blink |
Connect LED to pin 8 |
|
DigitalReadSerial |
||
Fade |
||
ReadAnalogVoltage |
ADC can read a maximum of 3.3V. |
|
02.Digital |
BlinkWithoutDelay |
Connect LED to pin 8 |
Button |
Connect LED to pin 13 |
|
Debounce |
Connect LED to pin 13 |
|
DigitalInputPullup |
Connect LED to pin 13 |
|
StateChangeDetection |
Connect LED to pin 13 |
|
toneKeyboard |
||
toneMelody |
||
toneMultiple |
||
tonePitchFollower |
||
03.Analog |
AnalogInOutSerial |
|
AnalogInput |
Connect LED to pin 13 |
|
Analog Write Mega |
||
Calibration |
Connect another LED to pin 13 |
|
Fading |
||
Smoothing |
||
04.Communication |
ASCIITable |
|
Dimmer |
Use serial baud rate 115200 |
|
Graph |
Use serial baud rate 115200, Connect potentiometer to 3.3V |
|
Midi |
Please use Serial1 and pin 26, or use Serial2 and pin 17 |
|
MultiSerial |
||
PhysicalPixel |
Use serial baud rate 115200 |
|
ReadASCIIString |
||
SerialCallResponse |
Use serial baud rate 115200 |
|
Serial CallResponseASCII |
Use serial baud rate 115200 |
|
SerialEvent |
||
SerialPassthrough |
||
VirtualColorMixer |
Use serial baud rate 115200 |
|
05.Control |
Arrays |
Use pins 1, 2, 3, 4, 5, 6 |
ForLoopIteration |
Use pins 1, 2, 3, 4, 5, 6 |
|
IfStatementConditional |
||
switchCase |
||
switchCase2 |
||
While StatementConditional |
Connect another LED to pin 13 |
|
06.Display |
barGraph |
Use another pin to replace pin 7 |
RowColumnScanning |
||
07.Strings |
CharacterAnalysis |
|
String AdditionOperator |
||
StringAppendOperator |
||
StringCaseChanges |
||
StringCharacters |
||
String ComparisonOperators |
||
StringIndexOf |
||
StringLength |
||
StringLengthTrim |
||
StringReplace |
||
String StartsWithEndsWith |
||
StringSubstring |
||
StringToInt |
Network Examples
Connect to WiFi
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Procedure
There three common encryption type in WiFi connection. The first one is “OPEN”, which means there is no password needed to connect to this network. The second type of encryption is WPA, which requires the correct password to access. The third type is WEP, which requires a hexadecimal password and a keyindex.
In the following, we will give a brief introduction on how to establish WiFi connection with these three types of encryption on Ameba.
First, make sure the correct Ameba development board is selected in “Tools” -> “Board”.
Open (WiFi connection without password)
Open the “ConnectNoEncryption” example in
“File” -> “Examples” -> “AmebaWiFi” -> “ConnectWithWiFi” -> “ConnectNoEncryption”
![]()
In the sample code, modify “ssid” to be the same as the WiFi SSID to be connected to.
Next, upload the sample code, and press the reset button on Ameba. Then you will see a message “You’re connected to the networkSSID: XXXXX”, and the information of this WiFi connection is printed in the serial monitor every 10 seconds.
![]()
WiFi connection with WPA encryption
Open the “ConnectWithWPA” example in
“File” -> “Examples” -> “AmebaWiFi” -> “ConnectWithWiFi” -> “ConnectWithWPA”
In the sample code, modify “ssid” to the WiFi SSID to be connected to and “pass” to the network password.
Next, upload the sample code, and press the reset button on Ameba. Then you will see a message “You’re connected to the networkSSID: XXXXX”, and the information of this WiFi connection is printed in the serial monitor every 10 seconds.
WiFi connection with WEP encryption
Open the “ConnectWithWEP” example in
“File” -> “Examples” -> “AmebaWiFi” -> “ConnectWithWiFi” -> “ConnectWithWEP”
In the sample code, modify “ssid” to the SSID to be connected, “key” to the hexadecimal password, “keyIndex” to your key index number.
Next, upload the sample code, and press the reset button on Ameba. Then you will see a message “You’re connected to the networkSSID: XXXXX”, and the information of this WiFi connection is printed in the IDE every 10 seconds.
Code Reference
WiFi.SSID()
to get SSID of the current connected network.WiFi.RSSI()
to get the signal strength of the connection.WiFi.encryptionType()
to get the encryption type of the WiFi
connection.WiFi.BSSID()
to get the MAC address of the router you are
connected to.WiFi.macAddress()
to get the MAC address of Ameba.WiFi.localIP()
to get the IP address of Ameba.WiFi.subnetMask()
to get the subnet mask.WiFi.gatewayIP()
to get the WiFi shield’s gateway IP address.Comparison with Arduino
#include
to
use SPI to communicate with WiFi module.#include
is not needed.Use Ameba as Server to communicate with Client
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Laptop(Make sure it is connected to the same network domain as Ameba, and tcp tools are installed.)
Example
In this example, we first connect Ameba to WiFi, then we use Ameba as server to communicate with client.
First, we make sure the correct Ameba development board is set in “Tools” -> “Board”
Then, open the Simple WiFi Server example in “File” -> “Examples” ->
“AmebaWiFi” -> “SimpleServerWiFi”
In the sample code, modify the highlighted parameters and enter the ssid and password for your WiFi connection.
Next, upload the code, then press the reset button on Ameba. At this moment, you will see the connection information is displayed in the console.
Next, we use the socket tool in the laptop to be the client and connect to the IP address of the Ameba board shown in the connection information at port 5000. (Note: The socket tool we used in this example is “sokit”)
Click on the “Client” tab to choose the client mode, specify the IP and port of the server, then click “TCP Connect”.
If the connection is established successfully, the server shows a message: “A client connected to this Server”, and the IP and port of the connected client.
In this example, when the client and server are connected and the client sends a string to Ameba server, the Ameba server returns the identical string back to the client.
The string sent to server is returned and showed at the client side.
Code Reference
WiFi.begin()
to establish WiFi connection;WiFi.SSID()
to get SSID of the current connected network.WiFi.RSSI()
to get the signal strength of the connection.WiFi.localIP()
to get the Ameba WiFi shield’s IP address.Server(port)
to create a server that listens on the specified
port.server.begin()
to tell the server to begin listening for incoming
connections.server.available()
to get a client that is connected to the server
and has data available for reading.client.read()
to read the next byte received from the server.client.write()
to write data to the server.client.stop()
to disconnect from the server.Use Ameba to retrieve HTTP websites from the internet
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaHttp” -> “SimpleHttpExample”
Code Reference
WiFi.begin()
to establish WiFi connection:WiFi.SSID()
to get SSID of the current connected network.WiFi.RSSI()
to get the signal strength of the connection.WiFi.localIP()
to get the IP address of Ameba.Use http.get()
to send a GET request to the website.
Use Ameba to retrieve information from the Internet
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaWiFi” -> “WiFiWebClient”
In the sample code, modify the highlighted snippet and enter the required information (ssid, password, key index) required to connect to your WiFi network.
Upload the code and press the reset button on Ameba. Then you can see the information retrieved from Google is shown in the Arduino serial monitor.
Code Reference
WiFi.SSID()
to get
SSID of the current connected network.WiFi.RSSI()
to get the signal strength of the connection.WiFi.localIP()
to get the IP address of Ameba.WiFiClient()
to create a client.client.connect()
to connect to the IP address and port specified.client.println()
to print data followed by a carriage return and
newline.client.available()
to return the number of bytes available for
reading.client.read()
to read the next byte received from the server the
client is connected to.client.stop()
to disconnect from the server the client is
connected to.Use Ameba as Server to control LED
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Breadboard x 1
LED x 1
1KΩ Resistor x 1
Procedure
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
“File” -> “Examples” -> “AmebaWiFi” -> “SimpleWebServerWiFi”
Upload the code and press the reset button on Ameba. When the connection is established, you will see the message:
“To see this page in action, open a browser to http://xxx.xxx.xxx.xxx”
in the Arduino IDE as shown in the figure:
Next, open the browser of a computer or a cell phone under the same WiFi domain, enter the address in the message.
In the webpage, you can turn on/off the LED.
Code Reference
WiFi.begin()
to establish WiFi connection.WiFi.SSID()
to get SSID of the current connected network.WiFi.localIP()
to get the IP address of Ameba.WiFiServer server()
to create a server that listens on the
specified port.server.begin()
to tell the server to begin listening for incoming
connections.server.available()
to get a client that is connected to the server
and has data available for reading.client.connected()
to get whether or not the client is connected.client.println()
to print data followed by a carriage return and
newline.client.print()
to print data to the server that a client is
connected to.client.available()
to return the number of bytes available for
reading.client.read()
to read the next byte received from the server the
client is connected to.client.stop()
to disconnect from the server the client is
connected to.Use Ameba as Server to send Ameba status
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaWiFi” -> “WiFiWebServer”
Code Reference
WiFi.begin()
to establish WiFi connection.WiFi.SSID()
to get SSID of the current connected network.WiFi.RSSI()
to get the signal strength of the connection.WiFi.localIP()
to get the IP address of Ameba.WiFiServer server()
to create a server that listens on the
specified port.server.begin()
to tell the server to begin listening for incoming
connections.server.available()
to get a client that is connected to the server
and has data available for reading.client.connected()
to check whether or not the client is connected.client.println()
to print data followed by a carriage return and
newline.client.print()
to print data to the server that a client is
connected to.client.available()
to return the number of bytes available for
reading.client.read()
to read the next byte received from the server the
client is connected to.client.stop()
to disconnect from the server the client is
connected to.Use Ameba as UDP server
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaWiFi”
-> “WiFiUdpSendReceiveString”
Compile the code and upload it to Ameba. After pressing the Reset button, Ameba connects to WiFi and starts the UDP server with port 2390. After the UDP server starts service, Ameba prints the “Starting connection to server” message and waits for client connection.
Code Reference
begin()
to open an UDP port on Ameba.parsePacket()
to wait for data from client.remoteIP()
and remotePort()
to
get the IP and port of the client.read()
to read the data sent by client.beginPacket()
, write()
, end()
.Retrieve Universal Time (UTC) By Ameba
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaWiFi” -> “WiFiUdpNtpClient”
Use MQTT To Upload And Listen To Data
Intro to MQTT
MQTT (Message Queuing Telemetry Transport) is a protocol proposed by IBM and Eurotech. The introduction in MQTT Official Website: MQTT is a machine-to-machine (M2M)/”Internet of Things” connectivity protocol. It was designed as an extremely lightweight publish/subscribe messaging transport. We can say MQTT is a protocol designed for IoT. MQTT is based on TCP/IP and transmits/receives data via publish/subscribe. Please refer to the figure below:
In the operation of MQTT, there are several roles:
Publisher: Usually publishers are the devices equipped with sensors (ex. Ameba). Publishers uploads the data of the sensors to MQTT-Broker, which serves as a database with MQTT service.
Subscriber: Subscribers are referred to the devices which receive and observe messages, such as a laptop or a mobile phone.
Topic: Topic is used to categorized the messages, for example the topic of a message can be “PM2.5” or “Temperature”. Subscribers can choose messages of which topics they want to receive.
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaMQTTClient” ->
“MQTT_Basic”
The “mqttServer” refers to the MQTT-Broker, we use the free MQTT sandbox “test.mosquitto.org” for testing.
“clientId” is an identifier for MQTT-Broker to identify the connected device.
“publishTopic” is the topic of the published message, we use “outTopic” in the example. The devices subscribe to “outTopic” will receive the message.
“publishPayload” is the content to be published.
“subscribeTopic” is to tell MQTT-broker which topic we want to subscribe to.
Install and open the MQTTLens, click “+” next to “Connection” on the left, and fill in the required information
Connection Name: Used to identify the connection, you can choose a name you like.
Hostname: The MQTT-Broker server, here we use “iot.eclipse.org”
Client ID: We use the default randomly generated ID.
Use Amazon AWS IoT Shadow Service
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
REST API endpoint: In the value “https://a1a7oo4baosgyy.iot.us-east-1.amazonaws.com/things/ameba/shadow”, the part “a1a7oo4baosgyy.iot.us-east-1.amazonaws.com” is the MQTT Broker server address.
MQTT topic:The value “$aws/things/ameba/shadow/update” represents the MQTT topic we will use in the AWS IoT Shadow service (if we use MQTT only, without AWS IoT Shadow service, then we can specify other topic name). It is recommended to use “$aws/things/ameba/shadow/update” here.
Ameba setting
“File” -> “Examples” -> “AmebaMQTTClient” -> “Amazon_AWS_IoT_Basic”
Compile and run
Alternatives
Ameba can also retrieve the current LED status variable from the AWS shadow. This is done by sending a message to the “shadow/get” topic. Refer to the Amazon_AWS_IoT_with_ACK example code for more information.
Code Reference
pinMode(led_pin, OUTPUT);
digitalWrite(led_pin, led_state);
WiFiSSLClient wifiClient;
wifiClient.setRootCA((unsigned char*)rootCABuff);
wifiClient.setClientCertificate((unsigned char*)certificateBuff,(unsigned char*)privateKeyBuff);
client.setServer(mqttServer, 8883);
client.setCallback(callback);
loop()
, call reconnect()
function and try to connect to MQTT Broker
server and do the certificate verification.while (!client.connected()) {
for (int i=0; i<5; i++) {
client.subscribe(subscribeTopic[i]);
}
sprintf(publishPayload,
"{\"state\":{\"reported\":{\"led\":%d}},\"clientToken\":\"%s\"}",
led_state, clientId);
client.publish(publishTopic, publishPayload);
if (strstr(topic, "/shadow/get/accepted") != NULL) {
If there is, the message is from the control side. If the attribute state in the message is different from current state, publish the new state.
updateLedState(desired_led_state);
Use MQTT over TLS
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” ->
“AmebaMQTTClient” -> “MQTT_TLS”
Upload PM2.5 Data to LASS System
Intro to LASS
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
PlanTower PMS3003 or PMS5003 x1
Example
In this example, we use applications mentioned at our website, including:
MQTT: a MQTT-Broker to connect to LASS. The Client is “FT1_0XXXX”, the XXXX are the four last digits of Ameba’s Wi-Fi MAC, and the outTopic is “LASS/Test/Pm25Ameba/clientID“, where clientID is the actual Ameba’s MQTT client ID.
NTP: uploaded data must have time notation
PM2.5: uploaded data includes PM2.5 information
“File” -> “Examples” -> “AmebaMQTTClient” ->
“lass_basic”
gps_lat
and gps_lon
.Ameba AP Mode
In AP mode, Ameba can accept at most 3 station connections, and can be set to open mode or WPA2 mode.
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” -> “AmebaWiFi” ->
“WiFiAPMode”
In the highlighted code snippet, fill in your SSID, PASSWORD and CHANNEL.
The code highlighted in green is the API we used to turn on the AP mode in security mode.
If you want to turn on the AP mode in open mode, please modify the code to
status = WiFi.apbegin(ssid, channel);
Then upload the sample code and press reset, and you can see related information shown in serial monitor.
In the figure below, we show the messages shown in serial monitor when two stations connect to Ameba AP in open mode:
In the figure below, we show the messages shown in serial monitor when a station connects to Ameba AP in security mode:
Use mDNS To Let Arduino IDE Find Ameba
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
mDNS (Multicast DNS) is a protocol used in the local area network. It delivers the network information like IP address and provided services to others. mDNS is based on the UDP protocol, and it sends packets to 224.0.0.251 with port 5353 under IPv4 address. The naming style for the service follows the format: {Instance Name}.{Protocol Name}.{Domain}
Instance Name: used to identify the name of the service
Protocol Name: Divided into two parts, the front end is in regard to the name of the service, and it adds baseline as a prefix. The rear end is in regard to the transport protocol name it used, and it also adds baseline as a prefix
Domain: Local area network in normal cases
“File” -> “Examples” -> “AmebaMDNS” -> “mdns_on_arduino_ide”
Next, go to (“Tools” ->
“Port”), and you can find out at least one Serial Port. This port is
simulated by Ameba board via USB. Choose this port and upload the
compiled code to Ameba.After uploading the code, press the reset
button on Ameba and waiting for Ameba to connect with AP and activate
the mDNS service after a while. You can see the Log at the bottom of the
Serial Monitor.
Then you can find out the added item “Network
Ports” “MyAmeba at 192.168.1.167 (Ameba RTL8722DM/RTL8722CSM)”,
“MyAmeba” is the device name we set up, and “IP” is the IP address that
AP assigned to Ameba, the IP address should be the same with the IP
shown in the Serial Monitor. Last, “Ameba RTL8722DM/RTL8722CSM” is the
type name of the board, and it means that Ameba can let Arduino IDE
identify the mDNS service successfully.(We still can not use the
Internet to upload the code, and we will explain this part in the OTA
example.)
Does your computer in the same local area network with the Ameba?
Restart the Arduino IDE, and it will find the mDNS service again
Check the Log in Serial Monitor if the Ameba connects to the AP and activate mDNS service successfully
Code Reference
The program set up the mDNS service in the beginning, the first parameter is Instance Name, and it is changeable in this example. The second parameter is the protocol that the service used, and it would be “_arduino._tcp” for Arduino IDE. The third parameter is Domain, and it would be “local” in common. The fourth parameter is the port number for the service, it is 5000 here and we doesn’t use it in the example.
MDNSService service("MyAmeba", "_arduino._tcp", "local", 5000);
After connected to the network, we set up some text fields for the service. For the following example, “board” is the name of the field, “ameba_rtl8721d” is the value of the field. “board” is used to let Arduino IDE check installed SDK to see if it exists known device or not. We will use the name of the device if there is known device, users can change “ameba_rtl8721d” to “yun” or other names to find out what’s the difference if interested.
service.addTxtRecord("board", strlen("ameba_rtl8721d"),"ameba_rtl8721d");
Then we add three text fields “auth_upload”, “tcp_check”, and “ssh_upload”, this example does not activate these services.
service.addTxtRecord("auth_upload", strlen("no"), "no");
service.addTxtRecord("tcp_check", strlen("no"), "no");
service.addTxtRecord("ssh_upload", strlen("no"), "no");
Next we activate MDNS
MDNS.begin();
and register to the mDNS service.
MDNS.registerService(service);
Use Firebase To Push Messaging Services
Preparation
Ameba x 1
Android Studio
Smart phone with Google Play Service x 1
Example
In the era of the popularity of smart phones, people often receive reminders from specific apps. In this example, we will teach how to use Google Firebase to send messages from the Ameba Client to mobile phones.
First, we use Firebase Cloud Messaging (FCM) as a cross-platform messaging solution that lets you deliver messages for free and reliably.
With FCM, you can notify your client application (App) to sync emails or other data. You can send a message to drive user engagement. For instant messaging content, a message can transfer up to 4KB of payload to the client application.

The FCM implementation includes two main parts for sending and receiving:
You can use Admin SDK or HTTP&XMPP API to send messages.To test or send marketing or engagement messages with powerful built-in targeting and analytics, you can also useNotifications composer
We know that Ameba can send messages to specific apps as long as it implements the http client function.
First of all, we must first set up an environment for developing Android apps. Please download Android Studio first on Android official website.
https://developer.android.com/studio/install
Then we can use the Android example provided by Firebase to download Firebase Quickstart Samples.
https://github.com/firebase/quickstart-android
Open Android Studio and click on Import Project, select the messaging project in Firebase Quickstart Samples. Since we won’t use other functions, we can only choose the messaging project.
Android Studio will need to install the SDK and Google repository for the first time to start the messaging project. You can refer to the following page for update.
https://developer.android.com/studio/intro/update
Wait until the required components for compiling the app are installed, you can open the messaging project, and Android Studio comes with the Firebase registration function.

As shown above, open the toolbar and click Tools->Select Firebase.

Open Firebase Assisant in the right pane, then see Cloud Messaging, select Set up Firebase Cloud Messaging to start the registration process.

Click Connect to Firebase

Then bring out the page, and click on Firebase on the left and log in to the Gmail account. Once you log in, you will be taken to the Firebase homepage.

Let’s keep the homepage first, we need to go to the Firebase Console and go back to Android Studio.

We can see that when the webpage is successfully logged in, Android Studio also brings up the login information dialog box, click connect to Firebase


As shown above, the messaging app is installed and executed successfully on the phone. Click LOG TOKEN at this time.

There will be a Token ID, which is the Access Token required to send the message, representing the ID of the FCM service APP installed on a particular phone. This ID is unique and will be reassigned when the app is removed and re-installed. It means that the message can be sent to a specific phone. The FCM service can also push messages to a NEWS (Topic). This section can be found in Firebase topic-messaging:
https://firebase.google.com/docs/cloud-messaging/android/topic-messaging
Therefore, we need to save this Access Token, return to Android Studio as shown below, select Debug at the log level of the Logcat. When you press the LOG TOKEN button on the App, Logcat will print out the Access Token ID. We will save the code after the InstanceID Token: in the Log message.

Then we have to go back to the page that was brought when we first logged into Firebase.

Click in the upper right corner to go to the console

At this point, You can see that Android Studio has just built the messaging project for us in the operation.

Click to enter the messaging project with settings page, as shown above.

Select Set up

“File” -> “Examples” -> “AmebaWiFi” -> “Firebase.ino”

As shown above, ACCESS_TOKEN and SERVER_KEY are defined in the reverse white part, that is, the ACCESS token ID that we just saved from the APP and the Server Key saved in the Firebase console page. We fill in the two sets of IDs, compile and upload them to Ameba. Press the Reset button and open the terminal.

Connect to FCM Server after connecting to AP

After showing Connect to Server successful, it means that the FCM connection is successful and the message will be sent. During the process, HTTP/1.1 200 OK will be received to indicate that the message is successfully pushed. At this time, the mobile phone screen is opened and the App receives the message from Ameba.

Code Reference
https://firebase.google.com/docs/cloud-messaging/send-message
The main payload format in the program is as follows. The user can freely change the Title and Body of the message. Body represents the content of the message.
char const* payload = "{" \
"\"to\": \"" ACCESS_TOKEN "\"," \
"\"notification\": {" \
"\"body\": \"Hello World!\"," \
"\"title\" : \"From Realtek Ameba\" " \
"} }" ;
setup() {
if (client.connect(server, 80)) {
Serial.println("connected to server");
// Make a HTTP request:
sprintf(message,"%s%s%s%s%s%d%s%s%s","POST /fcm/send HTTP/1.1\nContent-Type: application/json\nAuthorization: key=",SERVER_KEY,"\nHost: ",HOST_NAME,"\nContent-Length: ",strlen(payload),"\n\n",payload,"\n");
printf("\nRequest:\n%s \n",message);
client.println(message);
client.println();
}
}
The sprintf part puts the payload into the HTTP POST content and sends the message out after connecting to the FCM Server.
loop(){
while (client.available()) {
char c = client.read();
Serial.write(c);
}
}
Waiting for the response from Server and printing out the response.
Access IFTTT Via Ameba
Introduction to IFTTT
IFTTT, known as If This Then That, is a website and mobile app and free web-based service to create the applets, or the chains of simple conditional statements. The applet is triggered by changes that occur within other web services such as Gmail, Facebook, Telegram, Instagram, Pinterest etc.
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
An account from https://ifttt.com/ , in order to access IFTTT service*
備註
Upon log in, there are several cloud and online services that are integrated with IFTTT platforms.
Example
Generate Applet from IFTTT
In this example, we obtain an example of IFTTT Applet to send email to specified recipient.
To run the example, HTTP POST feature of the Ameba is used to post a simple webhook service that is received by IFTTT platform and in turn be used to trigger a response (sending an email).
After logging in https://ifttt.com/, click Create from the top bar.
Click “Add” to add the trigger.
Choose Webhooks service as shown below. Alternatively, search the service by typing into the search bar.
After that, the available triggers will appear. Choose Receive a Web request.
Next, an Event Name is required to identify the trigger successfully. In this example, set the Event name as “test_event”.
Next, click Add in Then That field to create the action service taken in response to the last trigger.
Choose Email as the action service.
Click on Send me an email.
Under the template of Send me an Email, the contents of the email, such as subject and body is editable. Click Create Action to complete the action. Take note that Email service is offered to the email address registered under IFTTT account.
Post the Trigger via Ameba
“File” -> “Examples” -> “AmebaWiFi” -> “HTTP_IFTTT_Post”
The WiFi credentials to connect to the Wi-Fi hotspot or access point of desirable choice.
Under the Host name field, enter the host name of the IFTTT service “maker.ifttt.com”.
Under the Path name field, enter the Event name and key field “/trigger/Event name/with/key/Key Field”
Event name: The event name should be the same as the one specified in the IFTTT applet. In this example, the event name is “test_event”.
Key Field: Available under webhook service in individual IFTTT account. See the next step for the steps to obtain the Key Field.
To obtain a key from documentation tab of the Webhooks, find the webhook service in the Explore tab.
On the Webhooks service page, click on the Documentation tab.
The key can be found in the documentation page. Also, information on how HTTP request can be used.
Thereafter an email is sent to recipient email account registered at IFTTT Applet and email notification will be received.
Use Ameba To Securely Retrieve Information From The Internet
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
This example uses Ameba to securely retrieve information from the internet using SSL. SSL is an acronym for Secure Sockets Layer. It is a cryptographic protocol designed to provide communications security over a computer network, by encrypting the messages passed between server and client.
Open the “WiFiSSLClient” example in “File” -> “Examples” -> “AmebaWiFi”
-> “WiFiSSLClient”
.
In the sample code, modify the highlighted snippet to reflect your WiFi network settings.
Upload the code and press the reset button on Ameba once the upload is finished.
Open the serial monitor in the Arduino IDE and observe as Ameba retrieves a text file from os.mbed.com.
Code Reference
Use “WiFiSSLClient client;” to create a client that uses SSL. After creation, the client can be used in the same way as a regular client.
BLE – BLE Battery Service
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Android / iOS mobile phone
Example
Introduction
BLE connections use a server client model. The server contains the data of interest, while the client connects to the server to read the data. Commonly, a Bluetooth peripheral device acts as a server, while a Bluetooth central device acts as a client. Servers can contain many services, with each service containing a some set of data. Clients can send requests to read or write some data and can also subscribe to notifications so that the server can send data updates to a client.
In this example, a basic battery service is set up on the Ameba Bluetooth stack. A mobile phone is used to connect to the Ameba peripheral device and read the battery data.
Procedure
Ensure that the following Bluetooth apps are installed on your mobile phone. These apps will show you the raw data sent by Ameba and allow you to interact with the data.
The recommended application is nRF connect, and is available at the links below:
LightBlue is an alternative application that can also be used, but has less features:
Open the example, “Files” -> “Examples” -> “AmebaBLE” ->
“BLEBatteryService”
Connect to the Ameba Bluetooth device, and a list of available services should appear. Click on the battery service to expand it, and you can see the battery level data value. The arrows highlighted in the box on the right are used to read data and subscribe to notifications. Click on the single arrow to read the battery level value, and a 90% value will appear.
Click on the triple arrow to subscribe to updates on the battery level value, and the battery value will start updating by itself.
The serial monitor will show the sketch increasing the battery level every second. When you click on either of the arrows, the sketch running on the Ameba will be notified, and will print out the action taken.
Code Reference
BLEService and BLECharacteristic classes are used to create and define the battery service to run on the Bluetooth device.
BLE.configAdvert()->setAdvType(GAP_ADTYPE_ADV_IND)
is used to set the
advertisement type to a general undirected advertisement that allows for
connections.
setReadCallback()
and setCCCDCallback()
is used to register functions
that will be called when the battery level data is read, or notification
is enabled by the user.
BLE.configServer(1)
is used to tell the Bluetooth stack that there will
be one service running.
addService()
registers the battery service to the Bluetooth stack.
BLE – BLE Beacon
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Android / iOS mobile phone
Example
Introduction
A BLE beacon broadcasts its identity to nearby Bluetooth devices, to enable the other devices to determine their location relative to the beacon, and to perform actions based on information broadcasted by the beacon.
Example applications of beacons include indoor positioning system, location-based advertising and more.
From the definition of its purpose as a broadcast device, a BLE beacon thus cannot be connected to, and can only send information in its Bluetooth advertisement packets.
There are several BLE beacon protocols. The Ameba BLEBeacon library supports the iBeacon and AltBeacon protocols.
Procedure
LightBlue is an alternative application that can also be used, but has less features:
Open the example, “Files” -> “Examples” -> “AmebaBLE” -> “BLEBeacon”
Upload the code and press the reset button on Ameba once the upload is finished.
On your mobile phone, open the Bluetooth app and scan for the beacon signal broadcast by Ameba.
If you happen to be in an environment with multiple BLE beacons, you can tap the entries to expand them, and verify that the beacon data is identical to the data in the sketch.
Code Reference
setRssi()
is used to set the received signal strength indicator (rssi)
data field for a beacon. The specification states that this should be
the received signal strength from the beacon at a 1 meter distance. With
no method to measure this, it is set to -65dBm as an estimate.
setMajor()
and setMinor()
are used to set the two data fields. The
purpose of these data are left for the manufacturer of the beacon to
define, and can be used in any way.
setUUID()
is used to give the beacon a universally unique identifier
(UUID). This is a 128-bit number usually expressed as a hexadecimal
string. It is used to identify each unique beacon, and can be randomly
generated for free online.
The BLEBeacon library includes both iBeacon and AltBeacon classes, replace line 6 iBeacon with altBeacon to create an AltBeacon instead. The data fields are mostly the same, with only minor changes, please look at the header files for more details.
BLE.init()
is used to allocate memory and prepare Ameba for starting the
Bluetooth stack.
BLE.configAdvert()
is used to configure the Bluetooth advertisement
settings, to which we pass the beacon data and set the device as
non-connectable.
BLE.beginPeripheral()
starts Ameba in Bluetooth peripheral mode, after
which it will begin to advertise with the beacon data provided.
BLE – BLE Scan
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Android / iOS mobile phone
Example
Introduction
This example configures the Ameba as a Bluetooth central device, uses the scan functionality to scan for other Bluetooth devices, and prints out the results to the serial monitor.
Procedure
Open the example, “Files” -> “Examples” -> “AmebaBLE” -> “BLEScan”
If you have the Bluetooth app nRF Connect installed, you can also use it to send out Bluetooth advertisements for the Ameba to pick up.
Code Reference
setScanMode(GAP_SCAN_MODE_ACTIVE)
is used to set the scan mode. Active
scanning will request for an additional scan response data packet from a
device when it is found. Passive scanning will only look at the
advertisement data, and not request for additional data.
setScanInterval()
and setScanWindow()
are used to set the frequency and
duration of scans in milliseconds. A scan will start every interval
duration, and each scan will last for the scan window duration. The scan
window duration should be lesser or equal to the scan interval. Set a
short interval to discover devices rapidly, set a long interval to
conserve power.
setScanCallback(scanFunction)
is used to register a function to be
called when scan results are received. This can be used to set a user
function for additional processing of scan data, such as looking for a
specific device. If no function is registered, the scan results are
formatted and printed to the serial monitor by default.
beginCentral(0)
is used to start the Bluetooth stack in Central mode.
The argument 0 is used to indicate that no clients will be operating in
central mode.
startScan(5000)
is used to start the scanning process for a specified
duration of 5000 milliseconds. The scan will repeat according to the set
scan interval and scan window values. After 5000 milliseconds, the scan
process will stop, and will be ready to be started again.
BLE – Battery Client
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
Introduction
BLE connections use a server client model. The server contains the data of interest, while the client connects to the server to read the data. Commonly, a Bluetooth peripheral device acts as a server, while a Bluetooth central device acts as a client. Servers can contain many services, with each service containing a some set of data. Clients can send requests to read or write some data and can also subscribe to notifications so that the server can send data updates to a client.
In this example, a basic battery client is set up on the Ameba Bluetooth stack. The client connects to another Ameba board running the corresponding BLE battery service to read the battery level data.
Procedure
On the first Ameba board, upload the BLEBatteryService example code and let it run.
For the second Ameba board, open the example “Files” -> “Examples” ->
“AmebaBLE” -> “BLEBatteryClient”
.
Upload the code and press the reset button on Ameba once the upload is finished.
Open the serial monitor and observe the log messages as the Ameba board with the battery client scans, connects, and reads data from the Ameba board with the battery service.
Highlighted in yellow, the Ameba board with the battery client first scans for advertising BLE devices with the advertised device name “AMEBA_BLE_DEV” and the advertised service UUID of 0x180F representing the battery service.
After finding the target device, the Ameba board with the battery client forms a BLE connection and searches for a battery service on the connected device, highlighted in blue.
With the client connected to the service, the battery client begins to read data using both regular data reads and notifications, highlighted in green.
Code Reference
BLEClient is used to create a client object to discover services and characteristics on the connected device.
setNotifyCallback()
is used to register a function that will be called when a battery level notification is received.
BLE.configClient()
is used to configure the Bluetooth stack for client operation.
addClient(connID)
creates a new BLEClient object that corresponds to the connected device.
BLE – WiFi Configuration Service
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Android / iOS mobile phone
Example
Introduction
In this example, a WiFi configuration service is set up on the Ameba Bluetooth stack. A mobile phone with the configuration app connects to the Ameba device using BLE and configures the Ameba to connect to the correct WiFi access point.
Procedure
Ensure that the Realtek WiFi configuration app is installed on your mobile phone, it is available at:
Open the example, “Files” -> “Examples” -> “AmebaBLE” ->
“BLEWifiConfigService”
.
Upload the code and press the reset button on Ameba once the upload is finished.
On your mobile phone, open the Realtek WiFiConfig app and tap the round button to scan for Ameba boards.
Select the correct Ameba board from the scan results. The app will connect to the Ameba board and ask the board to scan for WiFi networks and send the scan results back to the app using BLE.
If your phone is currently connected to a WiFi network, the app will ask for the WiFi password to connect the Ameba board to the same WiFi network. Tap “Select AP” to choose another WiFi network, or enter the password and tap continue to connect Ameba to the selected WiFi network.
After the Ameba board connects to the WiFi network, the following message will be shown. Tap “Try another AP” to connect to another WiFi network or tap “Confirm” to keep the current WiFi network and disconnect BLE from the Ameba board.
Code Reference
BLEWifiConfigService is used to create an instance of the WiFi configuration service to run on the Bluetooth device.
BLE.configAdvert()->setAdvType(configService.advData())
is used to set
the correct advertisement data necessary for the phone app to find the
Ameba Bluetooth device.
BLE – BLE UART Client
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 2
Example
Introduction
In this example, two RTL8722 boards are connected using BLE. One board runs a BLE UART service, while the other connects to the service using a client and both boards are able to communicate with text messages over the UART service.
Procedure
On the first board, upload the BLE UART service example code. Refer to the example guide for detailed instructions.
For the second board, open the example, “Files” -> “Examples” ->
“AmebaBLE” -> “BLEUartClient”
.
Code Reference
The BLEClient class is used to discover the services that exist on a connected BLE device. The discovery process will create BLERemoteService, BLERemoteCharacteristic and BLERemoteDescriptor objects corresponding to the services, characteristics and descriptors that exist on the connected device. These objects can then be used to read and write data to the connected device.
BLE – BLE UART Service
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Android / iOS smartphone
Example
Introduction
Procedure
Open the example, “Files” -> “Examples” -> “AmebaBLE” ->
“BLEUartService”
.




Code Reference
set__Property()
methods, and callback
functions are registered using the set__Callback()
methods. The
required buffer size is also set for each characteristic so that it
has enough memory to store a complete string.notify()
method is used to
inform the connected device of the new data.BLE – DHT over BLE UART
Materials
AmebaD [RTL8722DM/ RTL8722CSM/ RTL8722DM MINI] x 1
DHT11 or DHT22 or DHT21
Android / iOS smartphone
Example
Introduction
In this example, the data obtained from a DHT temperature and humidity sensor are transmitted over a BLE UART service to a smartphone. Refer to the other examples for detailed explanations of using the DHT sensor and the BLE UART service.
Procedure
Connect the DHT sensor to the Ameba board following the diagram.
RTL8722DM / RTL8722CSM:
RTL8722DM MINI:
Open the example, “Files” -> “Examples” -> “AmebaBLE” ->
“DHT_over_BLEUart”
.
BLE – PWM over BLE UART
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
RGB LED
Android / iOS smartphone
Example
Introduction
In this example, a smartphone app is used to transmit commands over BLE UART to control the PWM outputs and change the color of a RGB LED. Refer to the other example guides for detailed explanations of the BLE UART service.
Procedure
Connect the RGB LED to the RTL8722 board following the diagram, the common LED pin may need to connect to 3.3V or GND depending on the type of LED (common anode / common cathode).
RTL8722DM / RTL8722CSM:
RTL8722DM MINI:
Open the example, “Files” -> “Examples” -> “AmebaBLE” ->
“PWM_over_BLEUart”
.
Upload the code and press the reset button on Ameba once the upload is finished.
Using the color selection wheel, saturation, and brightness sliders, choose a desired color and click select to send the RGB values to the board. You should see the RGB LED change to the matching color.
Code Reference
The RGB values are sent as three consecutive bytes prefixed by “!C” characters. The “!” exclamation mark is used to indicate that the following data is a command, and the “C” character is used to indicate that the data is RGB values. The received UART message is checked in the callback function for “!C” first, otherwise it is treated as a regular message and printed to the serial terminal.
Approximate UDP Receive Delay
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Windows computer connected to same network
Example
This example uses Ameba to receive UDP packets from a computer and calculates the UDP receive delay.
Ameba Preparation
Open the “CalculateUdpReceiveDelay” example in
“File” -> “Examples” -> “AmebaWiFi” -> “UDP_Calculation” -> “CalculateUdpReceiveDelay”
.
In the sample code, modify the highlighted section to enter the information required (ssid, password, key index) to connect to your WiFi network.
Upload the code and press the reset button on Ameba once the upload is finished. Open the serial monitor in Arduino IDE and take note of the IP address assigned to Ameba.
Computer Preparation
On the computer, Cygwin will be required to compile the code to send the UDP packets. Cygwin can be downloaded from https://www.cygwin.com/
Follow the instructions there to install it. Next, from the “CalculateUdpReceiveDelay” Arduino example, copy the code from the bottom between “#if 0” and “#endif”, into a new text file, change the hostname to the IP address assigned to Ameba, and rename the file to “UdpReceiveDelay.cpp”.
Next, open a Cygwin terminal, change the working directory to the location of “UdpReceiveDelay.cpp”, and use the command “g++ UdpReceiveDelay.cpp -o UdpDelay” to compile the code. A file named “UdpDelay.exe” will be created in the same directory.
Running the Example
Reset the Ameba, wait for the WiFi to connect, and check that the IP address remains the same. On the computer, run the UdpDelay.exe file, and the computer will begin to send packets to Ameba. Once 10000 packets have been received, Ameba will calculate the average delay and print out the result to the serial monitor. It may take up to a few minutes for 10000 packets to be sent.
Approximate UDP Receive Timeout
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Windows computer connected to same network
Example
This example uses Ameba to receive UDP packets from a computer and calculates the allowed UDP receive timeout setting.
Ameba Preparation
Open the “CalculateUdpReceiveTimeout” example in
“File” -> “Examples” -> “AmebaWiFi” -> ” UDP_Calculation ” -> “CalculateUdpReceiveTimeout”
.
In the sample code, modify the highlighted section to enter the information required (ssid, password, key index) to connect to your WiFi network.
Upload the code and press the reset button on Ameba once the upload is finished.
Open the serial monitor in Arduino IDE and take note of the IP address assigned to Ameba.
Computer Preparation
On the computer, Cygwin will be required to compile the code to send the UDP packets. Cygwin can be downloaded from https://www.cygwin.com/
Follow the instructions there to install it. Next, from the “CalculateUdpReceiveTimeout” Arduino example, copy the code from the bottom between “#if 0” and “#endif”, into a new text file, change the hostname to the IP address assigned to Ameba, and rename the file to “UdpReceiveTimeout.cpp”.
Next, open a Cygwin terminal, change the working directory to the location of “UdpReceiveTimeout.cpp”, and use the command “g++ UdpReceiveTimeout.cpp -o UdpTimeout” to compile the code. A file named “UdpTimeout.exe” will be created in the same directory.
Running the Example
Reset the Ameba, wait for the WiFi to connect, and check that the IP address remains the same. On the computer, run the UdpTimeout.exe file, and the computer will begin to send packets continuously to Ameba.
The timeout value is set to 1000ms initially. For each packet received successfully, Ameba decreases the timeout value. The next packet must be received within the timeout period, otherwise Ameba registers a failed packet and increases the timeout value. Open the serial monitor and observe the timeout value converge to a minimum value.
Approximate UDP Sending Delay
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Windows computer connected to same network
Example
This example uses Ameba to send UDP packets to a computer and calculates the UDP sending delay.
Ameba Preparation
Open the “CalculateUdpSendDelay” example in “File” -> “Examples” ->
“AmebaWiFi” -> ” UDP_Calculation ” -> “CalculateUdpSendDelay”
.
In the sample code, modify the highlighted section to enter the information required (ssid, password, key index) to connect to your WiFi network.
The server variable also needs to be changed to match the IP address of your computer. You can find the IP address using the “ipconfig” command in a terminal window.
Computer Preparation
On the computer, Cygwin will be required to compile the code to send the UDP packets. Cygwin can be downloaded from https://www.cygwin.com/
Follow the instructions there to install it. Next, from the “CalculateUdpSendDelay” Arduino example, copy the code from the bottom between “#if 0” and “#endif”, into a new text file and rename the file to “UdpSendDelay.cpp”.
Next, open a Cygwin terminal, change the working directory to the location of “UdpSendDelay.cpp”, and use the command “g++ UdpSendDelay.cpp -o UdpDelay” to compile the code. A file named “UdpDelay.exe” will be created in the same directory.
Running the Example
First, on the computer, run the UdpDelay.exe file, and the computer will begin to listen for packets from Ameba.
Next, compile and upload the code from the Arduino IDE to Ameba and press the reset button when the upload is complete.
The Ameba will begin to send UDP packets to the computer. Once 10000 packets have been received, the computer will calculate the average delay and print out the result.
It will take some time for 10000 packets to be sent.
Google Cloud IoT
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Google Cloud IoT Configuration
1. Select or create a Cloud Platform project In the Google Cloud Console, select an existing project or create a new project. You will need a Project ID to use with Ameba.
If creating a new project, enter a project name, and take note of the Project ID generated.
2. Enable billing for your project Billing needs to be enabled for your project to use Google Cloud Platform features. Follow the guide in Google cloud documentation to enable billing. https://cloud.google.com/billing/docs/how-to/modify-project 3. Enable the Cloud IoT Core API In Google Cloud console, click on the top left menu button and search for IoT Core.
Click enable to activate Google Cloud IoT API for your project.
4. Create a Cloud Pub/Sub topic In Google Cloud console, click on the top left menu button and search for Pub/Sub.
Create a new topic for your project and give it a suitable topic ID.
After the topic is created, go to the permissions tab of the info panel, and add “cloud-iot@system.gserviceaccount.com” with the role of “Pub/Sub Publisher”.
5.Create a device registry Go back to the IoT Core settings page and create a new registry.
Choose a suitable Registry ID and in which to store data. Remember the **Registry ID and Regionfor use with Ameba later. For the Pub/Sub topic, select the topic created in the previous step.
6. Create a public/private key pair Using Openssl in a terminal in Windows/Linux/MacOs, run the following commands to generate a private and public key pair. Two files will be created by these commands, “ec_private.pem” containing the private key, and “ec_public.pem” containing the public key.
$ openssl ecparam -genkey -name prime256v1 -noout -out ec_private.pem
$ openssl ec -in ec_private.pem -pubout -out ec_public.pem
Run the next command to extract out the private key, and remember the highlighted string of hexadecimal numbers for use with Ameba later.
$ openssl ec -in ec_private.pem -noout -text
7. Create a device Go back to the IoT Core settings page and create a new device.
Give the device a suitable Device ID and remember it for use with Ameba later.
In the authentication section of the additional options, upload the previously generated “ec_public.pem” public key.
8. Create a Cloud Pub/Sub subscription To observe messages sent by Ameba, create a subscription in Pub/Sub.
Choose a suitable subscription ID and select the previously created topic.
Example
“File” -> “Examples” -> “AmebaMQTTClient” ->
“Google_Cloud_IoT”
.Code Reference
In setup()
, we set up RootCA which is required to form a TLS connection
with Google’s servers.
wifiClient.setRootCA((unsigned char*)rootCABuff);
In loop()
, each loop checks the Internet status and re-connect to it
when the environment has a problem.
if (WiFi.status() != WL_CONNECTED) {
while (WiFi.begin(ssid, pass) != WL_CONNECTED)
{
delay(1000);
}
Serial.println("Connected to wifi");
}
To publish messages, mqtt_id , clientPass and pub_topic are required. mqtt_id is generated by printing the project ID, server location, registry ID and device ID in the required format:
mqtt_id = (char *)malloc(strlen("projects/") + strlen(project_id) + strlen("/locations/us-central1/registries/") + strlen(registry_id) + strlen("/devices/") + strlen(device_id) + 1);
sprintf(mqtt_id, "projects/%s/locations/us-central1/registries/%s/devices/%s", project_id, registry_id, device_id);
clientPass
is generated using a JSON web token (JWT) generator function,
which requires the project ID and current time, and signs it with the
private key:
clientPass = CreateJwt(project_id, timeClient.getEpochTime(), priv_key);
pub_topic
is generated by printing the project ID and topic in the
required format:
pub_topic = (char *)malloc(strlen("/devices/") + strlen(device_id) + strlen("/events") + 1);
sprintf(pub_topic, "/devices/%s/events", device_id);
MQTT Server setting:
client.setServer(GOOGLE_MQTT_SERVER, GOOGLE_MQTT_PORT);
client.setPublishQos(MQTTQOS1);
client.waitForAck(true);
Connect to google cloud and publish messages:
if (client.connect(mqtt_id, clientUser, clientPass.c_str())){
// ...
for(int i = 0; i < count; i++){
// ...
sprintf(payload, "This is Ameba's %d message!!", i);
ret = client.publish(pub_topic, payload);
// ...
}
// ...
client.disconnect();
}
free(mqtt_id);
free(pub_topic);
使用元件
溫濕度傳感器
|
距離測量的功能
|
使用 SPI 接口的 TFT LCD 顯示屏
|
|
QVGA TFT LCD 顯示器模組
|
高質量 GPS 定位模組
|
高輸出功率的伺服電機
|
Peripheral Examples
GPIO - Measure The Distance By Ultrasound Module
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
HC-SR04 Ultrasonic x 1
Dropping resistor or Level converter
Example
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Next, open the sample code in “File” -> “Examples” -> “AmebaGPIO” -> “HCSR04_Ultrasonic”
Compile and upload to Ameba, then press the reset button. Open the Serial Monitor, the calculated result is output to serial monitor every 2 seconds.
Note that the HCSR04 module uses the reflection of sound wave to calculate the distance, thus the result can be affected by the surface material of the object (e.g., harsh surface tends to cause scattering of sound wave, and soft surface may cause the sound wave to be absorbed).
Code Reference
Before the measurement starts, we need to pull high the TRIG pin for 10us and then pull low. By doing this, we are telling the HC-SR04 that we are about to start the measurement:
digitalWrite(trigger_pin, HIGH);
delayMicroseconds(10);
digitalWrite(trigger_pin, LOW);
Next, use pulseIn to measure the time when the ECHO pin is pulled high.
duration = pulseIn (echo_pin, HIGH);
Finally, use the formula to calculate the distance.
distance = duration / 58;
GPIO - Measuring The Temperature And Humidity
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
DHT11 or DHT22 or DHT21
Example
Since one of the 4 pins has no function, there are temperature/humidity sensors with only 3 pins on the market:
DHT is normally in the sleeping mode. To get the temperature/humidity data, please follow the steps:
Awake DHT: Ameba toggles low its DATA pin of GPIO. Now the DATA pin of GPIO serves as digital out to Ameba.
DHT response: DHT also toggle low its DATA pin of GPIO. Now the DATA pin of GPIO serves as digital in for Ameba.
DHT sends data: DHT sends out the temperature/humidity data (which has size 5 bytes) in a bit by bit manner. To represent each bit, DHT first pull low the DATA GPIO pin for a while and then pull high. If the duration of high is smaller than low, it stands for bit 0. Otherwise it stands for bit 1.
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Open the sample code in “Files” -> “Examples” -> “AmebaGPIO” ->
“DHT_Tester”
. Compile and upload to Ameba, then press the reset button.
The result would be shown on the Serial Monitor.
Code Reference
Use dht.readHumidity()
read the humidity value, and
use dht.readTemperature()
to read the temperature value.
Every time we read the temperature/humidity data, Ameba uses the buffered temperature/humidity data unless it found the data has expired (i.e., has not been updated for over 2 seconds). If the data is expired, Ameba issues a request to DHT to read the latest data.
GPIO - Use GPIO Interrupt To Control LED
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
LED x 1
Button x 1
Example
In this example, we use a button to trigger interrupt and control the LED. When we press and release the button, the LED dims, press and release the button again, and the LED lights.Note that in the Arduino example “Button and LED”, LED only lights when the button is pressed and hold, when we release the button, the LED dims.
Open the example, “Files” -> “Examples” -> “AmebaGPIO” ->
“LED_InterruptCtrl”
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Code Reference
In
setup()
we set Pin 12 to
INPUT_IRQ_RISE
, this means that an interrupt occurs when the voltage of this pin changes from GND to 3V3. Therefore, we connect the other side of the button to 3V3, so as to trigger interrupt event when the button is pressed.
pinMode(button, INPUT_IRQ_RISE);
On the other hand, we can set pin 12 to
INPUT_IRQ_FALL
, this means that an interrupt occurs when the voltage of this pin changes from 3V3 to GND. In this case, the other side of the button is connected to GND.Next, we need to specify the funtion to be execute to handle the interrupt:
digitalSetIrqHandler(button, button_handler);
The second parameter is a function pointer, with prototype:
void button_handler(uint32_t id, uint32_t event)
In this handler, every time we press and release the button, we trigger an interrupt, and change the status of the LED.
PWM – Play Music
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Buzzer x 1
Example
A sound is composed of volume, tone and timbre. Volume is determined by the amplitude of the sound wave. Tone is determined by the frequency of the sound wave. Timbre is determined by the waveform of the sound wave.
In this example, we use PWM to control the buzzer to emit sound with desired tone. As PWM outputs square wave, if we wish to emit tone C4 (frequency=262Hz), we have to make PWM to output square wave with wavelength 1/262 = 3.8ms:
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
“Examples” -> “AmebaAnalog” -> “TonePlayMelody”
Code Reference
In the sample code, we initiate a melody array, which stores the tones to make. Another array, noteDurations, contains the length of each tone, 4 represents quarter note (equals to 3000ms/4 = 750ms, and plus an extra 30% time pause), 8 represents eighth note.
PWM – Using A Servo
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Servo x 1 (Ex. Tower Pro SG90)
Example
A typical servo has 3 wires, the red wire is for power, black or brown one should be connected to GND, and the other one is for signal data. We use PWM signal to control the rotation angle of the axis of the servo. The frequency of the signal is 50Hz, that is length 20ms. Each servo defines its pulse bandwidth, which is usually 1ms~2ms.
To control the rotation angle, for example if 1ms-length pulse rotates the axis to degree 0, then 1.5 ms pulse rotates the axis to 90 degrees, and 2 ms pulse rotates the axis to 180 degrees. Furthermore, a servo defines the “dead bandwidth”, which stands for the required minimum difference of the length of two consecutive pulse for the servo to work.
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
“File” -> “Examples” -> “AmebaAnalog” ->
“ServoSweep”
Code Reference
The Servo API of Ameba is similar to the API of Arduino. To distinguish from the original API of Arduino, we name the header file “AmebaServo.h” and the Class “AmebaServo”, the usage is identical to the Arduino API.
The default pulse bandwidth of Arduino Servo is 0.5ms~2.4ms, which is the same as Tower Pro SG90. Therefore, we set the attached pin directly:
myservo.attach(9);
Next, rotate the axis to desired position:
myservo.write(pos);
I2C - Communicate with Arduino UNO via I2C
Introduction of I2C
There are two roles in the operation of I2C, one is “master”, the other is “slave”. Only one master is allowed and can be connected to many slaves. Each slave has its unique address, which is used in the communication between master and the slave. I2C uses two pins, one is for data transmission (SDA), the other is for the clock (SCL). Master uses the SCL to inform slave of the upcoming data transmission, and the data is transmitted through SDA. The I2C example was named “Wire” in the Arduino example.
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Arduino UNO x 1
Example
Setting up Arduino Uno to be I2C Slave
“Tools” -> “Board” -> “Arduino Uno”
“Examples” -> “Wire” -> “slave_receiver”
:Then click “Sketch” -> “Upload”
to compile and upload the example to Arduino Uno.
Setting up Ameba to be I2C Master
“Tools” -> “Board”
“File” -> “Examples” ->
“AmebaWire” -> “MasterWriter”
Wiring
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Code Reference
I2C - Display Data On LCD Screen
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
I2C 2×16 LCD
Example
“File” -> “Examples” -> “AmebaWire” -> “LCD_HelloWorld”
.After 8 seconds, you can input to the Serial Monitor the string you would like to display on the LCD.
For example, we enter “123456789” and press “Send”:
Code Reference
The required settings of each model of LCD might be different, the constructor we use in this example is:
LiquidCrystal_I2C(uint8_t lcd_Addr, uint8_t En, uint8_t Rw, uint8_t Rs,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7,
uint8_t backlighPin, t_backlighPol pol);
And the setting parameters are as follows:
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address
The first parameter 0x27 is the address of I2C. Each of the following 8 parameters represents the meaning of each bit in a byte, i.e., En is bit 2, Rw is bit 1, Rs is bit 0, d4 is bit 4, and so forth.
backlight()
to light the screen,setCursor(0, 0)
to set the position of the cursor.lcd.print()
to output string on the screen.I2C - Use I2C to receive data from Arduino UNO
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Arduino UNO x 1
Example
Setting up Arduino Uno to be I2C Slave
“Tools” -> “Board” ->
“Arduino Uno”
:“Examples” -> “Wire” -> “slave_sender”
Then click “Sketch” -> “Upload” to compile and upload the example to Arduino Uno.
Setting up Ameba to be I2C Master
“File” -> “Examples” -> “AmebaWire” -> “MasterReader”
Wiring
Code Reference
Wire.begin()
/ Wire.begin(address)
to join the I2C bus as a
master or slave, in the Master case the address is not required.Wire.requestFrom()
to specify from which Slave
to request data.UART - Communicate with the computer via UART
Introduction of UART
UART uses two wire, one for transmitting and the other one for receiving, so the data transmission is bidirectional. The communication uses a predefined frequency (baud rate) to transmit data. In Arduino, UART is called “Serial”. There is only one hardware UART on Arduino Uno and it is primarily used to read the log and messages printed by Arduino (so it is also called “Log UART”). If we use the hardware UART for other purposes, the Log UART does not have resources to function. To provide more UART connections, it is possible to use a GPIO pin to simulate the behavior of UART with a software approach, this is called Software Serial. Ameba is equipped with several hardware UART ports, but it is also compatible with the Software Serial library.
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
USB to TTL Adapter x 1
Example
Install USB to TTL Adapter
Executing the Example
“File” -> “Examples” ->
“AmebaSoftwareSerial” -> “SoftwareSerial_Basic”
:Next, open a serial port terminal, such as Putty or Tera Term. (Putty is used in this example). Open the Putty window, choose “Serial” in connection type, and specify the port number of the USB to TTL adapter (e.g. COM8). In the speed field, fill in the baud rate of this connection. Note that both sides of the connection should use the same baud rate. In this example we set baud rate 4800.
Next, select “Serial” on the left side. Set data bits to 8, stop bits to 1, parity to none, and flow control to none.
Then click Open and press the reset button on Ameba. You can see the “Hello, world?” message appears in Putty. If characters are typed into Putty, the input characters would be sent to Serial RX of Ameba by TX of USB to TTL Adapter, and returned by Serial TX of Ameba. Finally, RX of USB to TTL Adapter receives the returned characters and prints them in Putty. Therefore, if you insert “I am fine”, you will get something like this:
Code Reference
SoftwareSerial:begin(speed)
to set the baud rate for the
serial communication:write()
to send data, and use SoftwareSerial:available()
to get the
number of bytes available for reading from a software serial port:UART - Retrieve GPS Position
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Adafruit Ultimate GPS Breakout x 1 (Refer to official document)
Example
In this example, we use Adafruit Ultimate GPS Breakout. Its data format
is pure text, so we can connect it to USB to TTL Adapter and observe the
output.
It follows the NMEA sentence format (refer to http://aprs.gids.nl/nmea/)
The GPS signal is weak in indoor environment.
The status that the GPS signal is not received is called “not fix”.
Bring the GPS module outdoors, when the GPS signal is “fix”,
you would get message similar to the figure below.
First field is the GMT time (Greenwich Mean Time), that is 032122.000 in this example. The time format is HH:MM:SS.SSS, i.e., 03:21:22.000. Note that the time zone and the daylight-saving time adjustment should be handled on your own.
Second field represents the status code
V: Void (Invalid)
A: Active, meaning the GPS signal is fix.
The third to sixth fields represent the geolocation
In this example, 2446.8181,N represents 24 degrees 46.8181 minutes north latitude, and 12059.7251,E represents 120 degrees 59.7251 minutes east longitude.
We can search +24 46.8181’, +120 59.7251’ in Google map
to check whether the position is correct.
The seventh field is relative speed(knot). 1 knot = 1.852km/hr, in this example the relative speed is 0.39 knot.
The eighth field is the moving angle, which is calculated by its moving orbit.
The ninth field is the date with format ddMMyy. In this example, “270116” stands for day 27, January, year 2016.
The last field is checksum. In the example we have *53 as checksum.
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Open the example in “Files” -> “Examples” ->
“AmebaSoftwareSerial” -> “Adafruit_GPS_parsing”
.
UART – Set Callback Function For UART Communications
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
USB to TTL Adapter x 1
Example
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
Open the example in “File” -> “Examples” -> “AmebaSoftwareSerial” ->
“SoftwareSerial_Irq_Callback”
Once the serial port is open, type in the terminal and press the enter key, and you will see the corresponding output.
Code Reference
mySerial.setAvailableCallback(mySerialCallback);
is used to set the
function mySerialCallback as a callback function for software serial.
When a new character is received, the callback function checks if the
character corresponds to the enter key, and releases the semaphore if it
is true, which in turn allows the main loop to print out all the
previously received characters.
PM2.5 Concentration in The Air
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
PlanTower PMS3003 or PMS5003 x 1
Example
PMS3003 (or PMS5003) is a sensor of air quality, it can detect the concentration of those 0.3 to 10 micrometer particulate matters in the air. The sensor output its data via UART.
The PMS3003 (or PMS5003) sensor detects the concentration value of PM 1.0, PM 2.5, PM 10. Take PM 2.5 for example, it stands for the fine particles with a diameter of 2.5 micrometers or less.
Open the example in “File” -> “Examples” -> “AmebaSoftwareSerial” -> “PMS3003_AirQuality”
There are 8 pins in PMS3003:
PMS3003 requires 5V power, but the working voltage of its IC is 3.3C. Therefore, the working voltage of Reset, TX, RX, Set are 3.3 as well. If the “Set” pin is pulled to high, the PMS3003 is put to operating mode. If the “Set” pin is pulled low, the PMS3003 is put to standby mode.
TX/RX pins are for UART connection. Under operating mode, PMS3003 output the data it reads continuously. Each data is of 32 byte, please refer to the following article for detailed data format information:
https://www.dfrobot.com/wiki/index.php?title=PM2.5_laser_dust_sensor_SKU:SEN0177 RTL8722
RTL8722DM / RTL8722CSM Wiring Diagram:
RTL8722DM MINI Wiring Diagram:
In this example, we do not use the “Set” and “Reset” pins.
Compile the code and upload it to Ameba. After pressing the Reset button, Ameba starts to output the PM 2.5 data to serial monitor.
Flash Memory - Store data in FlashEEProm
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
Code Reference
By default, the Flash Memory API uses address 0xFF000~0xFFFFF to store data.
There is limitation when writing to flash memory. That is, you can not directly write data to the same address you used in last write. To do that correctly, you need erase the sector first. The Flash API of Ameba uses a 4K SRAM to record the user modification and do the erase/write task together.
FlashMemory.read()
to read from Flash memory.FlashMemory.buf[0] = 0x00;
to manipulate the 4K buf.FlashMemory.update();
to update the data in buf to Flash Memory.Flash Memory - Use Flash Memory Larger Than 4K
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
“File” -> “Examples” ->
“AmebaFlashMemory” -> “ReadWriteOneWord”
Code Reference
We can use the flash api we used in previous flash memory example, but
we need to use begin()
function to specify the desired starting address
and memory size.
FlashMemory.begin(0xFC000, 0x4000);
Use readWord()
to read the value stored in a memory address. In the
example, we read the value stored in memory offset 0x3F00, that is
0xFC000 + 0x3F00 = 0xFFF00. readWord()
function reads a 32-bit value and
returns it.
value = FlashMemory.readWord(0x3F00);
Use writeWord()
to write to a memory address. The first argument is the
memory offset, the second argument is the value to write to memory.
FlashMemory.writeWord(0x3F0C, value);
SPI – Print Image And Text On LCD Screen
If you are not familiar with SPI, please read Introduction to SPI first.
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
ILI9341 TFT LCD with SPI interface x 1
Example
We have tested the following two models of ILI9341 TFT LCD with SPI interface:
Adafruit 2.8″ TFT LCD (with touch screen)
QVGA 2.2″ TFT LCD
Common pins in ILI9341 TFT LCD with SPI interface:
MOSI: Standard SPI Pin
MISO: Standard SPI Pin
SLK: Standard SPI Pin
CS: Standard SPI Pin
RESET: Used to reboot LCD.
D/C: Data/Command. When it is at Low, the signal transmitted are commands, otherwise the data transmitted are data.
LED (or BL): Adapt the screen backlight. Can be controlled by PWM or connected to VCC for 100% backlight.
VCC: Connected to 3V or 5V, depends on its spec.
GND: Connected to GND.
RTL8722DM / RTL8722CSM and QVGA TFT LCD Wiring Diagram:
RTL8722DM MINI and QVGA TFT LCD Wiring Diagram:
RTL8722DM / RTL8722CSM and Adafruit 2.8』』 TFT LCD touch shield Wiring Diagram:
RTL8722DM MINI and Adafruit 2.8』』 TFT LCD touch shield Wiring Diagram:
Open the example, “Files” -> “Examples” -> “AmebaSPI” -> “ILI9341_TFT_LCD_basic”
Code Reference
RGB 16-bit
ILI9341 uses RGB 16-bit to display colors. Different from RGB 24-bit, it uses 5 bits for red, 6 bits for green, 5 bits for blue. For example, the RGB 24-bit representation of sky blue is 0x87CEFF, that is in binary:
Red: 0x87 = B10000111
Green: 0xCE = B11001110
Blue: 0xFF = B11111111
and converted to RGB 16-bit:
Red: B10000
Green: B110011
Blue: B11111
Then concatenate them, which forms B1000011001111111 = 0x867F
Drawing of ILI9341
First you must specify the range of the rectangle to draw, then pass the 2-byte RGB 16-bit color to ILI9341 corresponding to each pixel one by one, in this way ILI9341 fills each color to each pixel.
You still must specify the drawing range even though the range covers only one pixel.
From the rules we mentioned above, we can conclude that drawing vertical or horizontal lines are faster than diagonal lines.
Printing text on ILI9341
In our API, each character is 5×7 but each character is printed to size 6×8 (its right side and below are left blank), so as to separate from next character. For example, the character “A”:
The font size represents the dot size. For example, if the font size is 2, each dot in the character is a 2×2 rectangle
Screen rotation
ILI9341 provides 0, 90, 180, 270 degrees screen rotation.
If the original width is 240 and original height is 320, when the screen rotates 90 degrees, the width becomes 320 and the height becomes 240.
SPI – Show PM2.5 Concentration On ILI9341 TFT LCD
If you are not familiar with SPI, please read Introduction to SPI first.
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
ILI9341 TFT LCD with SPI interface x 1
Plantower PMS3003 or PMS5003 x 1
Example
Open the example, “Files” -> “Examples” -> “AmebaSPI” -> “PM25_on_ILI9341_TFT_LCD”
Compile and upload to Ameba, then press the reset button.
Then you can see the concentration value of PM1.0, PM2.5 and PM10 on the LCD.
Code Reference
In this example, first rotate the screen by 90 degrees, and draw the static components such as the circles, the measuring scale, and the title text. After the concentration value is detected, it is printed inside the circle.
Timer - Using The Periodic GTimer
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] / [RTL8720DN(BW16)] x 1
Example
“File” -> “Examples” -> “AmebaGTimer” -> “TimerPeriodical”
. Compile and upload to Ameba, and press reset.Code Reference
GTimer.begin(0, 1 * 1000 * 1000, myhandler);
The GTimer is periodic by default, therefore “myhandler” function is
called every second. When we want to stop the GTimer, use stop()
:
GTimer.stop(0);
Timer - Using The Single-Use GTimer
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] / [RTL8720DN(BW16)] x 1
Example
In this example, we will use 4 One-Time GTimer, and pass user data to each timer.
Open the example “File” -> “Examples” -> “AmebaGTimer” -> “TimerOneshot”
.
Compile and upload to Ameba, and press reset.
Then you can see the 4 timer log printed to the serial monitor in series.
Code Reference
The first argument of begin() is the Timer ID (0~3). The second argument is the value of the timer (in microseconds). In the example, we fill in 1000000us = 1s. The third argument specifies the function to call when the time is up. The fourth argument is to set whether this timer is a periodic timer, we use “false” here to begin a single-use timer. The fifth argument is the user data, we give 0 here to represent that this is timer 0.
GTimer.begin(0, 1 * 1000 * 1000, myhandler, false, 0);
Next, we set up the second timer, which has timer value 2 seconds, and user data 1. And other timers are set similarly.
GTimer.begin(1, 2 * 1000 * 1000, myhandler, false, 1);
In myhandler function, we print the user data to serial monitor. Since the 4 timers are separately set to count for 1, 2, 3, 4 seconds, from 1 second to 4 second, the user data of each timer are printed on the serial monitor in order. After 4 second, no log will be printed.
Power Save Deep Sleep Mode
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
Introduction
Ameba-D supports two low power modes which are deepsleep mode and sleep mode. Deepsleep mode turns off more power domain than sleep mode. The power consumptions of DeepSleep Mode is around 7uA to 8uA compare to normal state around 22mA. This example describes how to enter deepsleep mode and configure wakeup source.
“File” -> “Examples” -> “AmebaPowerSave” -> “DeepSleepMode”
DS_WAKEUP_SOURCE
is used to set the wake-up source, user can chose 3
wake up sources now,AON timer (SET_DS_AON_TIMER_WAKEUP);
AON pins (SET_DS_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON timer can be set from 0 to 32760000 range (unit ms) by
AON_TIMER_SLEEP_DURATION
There are 4 pins can be set as AON pins and active high for wake-up,
D16, D17, D26 and D27. The AON pin can be set by
SET_DS_AON_WAKEPIN_WAKEUPPIN
RTC timer wake-up system by set alarm. The alarm has 4 values, day,
hour, min and sec. All 4 values can be set by DS_RTC_ALARM_DAY
,
DS_RTC_ALARM_HOUR
, DS_RTC_ALARM_MIN
, and DS_RTC_ALARM_SEC
When finished the condition values setting, system will run and switch between normal and deepsleep mode controlled by wakeup source. Serial Monitor displays the switching log.
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
Power Save Deep Sleep DHT Eink
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
DHT11 or DHT22 or DHT21 x 1
LCD I2C screen x 1
Example
“File” -> “Examples” -> “AmebaPowerSave” ->
“DeepSleep_DHT_Eink_Example”
DS_WAKEUP_SOURCE
is used to set the wake-up source, user can chose 3
wake up sources now,AON timer (SET_DS_AON_TIMER_WAKEUP);
AON pins (SET_DS_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON timer can be set from 0 to 32760000 range (unit ms) by
AON_TIMER_SLEEP_DURATION
There are 4 pins can be set as AON pins and active high for wake-up,
D16, D17, D26 and D27. The AON pin can be set by
SET_DS_AON_WAKEPIN_WAKEUPPIN
RTC timer wake-up system by set alarm. The alarm has 4 values, day,
hour, min and sec. All 4 values can be set by DS_RTC_ALARM_DAY
,
DS_RTC_ALARM_HOUR
, DS_RTC_ALARM_MIN
, and DS_RTC_ALARM_SEC
DHTPIN
is used to set DHT sensor data pin. User can choose any GPIO
pins.DHTTYPE
is used to set DHT sensor type. (DHT11, DHT22 and DHT33)When finished the condition values setting, system will run and switch between normal working mode and deepsleep mode controlled by wakeup source. Eink screen will display the temperature and humidity data measured from DHT sensor when system is awake.
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
Power Save Deep Sleep DHT LCD
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
DHT11 or DHT22 or DHT21 x 1
LCD I2C screen x 1
Example
Introduction
Ameba-D supports low power modes which are deepsleep mode. Deepsleep mode turns off most of the system power domain. The power consumptions of core module in DeepSleep Mode is around 7uA to 8uA compare to normal state around 22mA. This example gives demo of system switch between “working” and “sleep”(power save).Using DHT sensor to read data and display on LCD screen when system is awake. After 5 seconds system auto enter DeepSleep Mode for power save. System will wake up by wakeup source.( Aon timer, Aon Pins or RTC timer).
“File” -> “Examples” -> “AmebaPowerSave” ->
“DeepSleep_DHT_LCD_Example”
DS_WAKEUP_SOURCE
is used to set the wake-up source, user can chose 3
wake up sources now,AON timer (SET_DS_AON_TIMER_WAKEUP);
AON pins (SET_DS_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON timer can be set from 0 to 32760000 range (unit ms) by
AON_TIMER_SLEEP_DURATION
There are 4 pins can be set as AON pins and active high for wake-up,
D16, D17, D26 and D27. The AON pin can be set by
SET_DS_AON_WAKEPIN_WAKEUPPIN
RTC timer wake-up system by set alarm. The alarm has 4 values, day,
hour, min and sec. All 4 values can be set by DS_RTC_ALARM_DAY
,
DS_RTC_ALARM_HOUR
, DS_RTC_ALARM_MIN
, and DS_RTC_ALARM_SEC
DHTPIN
is used to set DHT sensor data pin. User can choose any GPIO
pins.DHTTYPE
is used to set DHT sensor type. (DHT11, DHT22 and DHT33)When finished the condition values setting, system will run and switch between normal working mode and deepsleep mode controlled by wakeup source. LCD screen will display the temperature and humidity data measured from DHT sensor when system is awake.
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
Power Save Tickless Mode
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
Introduction
Ameba-D supports two low power modes which are deepsleep mode and sleep mode. The power consumptions of Tickless Sleep Mode is around 28uA to 30uA compare to normal state around 15mA. This example describes how to use freertos tickless with uart interruptable interface.
“File” -> “Examples” -> “AmebaPowerSave” -> “TicklessMode”
DS_WAKEUP_SOURCE
is used to set the wake-up source, user can chose 3
wake up sources now,AON timer (SET_DS_AON_TIMER_WAKEUP);
AON pins (SET_DS_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON timer can be set from 0 to 32760000 range (unit ms) by
AON_TIMER_SLEEP_DURATION
There are 4 pins can be set as AON pins and active high for wake-up,
D16, D17, D26 and D27. The AON pin can be set by
SET_DS_AON_WAKEPIN_WAKEUPPIN
RTC timer wake-up system by set alarm. The alarm has 4 values, day,
hour, min and sec. All 4 values can be set by DS_RTC_ALARM_DAY
,
DS_RTC_ALARM_HOUR
, DS_RTC_ALARM_MIN
, and DS_RTC_ALARM_SEC
There are 4 pins can be set as AON pins and active high for wake-up,
D16, D17, D26 and D27. The AON pin can be set by
SET_TL_AON_WAKEPIN_WAKEUP
TL_SYSACTIVE_TIME
is for setting time duration of the system to keep
alive. (unit ms)
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
Use NTPClient Library To Obtain Local Time
Preparation
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
In this example, we use an NTP client to sync with NTP
servers using UDP and keep track of time locally.
Open the example.
“File” -> “Examples”-> “NTPClient” -> “Advanced”
Code Reference
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000);
begin()
function, which causes the client to sync with the NTP
server and get the UTC time.WiFiUDP ntpUDP;
timeClient.begin();
getFormattedTime()
is used to format the received UTC
time into the local time zone. update()
is called every loop so that the
NTPClient will sync with the NTP server once every update interval.timeClient.update();
timeClient.getFormattedTime();
Transmit IR NEC Raw Data And Decode
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 2
Grove – Infrared Emitter x1 (Figure 1)
Grove – Infrared Receiver x1 (Figure 2)
Example
In this example, we use two Ameba RTL8722 modules that connecting with an infrared (IR) Emitter and an IR Receiver separately to transmit and receive IR NEC Raw data.
For more details, please refer to SB-Projects’ topic of IR Remote Control Theory to learn the theory of IR remote controls operation and a collection of IR protocol descriptions. In this example, we are going to use NEC (Now Renesas, also known as Japanese Format) as the transmission protocol.
8-bit address and 8-bit command length.
Extended mode available, doubling the address size.
Address and command are transmitted twice for reliability.
Pulse distance modulation.
The carrier frequency of 38kHz.
Bit time of 1.125ms or 2.25ms.
Since a total number of 32-bit data together with the header and the end-bit will be transferred (Figure 5). If we separate the data in the time-frame (in us), there will be ( 2 + 32 ) x 2 + 1 = 69 “marks” / “spaces” to be transmitted (Figure 6), which forms the raw NEC data we would like to transmit in our Arduino “*.ino” file. This part of the code can be modified by users. Details of how to obtain raw data code for your remote devices, you may refer to Ken Shirriff’s blog, where it provides multiple libraries provided online.
Figure 7 and 8 shows the pin configuration of IR Emitter and Receiver with Ameba RTL8722 board.
Figure 9 and Figure 10 shows the pin configuration of IR Emitter and Receiver with Ameba RTL8722DM MINI.
After the connection is being set up correctly, we will move to the coding part for this example. First, make sure the correct Ameba development board is selected in Arduino IDE: “Tools” -> “Board”.
Open the “IRSendRAW” example in “File” -> “Examples” -> “AmebaIRDevice”
-> “IRSendRAW”
(Figure 11) and upload to 1st board connected with IR
Emitter:
After successfully upload the sample code for IRSendRaw, you might need
to upload the IRRecvNEC example for the 2nd board connected with IR
Receiver from “File” -> “Examples” -> “AmebaIRDevice” -> “IRRecvNEC”
.
After opening the serial monitor on the IR Receiver side and press the reset buttons on two boards, the data “48” will be received every 3 seconds (due to the delays () function, not compulsory to wait). After decoding the signal from the receiving Pin D8 and transmitting Pin D9 with Logic Analyser and Pulse View (Figure 10), the result is also shown as “48” after decoding the receiving data with IR NEC Protocol.
Code Reference
A Simple RTC Example
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
This example demonstrates how to use the RTC library methods. This function describes how to use the RTC API. The RTC function is implemented by an independent BCD timer/counter.
"File" -> "Examples" -> "AmebaRTC" -> "RTC"
:Upon successfully upload the sample code and press the reset button, this example will print out time information since the user initialized time every second in the Serial Monitor.
Code Reference
A Simple RTC Alarm
Materials
AmebaD [RTL8722DM / RTL8722CSM / RTL8722DM MINI] x 1
Example
This example demonstrates how to use the RTC library methods to create a RTC Alarm, so that to do some tasks when an alarm is matched. In particular, the RTC time is set at 16:00:00 and an alarm at 16:00:10. When the time matches, “Alarm Match” information will be printed on the serial monitor.
First, select the correct Ameba development board from the Arduino IDE: “Tools” -> “Board”.
Then open the 「RTCAlarm」 example from:
“File” -> “Examples” -> “RTC” -> “RTCAlarm”
:
In the example, the RTC time is set at 16:00:00 and an alarm is set at 16:00:10. Upon successfully upload the sample code and press the reset button. When the alarm time (10 seconds) is reached the attached interrupt function will print the following information: “Alarm Matched!” showing in this figure below.
Watchdog Timer Simple Example
Preparation
AmebaD RTL8722CSM/RTL8722DM/RTL8722DM MINI Board x 1
Example
In this example, we will use this simple watchdog timer example runs on the Ameba RTL8722 module to illustrate how to use the watchdog API. Before we get into the details of the example, let’s briefly go through the definition of Watchdog as well as it’s working principles.
Watchdog
Watchdog Timer (WDT) is a hardware timer that is used to detect the occurrence of a software fault, then automatically generates a system reset or a watchdog interrupt on the expiry of a programmed period.
In layman terms, imagine in the situation while your micro-controller is confused in an infinity loop, or any case like the micro-controller hang while performing some tasks. The normal troubleshooting method would be to press the reset button and jump out of the infinity loop. However, is it practically impossible to do press on the button all time, therefore, the watchdog timer that embedded inside the micro-controller would help with this situation.
Feed the Dog
“Tools” -> “Board” -> “RTL8722CSM/RTL8722DM” (or “RTL8722DM MINI”)
.
Then open the “Watchdog Timer” example in “File” -> “Examples” -> “AmebaWatchdog” ->
“Watchdog Timer”
:API Documents
RTL8722DM ARDUINO Online API Documents
Analog
Class AmebaServo
Description
Defines a class of manipulating servo motors connected to Arduino pins.
Syntax
class AmebaServo
Members
Public Constructors |
|
---|---|
AmebaServo::AmebaServo |
Constructs an AmebaServo object. |
Public Methods |
|
AmebaServo::attach |
Attach the given pin to the next free channel. |
AmebaServo::detach |
Detach the servo. |
AmebaServo::write |
Write value, if the value is < 200 it’s treated as an angle, otherwise as pulse-width in microseconds. |
AmebaServo::writeMicroseconds |
Write pulse width in microseconds. |
AmebaServo::read |
Output current pulse width as an angle between 0 and 180 degrees. |
AmebaServo::readMicroseconds |
Output current pulse width in microseconds for this servo. |
AmebaServo::attached |
Check if the servo is attached. |
Description
Attach the given pin to the next free channel, sets pinMode (including minimum and maximum values for writes), returns channel number, or 0 if failure.
Syntax
uint8_t attach(int pin);
uint8_t attach(int pin, int min, int max);
Parameters
pin: The Arduino pin number to be attached.
min: Minimum values for writes.
max: Maximum values for writes.
Returns
The function returns channel number or 0
Example Code
Example: ServoSweep
The code demos servo motor sweeping from 0 degrees to 180 degrees then sweep back to 0 degrees in the step of 1 degree.
1 /* Sweep
2 by BARRAGAN < http://barraganstudio.com >
3 This example code is in the public domain.
4 modified 8 Nov 2013
5 by Scott Fitzgerald
6 http://www.arduino.cc/en/Tutorial/Sweep
7 refined 2016/03/18 by Realtek
8 */
9
10 #include "AmebaServo.h"
11
12 // create servo object to control a servo
13 // 4 servo objects can be created correspond to PWM pins
14
15 AmebaServo myservo;
16
17 // variable to store the servo position
18 int pos = 0;
19
20 void setup() {
21 #if defined(BOARD_RTL8195A)
22 // attaches the servo on pin 9 to the servo object
23 myservo.attach(9);
24 #elif defined(BOARD_RTL8710)
25 // attaches the servo on pin 13 to the servo object
26 myservo.attach(13);
27 #elif defined(BOARD_RTL8721D)
28 // attaches the servo on pin 8 to the servo object
29 myservo.attach(8);
30 #else
31 // attaches the servo on pin 9 to the servo object
32 myservo.attach(9);
33 #endif
34 }
35
36 void loop() {
37 // goes from 0 degrees to 180 degrees in steps of 1 degree
38 for (pos = 0; pos <= 180; pos += 1) {
39 // tell servo to go to position in variable 'pos'
40 myservo.write(pos);
41 // waits 15ms for the servo to reach the position
42 delay(15);
43 }
44 // goes from 180 degrees to 0 degrees
45 for (pos = 180; pos >= 0; pos -= 1) {
46 // tell servo to go to position in variable 'pos'
47 myservo.write(pos);
48 // waits 15ms for the servo to reach the position
49 delay(15);
50 }
51 }
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
Description
Detach the servo.
Syntax
void AmebaServo::detach(void);
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AmebaServo::write
Description
Write an integer value to the function, if the value is < 200, it’s being treated as an angle, otherwise as pulse-width in microseconds.
Syntax
void AmebaServo::write(int value);
Parameters
value: The value < 200 its treated as an angle; otherwise as pulse width in microseconds.
Returns
The function returns nothing.
Example Code
Example: ServoSweep
The code demos servo motor sweeping from 0 degrees to 180 degrees then sweep back to 0 degrees in the step of 1 degree. Please refer to code in “AmebaServo:: attach” section.
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AmebaServo::writeMicroseconds
Description
Write pulse width to the servo in microseconds.
Syntax
void AmebaServo::writeMicroseconds(int value);
Parameters
value: Write value the pulse width in microseconds.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AmebaServo::read
Description
The function reads current pulse width and returns as an angle between 0 and 180 degrees.
Syntax
int AmebaServo::read(void);
Parameters
The function requires no input parameter.
Returns
The pulse width as an angle between 0 ~ 180 degrees.
Example Code
NA
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AmebaServo::readMicroseconds
Description
The function returns a Boolean value “true” if this servo is attached, otherwise returns “false”.
Syntax
int AmebaServo::readMicroseconds(void);
Parameters
The function requires no input parameter.
Returns
The function returns current servo pulse width in microseconds.
Example Code
NA
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AmebaServo::attached
Description
It returns true if this servo is attached, otherwise false.
Syntax
bool AmebaServo::attached(void);
Parameters
The function requires no input parameter.
Returns
The function returns a Boolean value as true or false.
Example Code
Example: ServoSweep
The code demos servo motor sweeping from 0 degrees to 180 degrees then sweep back to 0 degrees in the step of 1 degree. Please refer to code in “AmebaServo:: attach” section.
Notes and Warnings
Every time must include the header file “AmebaServo.h” in front of the project to use the class function.
AudioCodec
Class AudioCodec
Description
A class used for general control and management of the hardware audio codec functions.
Syntax
class AudioCodec
Members
Public Constructors
The public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named Codec.
Public Methods
AudioCodec::begin |
Configure and start the audio codec for transmit and receive operation |
---|---|
AudioCodec::end |
Stop all audio codec operation |
AudioCodec::getBufferPageSize |
Get the byte size of a single page of the audio codec buffer |
AudioCodec::setSampleRate |
Configure the audio codec transmit and receive sampling rate |
AudioCodec::setBitDepth |
Configure the audio codec transmit and receive bit depth (bits per sample) |
AudioCodec::setChannelCount |
Configure the audio codec transmit and receive channel count |
AudioCodec::setInputMicType |
Configure for analog or digital input microphone type |
AudioCodec::setInputLRMux |
Configure input left right channel multiplexing |
AudioCodec::setDMicBoost |
Configure boost gain for digital microphone input |
AudioCodec::setAMicBoost |
Configure boost gain for analog microphone input |
AudioCodec::setADCGain |
Configure gain of ADC used to acquire analog input |
AudioCodec::muteInput |
Mute input audio data stream |
AudioCodec::setOutputVolume |
Configure output audio volume |
AudioCodec::muteOutput |
Mute output audio |
AudioCodec::writeAvaliable |
Check for free buffer page available for data write |
AudioCodec::writeDataPage |
Write audio data to an available buffer page |
AudioCodec::readAvaliable |
Check for buffer page with new data available for read |
AudioCodec::readDataPage |
Read audio data from a ready buffer page |
AudioCodec::setWriteCallback |
Set a callback function to be notified when a free buffer page is available for write |
AudioCodec::setReadCallback |
Set a callback function to be notified when a buffer page with new data is available for read |
AudioCodec::begin
Description
Configure and start the audio codec for transmit and receive operation.
Syntax
void begin(bool input, bool output);
Parameters
input: enable audio codec data input
output: enable audio codec data output
Returns
The function returns nothing.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::end
Description
Stop all audio codec operation.
Syntax
void end();
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
AudioCodec::getBufferPageSize
Description
Get the byte size of a single page of the audio codec buffer.
Syntax
uint32_t getBufferPageSize();
Parameters
The function requires no input parameter.
Returns
The size of a audio codec buffer page, in number of bytes.
Example Code
NA
Notes and Warnings
The AudioCodec class includes a transmit and receive buffer to store audio sample data while transferring to and from the DAC output and ADC input. The buffer is divided into pages of fixed size, and audio data can be read and written one page at a time. Depending on the configured bit depth (bits per audio sample) and channel count, a buffer page may contain a different number of audio samples.
AudioCodec::setSampleRate
Description
Configure the audio codec transmit and receive sampling rate.
Syntax
void setSampleRate(uint32_t sampleRate);
Parameters
sampleRate: desired audio codec sampling rate in Hz. Default value of 48000. Supported values: 8000, 16000, 32000, 44100, 48000, 88200, 96000.
Returns
The function returns nothing.
Example Code
Example: BasicInputOutput
Notes and Warnings
High sample rates above 48000Hz will require frequent buffer reads and writes to keep up with the large amount of data input and output. If there is insufficient processing time dedicated to this task, audio quality will be degraded.
AudioCodec::setBitDepth
Description
Configure the audio codec transmit and receive bit depth (bits per sample).
Syntax
void setBitDepth(uint8_t bitDepth);
Parameters
bitDepth: desired number of bits per sample. Default value of 16. Supported values: 8, 16, 24.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Setting a bit depth of 24 bits per sample will require 32 bits (4 bytes) of buffer space for storing each sample, with the most significant byte ignored.
AudioCodec::setChannelCount
Description
Configure the audio codec transmit and receive channel count.
Syntax
void setChannelCount(uint8_t monoStereo);
Parameters
monoStereo: number of channels. Default value of 1. Supported values: 1, 2.
Returns
The function returns nothing.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::setInputMicType
Description
Configure for analog or digital input microphone type.
Syntax
Void setInputMicType(Mic_Type micType);
Parameters
micType: Input microphone type. Default value ANALOGMIC. Valid values:
ANALOGMIC – microphone with an analog output
PDMMIC – digital microphone with a PDM output
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
For analog single-ended output, connect to PA_4 for the left channel and PA_2 for the right channel.
For digital PDM output, connect the PDM clock to PB_1 and PDM data to PB_2.
AudioCodec::setInputLRMux
Description
Configure input left right channel multiplexing.
Syntax
void setInputLRMux(uint32_t mux);
Parameters
mux: desired left right audio channel multiplexing setting. Default value RX_CH_LR. Valid values:
RX_CH_LR
RX_CH_RL
RX_CH_LL
RX_CH_RR
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
In mono channel mode, both RX_CH_LR and RX_CH_LL will result in the audio codec sampling input data from the left channel microphone. Similarly, both RX_CH_RL and RX_CH_RR will result in the audio codec sampling input data from the right channel microphone.
In stereo channel mode, RX_CH_RL will switch the positions of input data sampled from the microphones. RX_CH_RR and RX_CH_LL will result in duplicated samples from the right and left microphones respectively.** **
AudioCodec::setDMicBoost
Description
Configure boost gain for digital microphone input.
Syntax
void setDMicBoost(uint32_t leftBoost, uint32_t rightBoost);
Parameters
leftBoost: boost gain for left channel digital microphone input
rightBoost: boost gain for right channel digital microphone input
Valid boost gain values:
0 : 0dB
1 : 12dB
2 : 24dB
3 : 36dB
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
AudioCodec::setAMicBoost
Description
Configure boost gain for analog microphone input.
Syntax
void setAMicBoost(uint32_t leftBoost, uint32_t rightBoost);
Parameters
leftBoost: boost gain for left channel analog microphone input
rightBoost: boost gain for right channel analog microphone input
Valid boost gain values:
0 : 0dB
1 : 20dB
2 : 30dB
3 : 40dB
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Only use this function if additional gain is required after using setADCGain function.
AudioCodec::setADCGain
Description
Configure gain of ADC used to acquire analog input.
Syntax
void setADCGain(uint32_t leftGain, uint32_t rightGain);
Parameters
leftGain: Gain for left channel ADC
rightGain: Gain for right channel ADC
Valid value range is from 0x00 to 0x7f. Gain increases by 0.375dB for every increment in value:
0x00 : -17.625dB
0x01 : -17.25dB
0x2f : 0dB
0x30 : 0.375dB
0x7f : 30dB
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
AudioCodec::muteInput
Description
Mute input audio data stream.
Syntax
void muteInput(uint8_t leftMute, uint8_t rightMute);
Parameters
leftMute: 1 to mute left channel input, 0 to unmute
rightMute: 1 to mute right channel input, 0 to unmute
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
AudioCodec::setOutputVolume
Description
Configure output audio volume.
Syntax
void setOutputVolume(uint8_t leftVol, uint8_t rightVol);
Parameters
leftVol: left channel output volume
rightVol: right channel output volume
Valid value ranges from 0 to 100, corresponding to a volume of -65.625dB to 0dB.
Returns
The function returns nothing.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::muteOutput
Description
Mute output audio.
Syntax
void muteOutput(uint8_t leftMute, uint8_t rightMute);
Parameters
leftMute: 1 to mute left channel output, 0 to unmute
rightMute: 1 to mute right channel output, 0 to unmute
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
AudioCodec::writeAvaliable
Description
Check for free buffer page available for data write.
Syntax
bool writeAvaliable();
Parameters
The function requires no input parameter.
Returns
Returns true if there is a buffer page that is available for writing data into. Returns false if all buffer pages are full.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::writeDataPage
Description
Write audio data to an available buffer page.
Syntax
uint32_t writeDataPage(int8_t* src, uint32_t len);
uint32_t writeDataPage(int16_t* src, uint32_t len);
Parameters
src: pointer to array containing audio samples to write to audio codec.
len: number of audio samples in array.
Returns
The function returns the number of audio samples written to the audio codec.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::readAvaliable
Description
Check for buffer page with new data available for read.
Syntax
bool readAvaliable();
Parameters
The function requires no input parameter.
Returns
Returns true if there is a buffer page with new data that is ready for reading data from. Returns false if all buffer pages are empty.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::readDataPage
Description
Read audio data from a ready buffer page.
Syntax
uint32_t readDataPage(int8_t* dst, uint32_t len);
uint32_t readDataPage(int16_t* dst, uint32_t len);
Parameters
dst: pointer to array to contain audio samples read from audio codec.
len: number of audio samples to read.
Returns
The function returns the number of audio samples read from the audio codec.
Example Code
Example: BasicInputOutput
Notes and Warnings
AudioCodec::setWriteCallback
Description
Set a callback function to be notified when a free buffer page is available for write.
Syntax
void setWriteCallback(void (writeCB)(**void*));
Parameters
writeCB: function to be called when a buffer page becomes available for data write. Takes no arguments and returns nothing
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
After starting the audio codec with AudioCodec::begin(), the callback function will be called each time the audio codec finishes outputting the data in a buffer page.
AudioCodec::setReadCallback
Description
Set a callback function to be notified when a buffer page with new data is available for read.
Syntax
void setReadCallback(void (readCB)(**void*));
Parameters
readCB: function to be called when a buffer page with new data becomes available for data read. Takes no arguments and returns nothing
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
After starting the audio codec with AudioCodec::begin(), the callback function will be called each time the audio codec fills up a buffer page with newly acquired audio samples.
Class FFT
Description
A class used for performing FFT calculations with real-number inputs and outputs.
Syntax
class FFT
Members
Public Constructors
FFT::FFT |
Create an instance of the FFT class |
Public Methods
FFT::setWindow |
Configure the window function used in FFT calculations |
---|---|
FFT::calculate |
Calculate FFT for an input array of values |
FFT::getFrequencyBins |
Get the FFT output frequency bins |
FFT::getFFTSize |
Get the size of FFT output for a given input size |
FFT::FFT
Description
Create a FFT class object.
Syntax
void FFT();
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
Example: FFT
Notes and Warnings
FFT::setWindow
Description
Configure the window function used in FFT calculations.
Syntax
void setWindow(FFTWindow_t window, uint16_t sampleCount);
Parameters
window: The window function to be used in FFT calculations. Valid values: None, Hann, Hamming.
sampleCount: Number of sample datapoints in the input.
Returns
The function returns nothing.
Example Code
Example: FFT
Notes and Warnings
The window function is used to reduce the effects of discontinuities that occur when the input signal has frequencies that do not fit an integer number of periods in the sample datapoints.
More information on FFTs and window functions can be seen at:
https://download.ni.com/evaluation/pxi/Understanding%20FFTs%20and%20Windowing.pdf
https://en.wikipedia.org/wiki/Window_function
FFT::Calculate
Description
Calculate FFT for an input array of values.
Syntax
void calculate(float* inputBuf, float* outputBuf, uint16_t sampleCount);
void calculate(int16_t* inputBuf, float* outputBuf, uint16_t sampleCount);
Parameters
inputBuf: pointer to an array of sampleCount size, containing input sample datapoints, in float or uint16_t format.
outputBuf: pointer to a float array of sampleCount/2 size, for containing FFT output.
sampleCount: number of sample datapoints in the input array, valid values: 16, 32, 64, 128, 256, 512, 1024, 2048.
Returns
The function returns nothing.
Example Code
Example:FFT
Notes and Warnings
Large sample counts will require a longer time for FFT calculations, but will also return a result with higher frequency resolution.
FFT::getFrequencyBins
Description
Get the FFT output frequency bins.
Syntax
void getFrequencyBins(uint16_t* outputBuf, uint16_t sampleCount, uint32_t sampleRate);
Parameters
outputBuf: pointer to a uint16_t array of sampleCount/2 size, for containing the calculated center frequency of each FFT output element.
Returns
The function returns nothing.
Example Code
Example: FFT
Notes and Warnings NA
—
FFT::getFFTSize
Description
Get the size of FFT output for a given input size.
Syntax
uint16_t getFFTSize(uint16_t sampleCount);
Parameters
sampleCount: number of input sample datapoints.
Returns
The function returns the FFT output size for the given sampleCount, which is sampleCount/2.
Example Code
NA
Notes and Warnings NA
Class PlaybackWav
Description
A class used for control and playback of .wav file format audio data.
Syntax
class PlaybackWav
Members
Public Constructors
PlaybackWav::PlaybackWav |
Create an instance of the PlaybackWav class |
Public Methods
PlaybackWav::openFile |
Open a .wav file for playback |
PlaybackWav::closeFile |
Close a previously opened file |
PlaybackWav::fileOpened |
Check if a .wav file is already opened |
PlaybackWav::getSampleRate |
Get the sample rate of the .wav file |
PlaybackWav::getChannelCount |
Get the number of audio channels in the .wav file |
PlaybackWav::getBitDepth |
Get the bit depth of each sample in the .wav file |
PlaybackWav::getLengthMillis |
Get the playback length of the .wav file in milliseconds |
PlaybackWav::getPositionMillis |
Get the current playback position in milliseconds |
PlaybackWav::setPositionMillis |
Set the current playback position in milliseconds |
PlaybackWav::millisToBytes |
Convert a playback duration to equivalent number of bytes |
PlaybackWav::bytesToMillis |
Convert number of bytes to an equivalent playback duration |
PlaybackWav::readAudioData |
Read audio data from the .wav file |
PlaybackWav::PlaybackWav
Description
Create a PlaybackWav class object.
Syntax
void PlaybackWav(void);
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
PlaybackWav::fileOpened
Description
Check if a .wav file is already opened.
Syntax
bool fileOpened(void);
Parameters
The function requires no input parameter.
Returns
The function returns true if a .wav file is already open, false otherwise.
Example Code
Example: RecordPlaybackWav
Notes and Warnings
NA
PlaybackWav::getSampleRate
Description
Get the sample rate of the .wav file.
Syntax
uint32_t getSampleRate(void);
Parameters
The function requires no input parameter.
Returns
The function returns sampling rate encoded in the .wav file header.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
PlaybackWav::getChannelCount
Description
Get the number of audio channels in the .wav file.
Syntax
uint16_t getChannelCount(void);
Parameters
The function requires no input parameter.
Returns
The function returns channel count encoded in the .wav file header.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
PlaybackWav::getBitDepth
Description
Get the bit depth of each sample in the .wav file.
Syntax
uint16_t getBitDepth(void);
Parameters
The function requires no input parameter.
Returns
The function returns bit depth encoded in the .wav file header.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
PlaybackWav::getLengthMillis
Description
Get the playback length of the .wav file in milliseconds.
Syntax
uint32_t getLengthMillis(void);
Parameters
The function requires no input parameter.
Returns
The function returns the total playback length of the currently open .wav file in milliseconds.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
PlaybackWav::getPositionMillis
Description
Get the current playback position in milliseconds.
Syntax
uint32_t getPositionMillis(void);
Parameters
The function requires no input parameter.
Returns
The function returns the current playback position of the currently open .wav file in milliseconds.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
PlaybackWav::setPositionMillis
Description
Set the current playback position in milliseconds.
Syntax
void setPositionMillis(uint32_t pos);
Parameters
pos: The desired playback position expressed in milliseconds.
Returns
The function returns nothing.
Example Code
Example: PlaybackWavFile
Notes and Warnings
Any changes to playback position will only take effect on the next call to PlaybackWav::readAudioData. If the desired playback position is beyond the total playback length of the file, the playback position will be set to the end of file, and no audio data will be output on subsequent data reads.
PlaybackWav::millisToBytes
Description
Convert a playback duration to equivalent number of bytes.
Syntax
uint32_t millisToBytes(uint32_t ms);
Parameters
ms: playback duration in milliseconds.
Returns
The function returns the number of bytes that is equivalent to the input playback duration, converted using the current sample rate, number of channels and bit depth.
Example Code
NA
Notes and Warnings
NA
PlaybackWav::bytesToMillis
Description
Convert number of bytes to an equivalent playback duration.
Syntax
uint32_t bytesToMillis(uint32_t bytes);
Parameters
bytes: playback duration in number of bytes.
Returns
The function returns the time duration in milliseconds that is equivalent to the input number of bytes, converted using the current sample rate, number of channels and bit depth.
Example Code
NA
Notes and Warnings
NA
PlaybackWav::readAudioData
Description
Read audio data from the .wav file.
Syntax
uint32_t readAudioData(int8_t* dst, uint32_t len);
uint32_t readAudioData(int16_t* dst, uint32_t len);
Parameters
dst
: pointer to array to store data read from .wav file.
len
: number of audio samples to read from .wav file.
Returns
The function returns number of audio samples read.
Example Code
Example: PlaybackWavFile
Notes and Warnings
NA
Class RecordWav
Description
A class used for control and recording of .wav file format audio data.
Syntax
class RecordWav
Members
Public Constructors
RecordWav:: RecordWav |
Create an instance of the RecordWav class |
Public Methods
RecordWav::openFile |
Open a .wav file for playback |
RecordWav::closeFile |
Close a previously opened file |
RecordWav::fileOpened |
Check if a .wav file is already opened |
RecordWav::setSampleRate |
Get the sample rate of the .wav file |
RecordWav::setChannelCount |
Set the number of audio channels in the .wav file |
RecordWav::setBitDepth |
Set the bit depth of each sample in the .wav file |
RecordWav::getLengthMillis |
Get the current record length of the .wav file in milliseconds |
RecordWav::millisToBytes |
Convert a playback duration to equivalent number of bytes |
RecordWav::bytesToMillis |
Convert number of bytes to an equivalent playback duration |
RecordWav::writeAudioData |
Write audio data to the .wav file |
RecordWav::RecordWav
Description
Create a RecordWav class object.
Syntax
void RecordWav(void);
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
Example: RecordWavFile
Notes and Warnings
NA
RecordWav::openFile
Description
Open a .wav file for recording.
Syntax
void openFile(const char* absFilepath);
Parameters
absFilepath: the filepath of the .wav file to open.
Returns
The function returns nothing.
Example Code
Example: RecordWavFile
Notes and Warnings
NA
RecordWav::closeFile
Description
Close a previously opened file.
Syntax
void closeFile(void);
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
Example: RecordWavFile
Notes and Warnings
Any open .wav files should be closed after recording is complete, otherwise, loss of recorded audio data may occur.
RecordWav::fileOpened
Description
Check if a .wav file is already opened.
Syntax
bool fileOpened(void);
Parameters
The function requires no input parameter.
Returns
The function returns true if a .wav file is already open, false otherwise.
Example Code
Example: RecordWavFile
Notes and Warnings
NA
RecordWav::setSampleRate
Description
Set the recording sample rate of the .wav file.
Syntax
void setSampleRate(uint32_t sampleRate);
Parameters
sampleRate: The desired recording sample rate.
Returns
The function returns nothing.
Example Code
Example: RecordWavFile
Notes and Warnings
NA
RecordWav::setChannelCount
Description
Set the number of recording audio channels in the .wav file.
Syntax
void setChannelCount(uint16_t channelCount);
Parameters
channelCount: number of recording audio channels.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
RecordWav::setBitDepth
Description
Set the recording bit depth of each sample in the .wav file.
Syntax
void setBitDepth(uint16_t bitDepth);
Parameters
bitDepth: number of bits per sample.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
RecordWav::getLengthMillis
Description
Get the current recorded length of the .wav file in milliseconds.
Syntax
uint32_t getLengthMillis(void);
Parameters
The function requires no input parameter.
Returns
The function returns the current recorded length of the currently open .wav file in milliseconds.
Example Code
NA
Notes and Warnings
NA
RecordWav::millisToBytes
Description
Convert a playback duration to equivalent number of bytes.
Syntax
uint32_t millisToBytes(uint32_t ms);
Parameters
ms: playback duration in milliseconds.
Returns
The function returns the number of bytes that is equivalent to the input playback duration, converted using the current sample rate, number of channels and bit depth.
Example Code
NA
Notes and Warnings
NA
RecordWav::bytesToMillis
Description
Convert number of bytes to an equivalent playback duration.
Syntax
uint32_t bytesToMillis(uint32_t bytes);
Parameters
bytes: playback duration in number of bytes.
Returns
The function returns the time duration in milliseconds that is equivalent to the input number of bytes, converted using the current sample rate, number of channels and bit depth.
Example Code
NA
Notes and Warnings
NA
RecordWav::writeAudioData
Description
Write audio data to the .wav file.
Syntax
uint32_t writeAudioData(int8_t* src, uint32_t len); uint32_t writeAudioData(int16_t* src, uint32_t len);
Parameters
src: pointer to array containing data to write to .wav file. len: number of audio samples to write to .wav file.
Returns
The function returns number of audio samples written.
Example Code
Example: RecordWavFile
Notes and Warnings
NA
BLE
Class BLEAddr
BLEAddr Class
Description
A class used for managing Bluetooth addresses.
Members
Public Constructors |
|
---|---|
BLEAddr::BLEAddr |
Constructs a BLEAddr object |
Public Methods |
|
BLEAddr::str |
Get the Bluetooth address represented as a formatted string |
BLEAddr::data |
Get the Bluetooth address represented as an integer array |
BLEAddr::BLEAddr
BLEAddr::str
BLEAddr::data
Class BLEAdvert
BLEAdvert Class
Members
Public Constructors |
---|
No public constructor is available as this class is intended to be a singleton class. You can get a pointer to this class using BLEDevice::configAdvert(). |
Public Methods |
|
---|---|
BLEAdvert::updateAdvertParams |
Update the current BLE advertisement settings to the lower Bluetooth stack |
BLEAdvert::startAdv |
Start BLE advertising |
BLEAdvert::stopAdv |
Stop BLE advertising |
BLEAdvert::setAdvType |
Set the BLE advertising type |
BLEAdvert::setMinInterval |
Set the BLE advertising minimum interval |
BLEAdvert::setMaxInterval |
Set the BLE advertising maximum interval |
BLEAdvert::setAdvData |
Set BLE advertising data |
BLEAdvert::setScanRspData |
Set BLE scan response data |
BLEAdvert::updateAdvertParams
BLEAdvert::startAdv
BLEAdvert::stopAdv
BLEAdvert::setAdvType
BLEAdvert::setMinInterval
BLEAdvert::setMaxInterval
BLEAdvert::setAdvData
BLEAdvert::setScanRspData
Class BLEAdvertData
BLEAdvertData Class
Members
Public Constructors |
|
---|---|
BLEAdvertData::BLEAdvertData |
Constructs a BLEAdvertData object |
Public Methods |
|
---|---|
BLEAdvertData::clear |
Clear all advertising data |
BLEAdvertData::addData |
Add binary advertising data |
BLEAdvertData::addFlags |
Add flags to advertising data |
B LEAdvertData::addPartialServices |
Add partial services to advertising data |
BL EAdvertData::addCompleteServices |
Add complete services to advertising data |
BLEAdvertData::addAppearance |
Add device appearance to advertising data |
BLEAdvertData::addShortName |
Add short device name to advertising data |
BLEAdvertData::addCompleteName |
Add complete device name to advertising data |
BLEAdvertData::parseScanInfo |
Parse advertising data received from a scan |
BLEAdvertData::hasFlags |
Check if received data includes advertising flags |
BLEAdvertData::hasUUID |
Check if received data includes UUIDs |
BLEAdvertData::hasName |
Check if received data includes device name |
BLEAdvertData::hasManufacturer |
Check if received data includes manufacturer data |
BLEAdvertData::getAdvType |
Get advertising type of received data |
BLEAdvertData::getAddrType |
Get Bluetooth address type of received data |
BLEAdvertData::getAddr |
Get Bluetooth address of received data |
BLEAdvertData::getRSSI |
Get RSSI of received data |
BLEAdvertData::getFlags |
Get advertising flags of received data |
BLEAdvertData::getServiceCount |
Get number of advertised services in received data |
BLEAdvertData::getServiceList |
Get array of advertised services in received data |
BLEAdvertData::getName |
Get advertised device name in received data |
BLEAdvertData::getTxPower |
Get advertised transmission power in received data |
BLEAdvertData::getAppearance |
Get advertised device appearance in received data |
BLEAdvertData::getManufacturer |
Get advertised manufacturer in received data |
BLEAdver tData::getManufacturerDataLength |
Get length of manufacturer data in received data |
BL EAdvertData::getManufacturerData |
Get advertised manufacturer data in received data |
BLEAdvertData::BLEAdvertData
BLEAdvertData::clear
BLEAdvertData::addData
BLEAdvertData::addFlags
BLEAdvertData::addPartialServices
BLEAdvertData::addCompleteServices
BLEAdvertData::addAppearance
BLEAdvertData::addShortName
BLEAdvertData::addCompleteName
BLEAdvertData::parseScanInfo
BLEAdvertData::hasFlags
BLEAdvertData::hasUUID
BLEAdvertData::hasName
BLEAdvertData::hasManufacturer
BLEAdvertData::getAdvType
BLEAdvertData::getAddrType
BLEAdvertData::getRSSI
BLEAdvertData::getFlags
BLEAdvertData::getServiceCount
BLEAdvertData::getServiceList
BLEAdvertData::getName
BLEAdvertData::getTxPower
BLEAdvertData::getAppearance
BLEAdvertData::getManufacturer
BLEAdvertData::getManufacturerDataLength
BLEAdvertData::getManufacturerData
Class BLEBeacon
iBeacon Class
Members
Public Constructors |
|
---|---|
iBeacon::iBeacon |
Create an instance of iBeacon advertising data |
Public Methods |
|
iBeacon::getManufacturerId |
Get current manufacturer ID value |
iBeacon::getUUID |
Get current UUID value |
iBeacon::getMajor |
Get current Major value |
iBeacon::getMinor |
Get current Minor value |
iBeacon::getRSSI |
Get current RSSI value |
iBeacon::setManufacturerId |
Set manufacturer ID value |
iBeacon::setUUID |
Set UUID value |
iBeacon::setMajor |
Set Major value |
iBeacon::setMinor |
Set Minor value |
iBeacon::setRSSI |
Set RSSI value |
iBeacon::getAdvData |
Get current advertising data |
iBeacon::getScanRsp |
Get current scan response data |
altBeacon Class
Members
Public Constructors |
|
---|---|
altBeacon::altBeacon |
Create an instance of altBeacon advertising data |
Public Methods |
|
altBeacon::getManufacturerId |
Get current manufacturer ID value |
altBeacon::getUUID |
Get current UUID value |
altBeacon::getMajor |
Get current Major value |
altBeacon::getMinor |
Get current Minor value |
altBeacon::getRSSI |
Get current RSSI value |
altBeacon::getRSVD |
Get current Reserved value |
altBeacon::setManufacturerId |
Set manufacturer ID value |
altBeacon::setUUID |
Set UUID value |
altBeacon::setMajor |
Set Major value |
altBeacon::setMinor |
Set Minor value |
altBeacon::setRSSI |
Set RSSI value |
altBeacon::setRSVD |
Set Reserved value |
altBeacon::getAdvData |
Get current advertising data |
altBeacon::getScanRsp |
Get current scan response data |
iBeacon::iBeacon
altBeacon::altBeacon
iBeacon::getManufacturerId
altBeacon::getManufacturerId
iBeacon::getUUID
altBeacon::getUUID
iBeacon::getMajor
altBeacon::getMajor
iBeacon::getMinor
altBeacon::getMinor
iBeacon::getRSSI
altBeacon::getRSSI
iBeacon::setManufacturerId
altBeacon::setManufacturerId
iBeacon::setUUID
altBeacon::setUUID
iBeacon::setMajor
altBeacon::setMajor
iBeacon::setMinor
altBeacon::setMinor
iBeacon::setRSSI
altBeacon::setRSSI
iBeacon::getAdvData
altBeacon::getAdvData
iBeacon::getScanRsp
altBeacon::getScanRsp
altBeacon::getRSVD
altBeacon::setRSVD
Class BLECharacteristic
BLECharacteristic Class
Description
A class used for creating and managing BLE GATT characteristics.
Members
Public Constructors |
|
---|---|
BLEC haracteristic::BLECharacteristic |
Constructs a BLECharacteristic object |
Public Methods |
|
BLECharacteristic::setUUID |
Set the characteristic UUID |
BLECharacteristic::getUUID |
Get the characteristic UUID |
BLECharacteristic::setBufferLen |
Set the size of the internal data buffer |
BLECharacteristic::getBufferLen |
Get the current size of the internal data buffer |
BL ECharacteristic::setReadProperty |
Get the current size of the internal data bufferSet the characteristic read property |
BLE Characteristic::setWriteProperty |
Set the characteristic write property |
BLEC haracteristic::setNotifyProperty |
Set the characteristic notify property |
BLECha racteristic::setIndicateProperty |
Set the characteristic indicate property |
BLECharacteristic::setProperties |
Set the characteristic properties |
BLECharacteristic::getProperties |
Get the characteristic properties |
BLECharacteristic::readString |
Read the characteristic data buffer as a String object |
BLECharacteristic::readData8 |
Read the characteristic data buffer as an unsigned 8-bit integer |
BLECharacteristic::readData16 |
Read the characteristic data buffer as an unsigned 16-bit integer |
BLECharacteristic::readData32 |
Read the characteristic data buffer as an unsigned 32-bit integer |
BLECharacteristic::writeString |
Write data to the characteristic data buffer as a String object or character array |
BLECharacteristic::writeData8 |
Write data to the characteristic data buffer as an unsigned 8-bit integer |
BLECharacteristic::writeData16 |
Write data to the characteristic data buffer as an unsigned 16-bit integer |
BLECharacteristic::writeData32 |
Write data to the characteristic data buffer as an unsigned 16-bit integer |
BLECharacteristic::setData |
Write data to the characteristic data buffer |
BLECharacteristic::getData |
Read data from the characteristic data buffer |
BLECharacteristic::getDataBuff |
Get a pointer to the characteristic data buffer |
BLECharacteristic::getDataLen |
Get the number of bytes of data in the characteristic data buffer |
BLECharacteristic::notify |
Send a notification to a connected device |
BLECharacteristic::indicate |
Send an indication to a connected device |
BLEC haracteristic::setUserDescriptor |
Add a user description descriptor to characteristic |
BLECha racteristic::setFormatDescriptor |
Add a data format descriptor to characteristic |
BLECharacteristic::Add a data format descriptor to characteristic |
Set a user function as a read callback |
BLE Characteristic::setWriteCallback |
Set a user function as a write callback |
BL ECharacteristic::setCCCDCallback |
Set a user function as a CCCD write callback |
BLECharacteristic::BLECharacteristic
BLECharacteristic::setUUID
BLECharacteristic::getUUID
BLECharacteristic::setBufferLen
BLECharacteristic::getBufferLen
BLECharacteristic::setReadProperty
BLECharacteristic::setWriteProperty
BLECharacteristic::setNotifyProperty
BLECharacteristic::setIndicateProperty
BLECharacteristic::setProperties
BLECharacteristic::getProperties
BLECharacteristic::readString
BLECharacteristic::readData8
BLECharacteristic::readData16
BLECharacteristic::readData32
BLECharacteristic::readData32
BLECharacteristic::writeData8
BLECharacteristic::writeData16
BLECharacteristic::writeData32
BLECharacteristic::setData
BLECharacteristic::getData
BLECharacteristic::getDataBuff
BLECharacteristic::getDataLen
BLECharacteristic::notify
BLECharacteristic::indicate
BLECharacteristic::setUserDescriptor
BLECharacteristic::setFormatDescriptor
BLECharacteristic::setReadCallback
BLECharacteristic::setWriteCallback
BLECharacteristic::setCCCDCallback
Class BLEClient
BLEClient Class
Members
Public Constructors |
---|
No public constructor is available for this class. You can get a pointer to an instance of this class using BLEDevice::addClient(). |
Public Methods |
|
---|---|
BLEClient::connected |
Check if the corresponding remote device for the client is connected |
BLEClient::discoverServices |
Start service discovery process for connected device |
BLEClient::discoveryDone |
Determine if service discovery process has been completed |
BLEClient::printServices |
Format and print discovered services to serial port |
BLEClient::getService |
Get a specific service on the remote device |
BLEClient::getConnId |
|
BLEClient::getClientId |
Get corresponding client ID |
BLEClient::setDisconnectCallback |
Set a user function to be called when the remote device is disconnected |
BLEClient::connected
BLEClient::discoverServices
BLEClient::discoveryDone
BLEClient::printServices
BLEClient::getService
BLEClient::getConnId
BLEClient::getClientId
BLEClient::setDisconnectCallback
Class BLEConnect
BLEConnect Class
Members
Public Constructors |
---|
No public constructor is available as this class is intended to be a singleton class. You can get a pointer to this class using BLEDevice::configConnection. |
Public Methods |
|
---|---|
BLEConnect::connect |
Connect to a target BLE device |
BLEConnect::disconnect |
Disconnect from a target BLE device |
BLEConnect::setScanInterval |
Set the BLE scanning interval when connecting |
BLEConnect::setScanWindow |
Set the BLE scanning window when connecting |
BLEConnect::setConnInterval |
Set the BLE connection interval duration |
BLEConnect::setConnLatency |
Set the BLE connection slave latency |
BLEConnect::setConnTimeout |
Set the BLE connection timeout value |
BLEConnect::updateConnParams |
Send new BLE connection parameters to a connected device |
BLEConnect::getConnInfo |
Get connection information |
BLEConnect::getConnAddr |
Get the Bluetooth address for a certain connection |
BLEConnect::getConnId |
Get the connection ID for a certain device |
BLEConnect::connect
BLEConnect::disconnect
BLEConnect::setScanInterval
BLEConnect::setScanWindow
BLEConnect::setConnInterval
BLEConnect::setConnLatency
BLEConnect::setConnTimeout
BLEConnect::updateConnParams
BLEConnect::getConnInfo
BLEConnect::getConnAddr
BLEConnect::getConnId
Class BLEDevice
BLEDevice Class
Members
Public Constructors |
---|
The public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named BLE. |
Public Methods |
|
---|---|
BLEDevice::init |
Allocate resources required for BLE functionality |
BLEDevice::deinit |
Free resources used by BLE functionality |
BLEDevice::connected |
Check if a BLE device is connected |
BLEDevice::setDeviceName |
Set BLE GAP device name |
BLEDevice::setDeviceAppearance |
Set BLE GAP device appearance |
BLEDevice::configAdvert |
Configure BLE advertising parameters |
BLEDevice::configScan |
Configure BLE scan parameters |
BLEDevice::setScanCallback |
Set callback function for BLE scans |
BLEDevice::beginCentral |
Start BLE stack in central mode |
BLEDevice::beginPeripheral |
Start BLE stack in peripheral mode |
BLEDevice::end |
Stop BLE stack |
BLEDevice::configServer |
Configure BLE stack for services |
BLEDevice::addService |
Add a service to the BLE stack |
BLEDevice::configClient |
Configure BLE stack for clients |
BLEDevice::addClient |
Add a client to the BLE stack |
BLEDevice::getLocalAddr |
Get local device Bluetooth address |
BLEDevice::init
BLEDevice::deinit
BLEDevice::connected
BLEDevice::setDeviceName
BLEDevice::setDeviceAppearance
BLEDevice::configAdvert
BLEDevice::configScan
#include 「BLEDevice.h」
#include 「BLEScan.h」
int dataCount = 0;
void scanFunction(T_LE_CB_DATA* p_data) {
printf(」rnScan Data %drn」, ++dataCount);
BLE.configScan()->printScanInfo(p_data);
}
void setup() {
BLE.init();
BLE.configScan()->setScanMode(GAP_SCAN_MODE_ACTIVE);
BLE.configScan()->setScanInterval(500); // Start a scan every 500ms
BLE.configScan()->setScanWindow(250); // Each scan lasts for 250ms
// Provide a callback function to process scan data.
// If no function is provided, default BLEScan::printScanInfo is used
BLE.setScanCallback(scanFunction);
BLE.beginCentral(0);
BLE.configScan()->startScan(5000); // Repeat scans for 5 seconds, then stop
}
void loop() {
}
BLEDevice::setScanCallback
BLEDevice::beginCentral
BLEDevice::beginPeripheral
BLEDevice::end
BLEDevice::configServer
BLEDevice::addService
BLEDevice::configClient
BLEDevice::addClient
BLEDevice::getLocalAddr
Class BLEHIDDevice
BLEHIDDevice Class
Description
A class used for creating and managing HID over GATT Profile (HOGP) services.
Members
Public Constructors |
---|
The public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named BLEHIDDev. |
Public Methods |
|
---|---|
BLEHIDDevice::init |
Initialize the HID Device Profile by creating the required services |
BLEHIDD evice::setNumOutputReport |
Configure the number of HID output reports |
BLEHID Device::setNumInputReport |
Configure the number of HID input reports |
B LEHIDDevice::setReportMap |
Configure the HID report map |
BLEHIDDevice::inputReport |
Send a HID input report |
BLEHIDDevice ::setOutputReportCallback |
Set a user callback function for receiving HID output reports |
BLEHIDD evice::bootKeyboardReport |
Send a HID boot keyboard input report |
BLEHIDDevice::setHidInfo |
Set HID info of the HID service |
B LEHIDDevice::setBattLevel |
Set battery level info of the Battery service |
BLEHIDDevice::setPNPInfo |
Set PNP information of the Device Information service |
BLEHIDDevi ce::setManufacturerString |
Set manufacturer information of the Device Information service |
BLE HIDDevice::setModelString |
Set model information of the Device Information service |
BLEHIDDevice::hidService |
Get reference to HID service |
BLE HIDDevice::devInfoService |
Get reference to Device Information service |
BLEHIDDevice::battService |
Get reference to Battery service |
BLEHIDDevice::init
BLEHIDDevice::setNumOutputReport
BLEHIDDevice::setNumInputReport
BLEHIDDevice::setReportMap
BLEHIDDevice::inputReport
BLEHIDDevice::setOutputReportCallback
BLEHIDDevice::bootKeyboardReport
BLEHIDDevice::setHidInfo
BLEHIDDevice::setBattLevel
BLEHIDDevice::setPNPInfo
BLEHIDDevice::setManufacturerString
BLEHIDDevice::setModelString
BLEHIDDevice::hidService
BLEHIDDevice::devInfoService
BLEHIDDevice::battService
Class BLEHIDGamepad
BLEHIDGamepad Class
Description
A class used for creating and managing a BLE HID Gamepad.
Members
Public Constructors |
|
---|---|
BLEHIDGame pad::BLEHIDGamepad |
Constructs a BLEHIDGamepad object |
Public Methods |
|
BLEHIDGa mepad::setReportID |
Set HID report ID for the HID Gamepad |
BLEHIDGame pad::gamepadReport |
Send a HID Gamepad report |
BLEHIDGa mepad::buttonPress |
Send a HID Gamepad report indicating buttons pressed |
BLEHIDGame pad::buttonRelease |
Send a HID Gamepad report indicating buttons released |
BLEHIDGamepad ::buttonReleaseAll |
Send a HID Gamepad report indicating no buttons pressed |
BLE HIDGamepad::setHat |
Send a HID Gamepad report indicating hat switch position |
BLEH IDGamepad::setAxes |
Send a HID Gamepad report indicating position of all axes |
BLEHIDGam epad::setLeftStick |
Send a HID Gamepad report indicating position of axes corresponding to left analog stick |
BLEHIDGame pad::setRightStick |
Send a HID Gamepad report indicating position of axes corresponding to right analog stick |
BLEHIDGa mepad::setTriggers |
Send a HID Gamepad report indicating position of axes corresponding to triggers |
Class BLEHIDKeyboard
BLEHIDKeyboard Class
Description
A class used for creating and managing a BLE HID Keyboard.
Members
Public Constructors |
|
---|---|
BLEHIDKeybo ard::BLEHIDKeyboard |
Constructs a BLEHIDKeyboard object |
Public Methods |
|
BLEHIDKe yboard::setReportID |
Set HID report ID for the HID Keyboard and HID consumer control |
BLEHIDKeybo ard::consumerReport |
Send a HID Consumer report |
BLEHIDKeybo ard::keyboardReport |
Send a HID Keyboard report |
BLEHIDKeyb oard::consumerPress |
Send a HID Consumer report indicating button pressed |
BLEHIDKeyboa rd::consumerRelease |
Send a HID Consumer report indicating button released |
BLEHI DKeyboard::keypress |
Send a HID Keyboard report indicating keys pressed |
BLEHIDK eyboard::keyRelease |
Send a HID Keyboard report indicating keys released |
BLEHIDKeyb oard::keyReleaseAll |
Send a HID Keyboard report indicating no keys pressed |
BLEHIDKey board::keyCharPress |
Send a HID Keyboard report indicating keys pressed to output an ASCII character |
BLEHIDKe yboard::keySequence |
Send a HID Keyboard report indicating keys pressed to output an ASCII string |
Class BLEHIDMouse
BLEHIDMouse Class
Description
A class used for creating and managing a BLE HID Mouse.
Members
Public Constructors |
|
---|---|
BLE HIDMouse::BLEHIDMouse |
Constructs a BLEHIDMouse object |
Public Methods |
|
BLE HIDMouse::setReportID |
Set HID report ID for the HID Mouse |
BLE HIDMouse::mouseReport |
Send a HID Mouse report |
BL EHIDMouse::mousePress |
Send a HID Mouse report indicating buttons pressed |
BLEH IDMouse::mouseRelease |
Send a HID Mouse report indicating buttons released |
BLEHIDM ouse::mouseReleaseAll |
Send a HID Mouse report indicating no buttons pressed |
B LEHIDMouse::mouseMove |
Send a HID Mouse report indicating mouse movement |
BLE HIDMouse::mouseScroll |
Send a HID Mouse report indicating mouse scroll wheel movement |
Class BLERemoteCharacteristic
BLERemoteCharacteristic Class
Members
Public Constructors |
---|
No public constructor is available for this class. You can get a pointer to an instance of this class using BLERemoteService::getCharacteristic(). |
Public Methods |
|
---|---|
BLERem oteCharacteristic::getDescriptor |
Get a specific descriptor on the remote device |
BLERemoteCharacteristic::getUUID |
Get the characteristic UUID |
BLERe moteCharacteristic::setBufferLen |
Set the size of the internal data buffer |
BLERe moteCharacteristic::getBufferLen |
Get the current size of the internal data buffer |
BLERemoteCharacteristic::canRead |
Determine if characteristic has read property enabled |
B LERemoteCharacteristic::canWrite |
Determine if characteristic has write property enabled |
BL ERemoteCharacteristic::canNotify |
Determine if characteristic has notify property enabled |
BLER emoteCharacteristic::canIndicate |
Determine if characteristic has indicate property enabled |
BLERem oteCharacteristic::getProperties |
Get the characteristic properties |
BLE RemoteCharacteristic::readString |
Read the characteristic data buffer as a String object |
BL ERemoteCharacteristic::readData8 |
Read the characteristic data buffer as an unsigned 8-bit integer |
BLE RemoteCharacteristic::readData16 |
Read the characteristic data buffer as an unsigned 16-bit integer |
BLE RemoteCharacteristic::readData32 |
Read the characteristic data buffer as an unsigned 32-bit integer |
BLER emoteCharacteristic::writeString |
Write data to the characteristic as a String object or character array |
BLE RemoteCharacteristic::writeData8 |
Write data to the characteristic as an unsigned 8-bit integer |
BLER emoteCharacteristic::writeData16 |
Write data to the characteristic as an unsigned 16-bit integer |
BLER emoteCharacteristic::writeData32 |
Write data to the characteristic as an unsigned 16-bit integer |
BLERemoteCharacteristic::setData |
Write data to the characteristic |
BLERemoteCharacteristic::getData |
Read data from the characteristic |
BLERemoteChar acteristic::enableNotifyIndicate |
Enable notification or indication for the characteristic |
BLERemoteChara cteristic::disableNotifyIndicate |
Disable notification and indication for the characteristic |
BLERemoteC haracteristic::setNotifyCallback |
Set a user function as a notification callback |
BLERemoteCharacteristic::getDescriptor
BLERemoteCharacteristic::getUUID
BLERemoteCharacteristic::setBufferLen
BLERemoteCharacteristic::getBufferLen
BLERemoteCharacteristic::canRead
BLERemoteCharacteristic::canWrite
BLERemoteCharacteristic::canNotify
BLERemoteCharacteristic::canIndicate
BLERemoteCharacteristic::getProperties
BLERemoteCharacteristic::readString
BLERemoteCharacteristic::readData8
BLERemoteCharacteristic::readData16
BLERemoteCharacteristic::readData32
BLERemoteCharacteristic::writeString
BLERemoteCharacteristic::writeData8
BLERemoteCharacteristic::writeData16
BLERemoteCharacteristic::writeData32
BLERemoteCharacteristic::setData
BLERemoteCharacteristic::getData
BLERemoteCharacteristic::enableNotifyIndicate
BLERemoteCharacteristic::disableNotifyIndicate
BLERemoteCharacteristic::setNotifyCallback
Class BLERemoteDescriptor
BLERemoteDescriptor Class
Members
Public Constructors |
---|
No public constructor is available for this class. You can get a pointer to an instance of this class using BLERemoteCharacteristic::getDescriptor(). |
Public Methods |
|
---|---|
BLERemoteDescriptor::getUUID |
Get the descriptor UUID |
B LERemoteDescriptor::setBufferLen |
Set the size of the internal data buffer |
B LERemoteDescriptor::getBufferLen |
Get the current size of the internal data buffer |
BLERemoteDescriptor::readString |
Read the descriptor data buffer as a String object |
BLERemoteDescriptor::readData8 |
Read the descriptor data buffer as an unsigned 8-bit integer |
BLERemoteDescriptor::readData16 |
Read the descriptor data buffer as an unsigned 16-bit integer |
BLERemoteDescriptor::readData32 |
Read the descriptor data buffer as an unsigned 32-bit integer |
BLERemoteDescriptor::writeString |
Write data to the descriptor as a String object or character array |
BLERemoteDescriptor::writeData8 |
Write data to the descriptor as an unsigned 8-bit integer |
BLERemoteDescriptor::writeData16 |
Write data to the descriptor as an unsigned 16-bit integer |
BLERemoteDescriptor::writeData32 |
Write data to the descriptor as an unsigned 16-bit integer |
BLERemoteDescriptor::setData |
Write data to the descriptor |
BLERemoteDescriptor::getData |
Read data from the descriptor |
BLERemoteDescriptor::getUUID
BLERemoteDescriptor::setBufferLen
BLERemoteDescriptor::getBufferLen
BLERemoteDescriptor::readString
BLERemoteDescriptor::readData8
BLERemoteDescriptor::readData16
BLERemoteDescriptor::readData32
BLERemoteDescriptor::writeString
BLERemoteDescriptor::writeData8
BLERemoteDescriptor::writeData16
BLERemoteDescriptor::writeData32
BLERemoteDescriptor::setData
BLERemoteDescriptor::getData
Class BLERemoteService
BLERemoteService Class
Members
Public Constructors |
---|
No public constructor is available for this class. You can get a pointer to an instance of this class using BLEClient::getService(). |
Public Methods |
|
---|---|
BLERemoteService::getUUID |
Get the service UUID |
BLE RemoteService::getCharacteristic |
Get a specific characteristic on the remote device |
BLERemoteService::getUUID
BLERemoteService::getCharacteristic
Class BLEScan
BLEScan Class
Members
Public Constructors |
---|
No public constructor is available as this class is intended to be a singleton class. You can get a pointer to this class using BLEDevice::configScan |
Public Methods |
|
---|---|
BLEScan::updateScanParams |
Update the current BLE advertisement settings to the lower Bluetooth stack |
BLEScan::startScan |
Start a BLE scan |
BLEScan::stopScan |
Stop a BLE scan |
BLEScan::setScanMode |
Set the BLE scanning mode |
BLEScan::setScanInterval |
Set the BLE scanning interval |
BLEScan::setScanWindow |
Set the BLE scanning window |
BLEScan::setScanDuplicateFilter |
Set the BLE scan duplicate filter |
BLEScan::scanInProgress |
Check if a scan is currently in progress |
BLEScan::printScanInfo |
Print out scanned information |
BLEScan::updateScanParams
BLEScan::startScan
BLEScan::stopScan
BLEScan::setScanMode
BLEScan::setScanInterval
BLEScan::setScanWindow
BLEScan::setScanDuplicateFilter
BLEScan::scanInProgress
BLEScan::printScanInfo
Class BLEService
BLEService Class
Members
Public Constructors |
|
---|---|
BLEService::BLEService |
Constructs a BLEService object |
Public Methods |
|
BLEService::setUUID |
Set service UUID |
BLEService::getUUID |
Get service UUID |
BLEService::addCharacteristic |
Add a characteristic to service |
BLEService::getCharacteristic |
Get a previously added characteristic |
BLEService::BLEService
BLEService::setUUID
BLEService::getUUID
BLEService::addCharacteristic
BLEService::getCharacteristic
Class BLEUUID
BLEUUID Class
Members
Public Constructors |
|
---|---|
BLEUUID::BLEUUID |
Create a UUID object |
Public Methods |
|
BLEUUID::str |
Get the character string representation of UUID |
BLEUUID::data |
Get the binary representation of UUID |
BLEUUID::length |
Get the length of UUID |
BLEUUID::BLEUUID
BLEUUID::str
BLEUUID::data
BLEUUID::length
Class BLEWifiConfigService
BLEWifiConfigService Class
Members
Public Constructors |
|
---|---|
BLEWifiCon figService::BLEWifiConfigService |
Only one instance of this class should be created |
Public Methods |
|
---|---|
BLEWifiConfigService::begin |
Start background thread to process WiFi configuration commands |
BLEWifiConfigService::end |
Stop background thread processing WiFi configuration commands |
BLEWifiConfigService::addService |
Add the service to the BLE stack |
BLEWifiConfigService::advData |
Get advertising data correctly formatted for WiFi configuration service |
BLEWifiConfigService::BLEWifiConfigService
BLEWifiConfigService::begin
BLEWifiConfigService::end
BLEWifiConfigService::addService
BLEWifiConfigService::advData
EPDIF
Class EpdIF
EpdIf Class
Members
Public Constructors |
---|
A public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named EpdIf. |
Public Methods |
|
---|---|
EpdIf::EPD_Dis_Part |
Put an image buffer to the frame memory, but not updating the display |
EpdIf::EPD_SetFrame |
Put display data to the frame memory, usually used for setup text display functions |
EpdIf::EPD_SetRAMValue_BaseMap |
To read image data stored in the RAM, but not display on the screen |
EpdIf::EPD_SetFrameMemory |
To read image data stored in the buffer, but not display on the screen |
EpdIf::EPD_UpdateDisplay |
Update the display |
EpdIf::EPD_ClearScreen_White |
Clear the frame memory with the White color, but not updating the display |
EpdIf::EPD_ClearScreen_Black |
Clear the frame memory with the Black color, but not updating the display |
EpdIf::EPD_Busy |
Wait until the Busy pin goes to low, which is the idle state |
EpdIf::EPD_Reset |
Used for the Epaper module reset. Often used to awaken the module in deep sleep |
EpdIf::EPD_Sleep |
After this command is transmitted, the chip would enter the deep-sleep mode to save power |
EpdIf:: EPD_Dis_Part
EpdIf:: EPD_SetFrame
EpdIf:: EPD_SetRAMValue_BaseMap
EpdIf:: EPD_SetFrameMemory
EpdIf:: EPD_UpdateDisplay
EpdIf:: EPD_ClearScreen_White
EpdIf:: EPD_ClearScreen_Black
EpdIf:: EPD_Busy
EpdIf:: EPD_Reset
EpdIf::EPD_Sleep
FatfsSDCard
Class SdFatFs
Description
Defines a class of SD FAT File system.
Syntax
class SdFatFs
Members
Public Constructors
SdFatFs::SdFatFs Constructs a SdFatFs object
SdFatFs::~SdFatFs Destructs a SdFatFs object
Public Methods
SdFatFs::begin |
Initialize SD FAT File System |
---|---|
SdFatFs::end |
Deinitialize SD FAT File System |
SdFatFs::*getRootPath |
Get the root path of the SD FAT File System |
SdFatFs::readDir |
List items under a specific folder |
SdFatFs::mkdir |
Create folder |
SdFatFs::rm |
Remove folder or file |
SdFatFs::isDir |
Check if a specific path is a directory |
SdFatFs::isFile |
Check if a specific path is a file |
SdFatFs::getLastModTime |
Get the last modified time for a file or directory |
SdFatFs::setLastModTime |
Set the last modified time for a file or directory |
SdFatFs::status |
Return the current status of SD |
SdFatFs::open |
Open a file |
SdFatFs::begin
SdFatFs::end
SdFatFs::*getRootPath
SdFatFs::readDir
SdFatFs::mkdir
SdFatFs::rm
SdFatFs::isDir
SdFatFs::isFile
SdFatFs::getLastModTime
SdFatFs::setLastModTime
SdFatFs::open
SdFatFs::status
Class SdFatFile
Description
Defines a class of SD FAT File.
Members
Public Constructors |
|
---|---|
SdFatFile::SdFatFile |
Constructs a SdFatFile object |
SdFatFile::~SdFatFile |
Destructs a SdFatFile object |
Public Methods |
|
SdFatFile::write |
Write 1 byte/bytes to file |
SdFatFile::read |
Read 1 byte/bytes from the file |
SdFatFile::peek |
Read 1 byte from file without move curser |
SdFatFile::available |
Check if the cursor is at EOF (End-Of-File) |
SdFatFile::bool |
Check if file is opened |
SdFatFile::seek |
Change cursor to a specific position |
SdFatFile::close |
Close file |
SdFatFile::write
SdFatFile:: read
Example Code
#include 「FatFs_SD.h」
char dirname[] = 「testdir」;
char filename[] = 「test.txt」;
char write_content[] = 「hello world!」;
FatFsSD fs;
void setup() {
char buf[128];
char absolute_filename[128];
fs.begin();
sprintf(absolute_filename, 「%s%s」, fs.getRootPath(), dirname);
fs.mkdir(absolute_filename);
printf(「create dir at \」%s"rn」, absolute_filename);
sprintf(absolute_filename, 「%s%s/%s」, fs.getRootPath(), dirname, filename);
SdFatFile file = fs.open(absolute_filename);
file.println(write_content);
file.close();
printf(「create file at \」%s"rn」, absolute_filename);
printf(「read back from \」%s"rn」, absolute_filename);
file = fs.open(absolute_filename);
memset(buf, 0, sizeof(buf));
file.read(buf, sizeof(buf));
file.close();
printf(「==== content ====rn」);
printf(「%s」, buf);
printf(「==== end ====rn」);
fs.end();
}
void loop() {
delay(1000);
}
#include 「FatFs_SD.h」
char filename[] = 「test.txt」;
char write_content[] = 「hello world!」;
FatFsSD fs;
void setup() {
char buf[128];
char absolute_filename[128];
fs.begin();
printf(「write something to \」%s"rn」, filename);
sprintf(absolute_filename, 「%s%s」, fs.getRootPath(), filename);
SdFatFile file = fs.open(absolute_filename);
file.println(write_content);
file.close();
printf(「write finishrnrn」);
printf(「read back from \」%s"rn」, filename);
file = fs.open(absolute_filename);
memset(buf, 0, sizeof(buf));
file.read(buf, sizeof(buf));
file.close();
printf(「==== content ====rn」);
printf(「%s」, buf);
printf(「==== end ====rn」);
fs.end();
}
void loop() {
delay(1000);
}
SdFatFile:: peek
SdFatFile:: available
SdFatFile:: flush
SdFatFile:: seek
SdFatFile:: close
#include <FatFs_SD.h>
FatFsSD fs;
char filename[] = 「test.txt」;
void setup() {
char absolute_filename[128];
uint16_t year = 2021;
uint16_t month = 4;
uint16_t date = 4;
uint16_t hour = 12;
uint16_t minute = 12;
uint16_t second = 12;
fs.begin();
sprintf(absolute_filename, 「%s%s」, fs.getRootPath(), filename);
SdFatFile file = fs.open(absolute_filename);
file.close();
fs.setLastModTime(absolute_filename, year, month, date, hour, minute, second);
fs.getLastModTime(absolute_filename, &year, &month, &date, &hour, &minute, &second);
printf(「filename:"%s"rn」, absolute_filename);
printf(「time mod:%04d/%02d/%02d %02d:%02d:%02drn」, year, month, date, hour, minute, second);
fs.end();
}
void loop() {
delay(1000);
}
FlashMemory
Class EpdIF
FlashMemoryClass Class
Members
Public Constructors |
|
---|---|
Fl ashMemoryClass::FlashMemoryClass |
Constructs a FlashMemoryClass object |
Fla shMemoryClass::~FlashMemoryClass |
Deconstructs a FlashMemoryClass object |
Public Methods |
|
FlashMemoryClass::begin |
Initialize/Re-initialize the base address and size |
FlashMemoryClass::read |
Read the content to buf |
FlashMemoryClass::update |
Write buf back to flash memory |
FlashMemoryClass::readWord |
Read 4 bytes from flash memory |
FlashMemoryClass::writeWord |
Write 4 bytes into flash memory |
FlashMemoryClass::buf_size |
The buf size |
FlashMemoryClass::*buf |
The buf to be operated |
FlashMemoryClass::FlashMemoryClass
#include <FlashMemory.h>
void setup() {
FlashMemory.read();
if (FlashMemory.buf[0] == 0xFF) {
FlashMemory.buf[0] = 0x00;
FlashMemory.update();
Serial.println(「write count to 0」);
} else {
FlashMemory.buf[0]++;
FlashMemory.update();
Serial.print(「Boot count: 「);
Serial.println(FlashMemory.buf[0]);
}
}
void loop() {
delay(1000);
}
#include <FlashMemory.h>
void setup() {
unsigned int value;
/* request flash size 0x4000 from 0xFC000 */
FlashMemory.begin(0xFC000, 0x4000);
/* read one word (32-bit) from 0xFC000 plus offset 0x3F00 */
value = FlashMemory.readWord(0x3F00);
printf(「value is 0x%08Xrn」, value);
if (value == 0xFFFFFFFF) {
value = 0;
} else {
value++;
}
/* write one word (32-bit) to 0xFC000 plus offset 0x3F00 */
FlashMemory.writeWord(0x3F00, value);
}
void loop() {
// put your main code here, to run repeatedly:
}
FlashMemoryClass::begin
FlashMemoryClass::read
FlashMemoryClass::update
FlashMemoryClass::readWord
FlashMemoryClass::writeWord
FlashMemoryClass::buf_size
FlashMemoryClass::*buf
GPIO
Class DHT
DHT Class
Members
Public Constructors |
|
---|---|
DHT::DHT |
Constructs a DHT object |
Public Methods |
|
DHT::begin |
Initialize the DHT sensor |
DHT::readTemperature |
Read temperature(Fahrenheit or Celcius) from the DHT sensor |
DHT::convertCtoF |
Convert a value from Celcius to Fahrenheit |
DHT::convertFtoC |
Convert a value from Fahrenheit to Celcius |
DHT::readHumidity |
Read humidity(%) from the DHT sensor |
DHT::computeHeatIndex |
Compute the HeatIndex from the readings (Using both Rothfusz and Steadman’s equations) |
DHT::read |
Check if the sensor is readable |
DHT::DHT
// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain
#include 「DHT.h」
// The digital pin we’re connected to.
#define DHTPIN 8
// 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(115200);
Serial.println(「DHTxx test!」);
dht.begin();
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 『old』 (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(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(」 *Ft」);
Serial.print(「Heat index: 「);
Serial.print(hic);
Serial.print(」 *C 「);
Serial.print(hif);
Serial.println(」 *F」);
}
DHT::begin
DHT::readTemperature
DHT::convertCtoF
DHT::convertFtoC
DHT::computeHeatIndex
DHT::readHumidity
DHT::read
Class HttpClient
InterruptLock Class
Members
Public Constructors |
|
---|---|
InterruptLock::InterruptLock |
Constructs a InterruptLock object |
InterruptLock::~ InterruptLock |
Deconstructs a InterruptLock object |
GTimer
Class EpdIF
GTimerClass Class
Members
Public Constructors |
|
---|---|
GTimerClass::GTimerClass |
Constructs a GTimerClass object |
Public Methods |
|
GTimerClass::begin |
Initialize a timer and start it immediately |
GTimerClass::stop |
Stop a specific timer |
GTimerClass::reload |
Reload a specific timer |
GTimerClass::read_us |
Read current countdown value |
GTimerClass::begin
/*
This sketch shows how to use several hardware timers in invoke handler only once for each timer.
*/
#include <GTimer.h>
void myhandler(uint32_t data) {
Serial.print(「I am timer!」);
Serial.println(data);
}
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// timerid 0, period 1s, invoke myhandler, invoke only once, user data is 0
GTimer.begin(0, 1 * 1000 * 1000, myhandler, false, 0);
// timerid 1, period 2s, invoke myhandler, invoke only once, user data is 1
GTimer.begin(1, 2 * 1000 * 1000, myhandler, false, 1);
GTimer.begin(2, 3 * 1000 * 1000, myhandler, false, 2);
GTimer.begin(3, 4 * 1000 * 1000, myhandler, false, 3);
}
void loop() {
delay(1000);
}
Example: TimerPeriodical
/*
This sketch shows how to use hardware timer and invoke interrupt handler periodically
*/
#include <GTimer.h>
int counter = 0;
void myhandler(uint32_t data) {
counter++;
Serial.print(「counter: 「);
Serial.println(counter);
if (counter >= 10) {
Serial.println(「stop timer」);
GTimer.stop(0);
}
}
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// timerid 0, period 1s, invoke myhander
GTimer.begin(0, (1 * 1000 * 1000), myhandler);
}
void loop() {
delay(1000);
}
GTimerClass::stop
GTimerClass::reload
GTimerClass::read_us
Http
Class HttpClient
HttpClient Class
Members
Public Constructors |
|
---|---|
HttpClient::HttpClient |
Constructs a HttpClient object |
Public Methods |
|
HttpClient::beginRequest |
Start a more complex request |
HttpClient::endRequest |
End a more complex request |
HttpClient::get |
Connect to the server and start to send a GET request |
HttpClient::post |
Connect to the server and start to send a POST request |
HttpClient::put |
Connect to the server and start to send a PUT request |
HttpClient::startRequest |
Connect to the server and start to send the request |
HttpClient::sendHeader |
Send an additional header line |
HttpClient::sendBasicAuth |
Send a basic authentication header |
HttpClient::finishRequest |
Finish sending the HTTP request |
HttpClient::responseStatusCode |
Get the HTTP status code contained in the response |
HttpClient::readHeader |
Read the next character of the response headers |
HttpClient::skipResponseHeaders |
Skip any response headers to get to the body |
HttpClient::endOfHeadersReached |
Test whether all of the response headers have been consumed |
HttpClient::endOfBodyReached |
Test whether the end of the body has been reached |
HttpClient::contentLength |
Return the length of the body |
HttpClient::HttpClient
#include <HttpClient.h>
#include <WiFi.h>
#include <WiFiClient.h>
char ssid[] = 「YourNetwork」; // your network SSID (name)
char pass[] = 「password」; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
// Name of the server we want to connect to
const char kHostname[] = 「www.google.com」;
const char kPath[] = 「/」;
// Number of milliseconds to wait without receiving any data before we give up
const int kNetworkTimeout = 30*1000;
// Number of milliseconds to wait if no data is available before trying again
const int kNetworkDelay = 1000;
int status = WL_IDLE_STATUS;
void setup() {
Serial.begin(9600);
while ( status != WL_CONNECTED) {
Serial.print(「Attempting to connect to SSID: 「);
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(「Connected to wifi」);
printWifiStatus();
}
void loop() {
int err =0;
WiFiClient c;
HttpClient http(c);
err = http.get(kHostname, kPath);
if (err == 0)
{
Serial.println(「startedRequest ok」);
err = http.responseStatusCode();
if (err >= 0)
{
Serial.print(「Got status code: 「);
Serial.println(err);
// Usually you’d check that the response code is 200 or a
// similar 「success」 code (200-299) before carrying on,
// but we’ll print out whatever response we get
err = http.skipResponseHeaders();
if (err >= 0)
{
int bodyLen = http.contentLength();
Serial.print(「Content length is: 「);
Serial.println(bodyLen);
Serial.println();
Serial.println(「Body returned follows:」);
// Now we’ve got to the body, so we can print it out
unsigned long timeoutStart = millis();
char c;
// Whilst we haven’t timed out & haven’t reached the end of the body
while ( (http.connected() || http.available()) &&
((millis() - timeoutStart) < kNetworkTimeout) )
{
if (http.available())
{
c = http.read();
// Print out this character
Serial.print(c);
bodyLen–;
// We read something, reset the timeout counter
timeoutStart = millis();
}
else
{
// We haven’t got any data, so let’s pause to allow some to arrive
delay(kNetworkDelay);
}
}
}
else
{
Serial.print(「Failed to skip response headers: 「);
Serial.println(err);
}
}
else
{
Serial.print(「Getting response failed: 「);
Serial.println(err);
}
}
else
{
Serial.print(「Connect failed: 「);
Serial.println(err);
}
http.stop();
// And just stop, now that we’ve tried a download
while(1);
}
void printWifiStatus() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.print(rssi);
Serial.println(」 dBm」);
}
HttpClient::beginRequest
HttpClient::endRequest
HttpClient::get
HttpClient::post
HttpClient::put
HttpClient::startRequest
HttpClient::sendHeader
HttpClient::sendBasicAuth
HttpClient::finishRequest
HttpClient::responseStatusCode
HttpClient::readHeader
HttpClient::skipResponseHeaders
HttpClient::endOfHeadersReached
HttpClient::endOfBodyReached
HttpClient::contentLength
IRDevice
Class HttpClient
IRDevice Class
Members
Public Constructors |
|
---|---|
A public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named IR. |
Public Methods |
|
---|---|
IRDevice::getFreq |
Get the current IR modulation frequency |
IRDevice::begin |
Allocate resources and start the IR device with a custom frequency |
IRDevice::end |
Stop the IR device operations and free up resources |
IRDevice::send |
Send IR raw data |
IRDevice::beginNEC |
Allocate resources and start the IR device with a frequency suitable for the NEC protocol |
IRDevice::sendNEC |
Send data using the NEC protocol |
IRDevice::recvNEC |
Receive data using the NEC protocol |
IRDevice::getFreq
IRDevice::begin
IRDevice::end
IRDevice::send
Example Code
#include 「IRDevice.h」
// User defined txPin, rxPin and carrier frequency
#define IR_RX_PIN 8
#define IR_TX_PIN 9
#define CARRIER_FREQ 38000
unsigned int irRawSignal[] = {
9000, 4500, // starting bit
560, 560, 560, 560, 560, 1690, 560, 560, 560, 560, 560, 560, 560, 560, 560, 560, // address 00100000 : 4
560, 1690, 560, 1690, 560, 560, 560, 1690, 560, 1690, 560, 1690, 560, 1690, 560, 1690, // ~ address 11011111
560, 560, 560, 560, 560, 560, 560, 1690, 560, 560, 560, 560, 560, 560, 560, 560, // data 00010000 : 8
560, 1690, 560, 1690, 560, 1690, 560, 560, 560, 1690, 560, 1690, 560, 1690, 560, 1690, //~ data 11101111
560 // stoping bit
};
int DataLen = sizeof(irRawSignal) / sizeof(irRawSignal[0]); // 284/ 4 = 71
void setup()
{
Serial.begin(115200);
IR.begin(IR_RX_PIN, IR_TX_PIN, IR_MODE_TX, CARRIER_FREQ);
}
void loop()
{
IR.send(irRawSignal, DataLen);
Serial.println(「Finished Sending NEC Raw Data….」);
delay(3000);
}
IRDevice::beginNEC
#include 「IRDevice.h」
uint8_t adr = 0;
uint8_t cmd = 0;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
IR.beginNEC(8, 9, IR_MODE_RX); // configure for NEC IR protocol
}
void loop() {
if (IR.recvNEC(adr, cmd, 1000)) {
Serial.print(「Received 「);
Serial.print(adr);
Serial.print(cmd);
Serial.println();
} else {
Serial.println(「Received nothing, timed out」);
}
//IR.end();
}
IRDevice::sendNEC
#include 「IRDevice.h」
uint8_t adr = 0;
uint8_t cmd = 0;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
IR.beginNEC(8, 9, IR_MODE_TX); // configure for NEC IR protocol
}
void loop() {
if (cmd++ >=255) {
adr++;
}
IR.sendNEC(adr, cmd);
Serial.print(「Sent 「);
Serial.print(adr);
Serial.print(cmd);
Serial.println();
//IR.end(); // Call this method to stop IR device and free up the pins for other uses
}
IRDevice::recvNEC
MDNS
Class HttpClient
MDNSClass Class
Members
Public Constructors |
|
---|---|
The public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named MDNS. |
Public Methods |
|
---|---|
MDNSClass::begin |
Start MDNS operations |
MDNSClass::end |
Stop MDNS operations |
MDNSClass::registerService |
Add a service record |
MDNSClass::deregisterService |
Remove service record |
MDNSClass::updateService |
Update service record |
MDNSClass::begin
#include <WiFi.h>
#include <AmebaMDNS.h>
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「secretPassword」; // your network password
MDNSService service(「MyAmeba」, 「_arduino._tcp」, 「local」, 5000);
void setup() {
printf(「Try to connect to %srn」, ssid);
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
printf(「Failed. Wait 1s and retry…rn」);
delay(1000);
}
printf(「Connected to %srn」, ssid);
service.addTxtRecord(「board」, strlen(「ameba_rtl8195a」), 「ameba_rtl8195a」);
service.addTxtRecord(「auth_upload」, strlen(「no」), 「no」);
service.addTxtRecord(「tcp_check」, strlen(「no」), 「no」);
service.addTxtRecord(「ssh_upload」, strlen(「no」), 「no」);
printf(「Start mDNS servicern」);
MDNS.begin();
printf(「register mDNS servicern」);
MDNS.registerService(service);
}
void loop() {
// put your main code here, to run repeatedly:
delay(1000);
}
MDNSClass::end
MDNSClass::registerService
MDNSClass::deregisterService
MDNSClass::updateService
Class HttpClient
MDNSService Class
Members
Public Constructors |
|
---|---|
MDNSService::MDNSService |
Create a MDNS service record |
Public Methods |
|
MDNSService::addTxtRecord |
Add text to MDNS service record |
MDNSService::MDNSService
MDNSService::addTxtRecord
MQTTClient
Class PMUClass
PubSubClient Class
Members
Public Constructors |
|
---|---|
PubSubClient::PubSubClient |
Constructs a PubSubClient object |
Public Methods |
|
PubSubClient::setServer |
Set MQTT server address and port |
PubSubClient::setCallback |
Set callback function |
PubSubClient::setClient |
Set WiFi client |
PubSubClient::setStream |
Set data stream |
PubSubClient::connect |
Attempt to connect to server |
PubSubClient::disconnect |
Disconnect from current session |
PubSubClient::publish |
Publish a message to server |
PubSubClient::publish_P |
Same as above |
PubSubClient::subscribe |
Subscribe to a topic |
PubSubClient::unsubscribe |
Unsubscribe to a topic |
PubSubClient::loop |
Keep MQTT session alive and process any queuing tasks |
PubSubClient::connected |
Check if client still connected |
PubSubClient::state |
Return connection state |
PubSubClient::PubSubClient
#include <WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「secretPassword」; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio’s status
char mqttServer[] = 「test.mosquitto.org」;
char clientId[] = 「amebaClient」;
char publishTopic[] = 「outTopic」;
char publishPayload[] = 「hello world」;
char subscribeTopic[] = 「inTopic」;
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print(「Message arrived [「);
Serial.print(topic);
Serial.print(」] 「);
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
WiFiClient wifiClient;
PubSubClient client(wifiClient);
void reconnect() {
// Loop until we’re reconnected
while (!client.connected()) {
Serial.print(「Attempting MQTT connection…」);
// Attempt to connect
if (client.connect(clientId)) {
Serial.println(「connected」);
// Once connected, publish an announcement…
client.publish(publishTopic, publishPayload);
// … and resubscribe
client.subscribe(subscribeTopic);
} else {
Serial.print(「failed, rc=」);
Serial.print(client.state());
Serial.println(」 try again in 5 seconds」);
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup()
{
Serial.begin(38400);
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to SSID: 「);
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
client.setServer(mqttServer, 1883);
client.setCallback(callback);
// Allow the hardware to sort itself out
delay(1500);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
}
PubSubClient::setServer
PubSubClient::setCallback
PubSubClient::setClient
PubSubClient::setStream
PubSubClient::connect
PubSubClient::disconnect
PubSubClient::publish
PubSubClient::publish_P
PubSubClient::subscribe
PubSubClient::unsubscribe
PubSubClient::loop
PubSubClient::connected
PubSubClient::state
Readme
PubSubClient.cpp
PubSubClient.h
These libraries are under MIT License.
NTPClient
Readme
NTPClient.cpp
NTPClient.h
These libraries are licensed under MIT License.
PowerSave
Class PMUClass
PMUClass Class
Members
Public Constructors |
|
---|---|
PMUClass::PMUClass |
Constructs a PMUClass object |
Public Methods |
|
PMUCLASS::begin |
Initialize the PMUCLASS and select sleep mode |
PMUCLASS::AONTimerDuration |
Set the duration of AON Timer |
PMUCLASS::AONTimerCmd |
Disable the AON Timer for power save usage |
PMUCLASS::RTCWakeSetup |
Set up RTC Timer for power save usage |
PMUCLASS::enable |
Enable power save deep sleep mode |
PMUCLASS::AONWakeReason |
Check AON wakeup source |
PMUCLASS::WakePinCheck |
Check AON GPIO pin wakeup source |
PMUCLASS::AONWakeClear |
Clear all the AON wakeup source |
PMUCLASS::DsleepWakeStatusGet |
Check if deepsleep mode is set |
PMUCLASS::TL_sysactive_time |
Tickless mode system active time |
PMUCLASS::TL_wakelock |
Tickless mode wake lock, select acquire of release |
PMUCLASS::DS_AON_TIMER_WAKEUP |
Return the Wakeup source |
PMUCLASS::DS_RTC_WAKEUP |
Return the Wakeup source |
PMUCLASS::TL_UART_WAKEUP |
Return the Wakeup source |
PMUCLASS::TL_RTC_WAKEUP |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA12 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA13 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA14 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA15 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA16 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA17 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA18 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA19 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA20 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA21 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA25 |
Return the Wakeup source |
PMUC LASS::AON_WAKEPIN_WAKEUP_GPIOA26 |
Return the Wakeup source |
RTC
Class RTC
RTC Class
Members
Public Constructors |
|
---|---|
A public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named RTC. |
Public Methods |
|
---|---|
RTC:: Init |
Initializes the RTC device, including the Clock, the RTC registers, and other functions |
RTC:: DeInit |
Deinitialize the RTC device |
RTC:: Write |
Set the specified timestamp in seconds to RTC |
RTC:: Read |
Get the current timestamp in seconds from RTC |
RTC:: Wait |
Wait for 1 second |
RTC:: SetEpoch |
Convert human-readable time to epoch time |
RTC::Init
/*
* This function describes how to use the RTC API.
* The RTC function is implemented by an independent BCD timer/counter.
* This example will print out the time information every second.
*/
#include <stdio.h>
#include <time.h>
#include 「rtc.h」
#define YEAR 2020
#define MONTH 9
#define DAY 10
#define HOUR 20
#define MIN 30
#define SEC 40
/* Create an rtc object */
RTC rtc;
int32_t seconds;
struct tm *timeinfo;
void setup() {
Serial.begin(115200);
rtc.Init(); // initialize RTC
}
void loop() {
// step 1: convert user time to epoch
int epochTime = humanReadableToEpoch(YEAR, MONTH, DAY, HOUR, MIN, SEC);
// step 2: write epoch time to rtc
rtc.Write(epochTime);
while (1) {
seconds = rtc.Read();
printf(「Epoch Time (in s) since January 1, 1970 = %dsn」, seconds);
printf(「Time as a basic string = %s」, ctime(&seconds));
timeinfo = localtime(&seconds);
printf(「Time as a custom formatted string = %d-%d-%d %d:%d:%dn」,
(timeinfo->tm_year + 1900), (timeinfo->tm_mon + 1), timeinfo->tm_mday, timeinfo->tm_hour,
timeinfo->tm_min, timeinfo->tm_sec);
Serial.println();
rtc.wait(1);
}
}
// convert human readable time to epoch time
int humanReadableToEpoch(int year, int month, int day, int hour, int min, int sec) {
struct tm t;
time_t t_of_day;
t.tm_year = year - 1900; // Year - 1970
t.tm_mon = month - 1; // Month, where 0 = jan
t.tm_mday = day; // Day of the month
t.tm_hour = hour;
t.tm_min = min;
t.tm_sec = sec;
t.tm_isdst = -1; // Is DST on? 1 = yes, 0 = no, -1 = unknown
t_of_day = mktime(&t);
// printf(「seconds since the Epoch: %dn」, (long)t_of_day);
return t_of_day;
}
RTC::DeInit
RTC:: Write
RTC::Read
RTC:: Wait
RTC:: SetEpoch
SoftwareSerial
Class Adafruit_GPS
Adafruit_GPS Class
Members
Public Constructors |
|
---|---|
Adafruit_GPS::Adafruit_GPS |
Constructs an Adafruit_GPS object |
Public Methods |
|
Adafruit_GPS::begin |
Initialize serial communication |
*Adafruit_GPS:: lastNMEA |
Returns the last NMEA line received and unsets the received flag |
Adafruit_GPS:: newNMEAreceived |
Check to see if a new NMEA line has been received |
Adafruit_GPS:: common_init |
Initialization code used by all constructor types |
Adafruit_GPS:: sendCommand |
Send a command to the GPS device |
Adafruit_GPS:: pause |
Pause/unpause receiving new data |
Adafruit_GPS:: parseHex |
Read a Hex value and return the decimal equivalent |
Adafruit_GPS:: read |
Read one character from the GPS device |
Adafruit_GPS:: parse |
Parse an NMEA string |
Adafruit_GPS:: wakeup |
Wake the sensor up |
Adafruit_GPS:: standby |
Standby Mode Switches |
Adafruit_GPS::waitForSentence |
Wait for a specified sentence from the device |
Adafruit_GPS::LOCUS_StartLogger |
Start the LOCUS logger |
Adafruit_GPS::LOCUS_StopLogger |
Stop the LOCUS logger |
Adafruit_GPS::LOCUS_ReadStatus |
Read the logger status |
Adafruit_GPS::Adafruit_GPS
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>
// If you’re using a GPS module:
// Connect the GPS Power pin to 3.3V
// Connect the GPS Ground pin to ground
// Connect the GPS TX (transmit) pin to Digital 0
// Connect the GPS RX (receive) pin to Digital 1
#if defined(BOARD_RTL8195A)
SoftwareSerial mySerial(0, 1);
#elif defined(BOARD_RTL8710)
SoftwareSerial mySerial(17, 5); // RTL8710 need change GPS TX/RX to pin 17 and 5
#else
SoftwareSerial mySerial(0, 1);
#endif
Adafruit_GPS GPS(&mySerial);
// Set GPSECHO to 『false』 to turn off echoing the GPS data to the Serial console
// Set to 『true』 if you want to debug and listen to the raw GPS sentences.
#define GPSECHO false
void setup()
{
Serial.begin(38400);
Serial.println(「Adafruit GPS library basic test!」);
// 9600 NMEA is the default baud rate for Adafruit MTK GPS’s- some use 4800
GPS.begin(9600);
// uncomment this line to turn on RMC (recommended minimum) and GGA (fix data) including altitude
GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
// uncomment this line to turn on only the 「minimum recommended」 data
//GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCONLY);
// For parsing data, we don’t suggest using anything but either RMC only or RMC+GGA since
// the parser doesn’t care about other sentences at this time
// Set the update rate
GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ); // 1 Hz update rate
// For the parsing code to work nicely and have time to sort thru the data, and
// print it out we don’t suggest using anything higher than 1 Hz
// Request updates on antenna status, comment out to keep quiet
GPS.sendCommand(PGCMD_ANTENNA);
delay(1000);
// Ask for firmware version
mySerial.println(PMTK_Q_RELEASE);
}
uint32_t timer = millis();
void loop() // run over and over again
{
// in case you are not using the interrupt above, you’ll
// need to 『hand query』 the GPS, not suggested :(
// read data from the GPS in the 『main loop』
char c = GPS.read();
// if you want to debug, this is a good time to do it!
if (GPSECHO)
if (c) Serial.print(c);
// if a sentence is received, we can check the checksum, parse it…
if (GPS.newNMEAreceived()) {
// a tricky thing here is if we print the NMEA sentence, or data
// we end up not listening and catching other sentences!
// so be very wary if using OUTPUT_ALLDATA and trytng to print out data
//Serial.println(GPS.lastNMEA()); // this also sets the newNMEAreceived() flag to false
if (!GPS.parse(GPS.lastNMEA())) // this also sets the newNMEAreceived() flag to false
return; // we can fail to parse a sentence in which case we should just wait for another
}
// if millis() or timer wraps around, we’ll just reset it
if (timer > millis()) timer = millis();
// approximately every 2 seconds or so, print out the current stats
if (millis() - timer > 2000) {
timer = millis(); // reset the timer
Serial.print(」nTime: 「);
Serial.print(GPS.hour, DEC); Serial.print(『:』);
Serial.print(GPS.minute, DEC); Serial.print(『:』);
Serial.print(GPS.seconds, DEC); Serial.print(『.』);
Serial.println(GPS.milliseconds);
Serial.print(「Date: 「);
Serial.print(GPS.day, DEC); Serial.print(『/』);
Serial.print(GPS.month, DEC); Serial.print(「/20」);
Serial.println(GPS.year, DEC);
Serial.print(「Fix: 「); Serial.print((int)GPS.fix);
Serial.print(」 quality: 「); Serial.println((int)GPS.fixquality);
if (GPS.fix) {
Serial.print(「Location: 「);
Serial.print(GPS.latitude, 4); Serial.print(GPS.lat);
Serial.print(」, 「);
Serial.print(GPS.longitude, 4); Serial.println(GPS.lon);
Serial.print(「Location (in degrees, works with Google Maps): 「);
Serial.print(GPS.latitudeDegrees, 4);
Serial.print(」, 「);
Serial.println(GPS.longitudeDegrees, 4);
Serial.print(「Speed (knots): 「); Serial.println(GPS.speed);
Serial.print(「Angle: 「); Serial.println(GPS.angle);
Serial.print(「Altitude: 「); Serial.println(GPS.altitude);
Serial.print(「Satellites: 「); Serial.println((int)GPS.satellites);
}
}
}
Adafruit_GPS::begin
*Adafruit_GPS::lastNMEA
Adafruit_GPS::newNMEAreceived
Adafruit_GPS::common_init
Adafruit_GPS::sendCommand
Adafruit_GPS::pause
Adafruit_GPS::parseHex
Adafruit_GPS::read
Adafruit_GPS::parse
Adafruit_GPS::wakeup
Adafruit_GPS::standby
Adafruit_GPS::waitForSentence
Adafruit_GPS::LOCUS_StartLogger
Adafruit_GPS::LOCUS_StopLogger
Adafruit_GPS::LOCUS_ReadStatus
Class HttpClient
PMS3003 Class
Members
Public Constructors |
|
---|---|
PMS3003::PMS3003 |
Constructs a PMS3003 object |
Public Methods |
|
PMS3003::begin |
Initialize hardware UART |
PMS3003::end |
Free allocated space thus stopping UART |
PMS3003::get_pm1p0_cf1 |
Get PM1.0 under correction factor = 1 |
PMS3003:: get_pm2p5_cf1 |
Get PM2.5 under correction factor = 1 |
PMS3003:: get_pm10_cf1 |
Get PM10 under correction factor = 1 |
PMS3003:: get_pm1p0_air |
Get PM1.0 air quality |
PMS3003:: get_pm2p5_air |
Get PM2.5 air quality |
PMS3003:: get_pm10_air |
Get PM10 air quality |
PMS3003:update_cache |
Updates the cache memory |
PMS3003::pms3003_handle_interrupt |
Set up the serial event handler |
PMS3003::PMS3003
PMS3003::begin
PMS3003::end
PMS3003::get_pm1p0_cf1
PMS3003::get_pm2p5_cf1
PMS3003::get_pm10_cf1
PMS3003::get_pm1p0_air
PMS3003::get_pm2p5_air
PMS3003::get_pm10_air
PMS3003::pms3003_handle_interrupt
PMS3003::update_cache
Class SoftwareSerial
SoftwareSerial Class
Members
Public Constructors |
|
---|---|
SoftwareSerial::SoftwareSerial |
Constructs a SoftwareSerial object |
Public Methods |
|
SoftwareSerial::begin |
Sets the speed (baud rate) for the serial communication |
SoftwareSerial::listen |
Enables the selected software serial port to listen |
SoftwareSerial::end |
Same as stopListening |
SoftwareSerial::stopListening |
Stop listening on the port |
SoftwareSerial::peek |
Return a character that was received on the RX pin of the software serial port |
SoftwareSerial::write |
Prints data to the transmit pin of the software serial port as raw bytes |
SoftwareSerial::read |
Return a character that was received on the RX pin of the software serial port |
SoftwareSerial::available |
Get the number of bytes (characters) available for reading from a software serial port |
SoftwareSerial::flush |
Flush the received buffer |
SoftwareSerial::setBufferSize |
Set buffer size |
Soft wareSerial::setAvailableCallback |
Set available callback |
SoftwareSerial::handle_interrupt |
Private methods handles interrupt |
SoftwareSerial::SoftwareSerial
/*
The circuit: (BOARD RTL8195A)
* RX is digital pin 0 (connect to TX of other devices)
* TX is digital pin 1 (connect to RX of other devices)
*/
#include <SoftwareSerial.h>
#if defined(BOARD_RTL8195A)
SoftwareSerial mySerial(0, 1); // RX, TX
#elif defined(BOARD_RTL8710)
SoftwareSerial mySerial(17, 5); // RX, TX
#else
SoftwareSerial mySerial(0, 1); // RX, TX
#endif
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(57600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println(「Goodnight moon!」);
// set the data rate for the SoftwareSerial port
mySerial.begin(4800);
mySerial.println(「Hello, world?」);
}
void loop() { // run over and over
if (mySerial.available()) {
mySerial.write(mySerial.read());
}
}
SoftwareSerial::begin
SoftwareSerial::listen
SoftwareSerial::end
SoftwareSerial::isListening
SoftwareSerial::stopListening
SoftwareSerial::peek
SoftwareSerial::write
SoftwareSerial::read
SoftwareSerial::available
SoftwareSerial::flush
SoftwareSerial::setBufferSize
SoftwareSerial::setAvailableCallback
/*
The circuit: (BOARD RTL8195A)
RX is digital pin 0 (connect to TX of other devices)
TX is digital pin 1 (connect to RX of other devices)
*/
#include <SoftwareSerial.h>
#if defined(BOARD_RTL8195A)
SoftwareSerial mySerial(0, 1); // RX, TX
#elif defined(BOARD_RTL8710)
SoftwareSerial mySerial(17, 5); // RX, TX
#else
SoftwareSerial mySerial(0, 1); // RX, TX
#endif
uint32_t semaID;
// The callback is hooking at UART IRQ handler and please don’t do heavy task here.
void mySerialCallback(char c)
{
/* The parameter c is only for peeking. The actual data is
* still in the buffer of SoftwareSerial.
*/
if (c == 『r』 || c == 『n』) {
os_semaphore_release(semaID);
}
}
void setup() {
// use 1 count for binary semaphore
semaID = os_semaphore_create(1);
// There is a token in the semaphore, clear it.
os_semaphore_wait(semaID, 0xFFFFFFFF);
// set the data rate for the SoftwareSerial port
mySerial.begin(38400);
mySerial.setAvailableCallback(mySerialCallback);
}
void loop() { // run over and over
// wait semaphore for 5s timeout
if (os_semaphore_wait(semaID, 5 * 1000)) {
// we got data before timeout
while(mySerial.available()) {
mySerial.print((char)mySerial.read());
}
mySerial.println();
} else {
mySerial.println(「No data comes in.」);
}
}
SoftwareSerial::handle_interrupt
Readme
NewSoftSerial.h
by Mikal Hart
(http://arduiniana.org/libraries/newsoftserial).
SoftwareSerial.cpp
SoftwareSerial.h
These libraries are under GNU Lesser General Public License.
Adafruit_GPS.cpp
Adafruit_GPS.h
These libraries are under BSD License.
SPI
Class AmebaILI9341
AmebaILI9341 Class
Description
Defines a class to use ILI9341 TFT SPI display for Ameba.
Syntax
class AmebaILI9341
Members
Public Constructors |
|
---|---|
AmebaILI9341::AmebaILI9341 |
Constructs an AmebaILI9341 object |
Public Methods |
|
AmebaILI9341::begin |
Initialize SPI, pin mapping and screen configuration |
AmebaILI9341::setAddress |
Initialize image size and position |
AmebaILI9341::writecommand |
SPI transfer a command |
AmebaILI9341::writedata |
SPI transfer a piece of data |
AmebaILI9341::setRotation |
Set screen orientation |
AmebaILI9341::fillScreen |
Fill the screen with a color |
AmebaILI9341::clr |
Clear screen |
AmebaILI9341::fillRectangle |
Fill a rectangular space with a color |
AmebaILI9341::drawPixel |
Turn on a pixel on the screen |
AmebaILI9341::drawChar |
To print a character on the screen |
AmebaILI9341::drawLine |
Draw line on the screen |
AmebaILI9341::drawRectangle |
Draw a rectangle on the screen |
AmebaILI9341::drawCircle |
Draw a circle on the screen |
AmebaILI9341::write |
Same as drawChar |
AmebaILI9341::getWidth |
Return the width 240 |
AmebaILI9341::getHeight |
Return the height 320 |
AmebaILI9341::setCursor |
Set cursor to the desired position |
AmebaILI9341::setForeground |
Set foreground color |
AmebaILI9341::setBackground |
Set background color |
AmebaILI9341::setFontSize |
Set character font size |
AmebaILI9341::reset |
Reset pin to High or Low |
AmebaILI9341::AmebaILI9341
Description
Constructs an AmebaILI9341 object and set CS, DC and RESET pins .
Syntax
AmebaILI9341::AmebaILI9341(int csPin, int dcPin, int resetPin)
Parameters
csPin: pin for Chip Select dcPin: pin for Data/Command resetPin: pin for Reset
Returns
The function returns nothing.
Example Code
Example: : PM25_ON_ILI9341_TFT_LCD
This example demonstrates how to read pm2.5 value on PMS 3003 air-condition sensor and display it on ILI9341 TFT LCD.
/*
PMS 3003 pin map is as follow:
PIN1 :VCC, connect to 5V
PIN2 :GND
PIN3 :SET, 0:Standby mode, 1:operating mode
PIN4 :RXD :Serial RX
PIN5 :TXD :Serial TX
PIN6 :RESET
PIN7 :NC
PIN8 :NC
In this example, we only use Serial to get PM 2.5 value.
The circuit:
* RX is digital pin 0 (connect to TX of PMS 3003)
* TX is digital pin 1 (connect to RX of PMS 3003)
For RTL8195A ILI9341 TFT LCD with SPI interface has these pins:
D/C : connect to pin 9
CS : connect to pin 10
MOSI : connect to pin 11
MISO : connect to pin 12
CLK : connect to pin 13
VCC : connect to 3V3
GND : connect to GND
*/
#include 「SoftwareSerial.h」
#include 「SPI.h」
#include 「AmebaILI9341.h」
#if defined(BOARD_RTL8195A)
SoftwareSerial mySerial(0, 1); // RX, TX
#define TFT_RESET 8
#define TFT_DC 9
#define TFT_CS 10
#elif defined(BOARD_RTL8710)
SoftwareSerial mySerial(17, 5); // RX, TX
// IMPORTANT: Due to limit pin, we do not connect TFT_RESET pin.
#define TFT_RESET 0xFFFFFFFF
#define TFT_DC 2
#define TFT_CS 10
#endif
AmebaILI9341 tft = AmebaILI9341(TFT_CS, TFT_DC, TFT_RESET);
#define ILI9341_SPI_FREQUENCY 20000000
#define pmsDataLen 32
uint8_t buf[pmsDataLen];
int idx = 0;
int pm10 = 0;
int last_pm25 = 0;
int pm25 = 0;
int pm100 = 0;
uint16_t pm25color[] = {
0x9FF3,
0x37E0,
0x3660,
0xFFE0,
0xFE60,
0xFCC0,
0xFB2C,
0xF800,
0x9800,
0xC99F
};
void setup() {
Serial.begin(57600);
mySerial.begin(9600); // PMS 3003 UART has baud rate 9600
SPI.setDefaultFrequency(ILI9341_SPI_FREQUENCY);
tft.begin();
drawPictureFrames();
}
void loop() { // run over and over
uint8_t c;
idx = 0;
memset(buf, 0, pmsDataLen);
while (true) {
while (c != 0x42) {
while (!mySerial.available());
c = mySerial.read();
}
while (!mySerial.available());
c = mySerial.read();
if (c == 0x4d) {
// now we got a correct header)
buf[idx++] = 0x42;
buf[idx++] = 0x4d;
break;
}
}
while (idx != pmsDataLen) {
while(!mySerial.available());
buf[idx++] = mySerial.read();
}
pm10 = ( buf[10] << 8 ) | buf[11];
last_pm25 = pm25;
pm25 = ( buf[12] << 8 ) | buf[13];
pm100 = ( buf[14] << 8 ) | buf[15];
updateValueToTftScreen();
}
void drawPictureFrames() {
tft.setRotation(1);
tft.clr();
tft.setFontSize(1);
// Upper title
tft.setFontSize(1);
tft.setCursor(20,20);
tft.print(「PM2.5 DETECTOR」);
// PM 2.5 Circle Frame
tft.drawCircle(100,130,60, ILI9341_BLUE);
tft.drawCircle(100,130,61, ILI9341_BLUE);
tft.setFontSize(1);
tft.setCursor(90,85);
tft.print(「PM2.5」);
tft.setFontSize(1);
tft.setCursor(90,170);
tft.print(「um/m3」);
// PM 10 Circle Frame
tft.drawCircle(220,70,40, ILI9341_BLUE);
tft.setFontSize(1);
tft.setCursor(210,40);
tft.print(「PM10」);
tft.setFontSize(1);
tft.setCursor(205,95);
tft.print(「um/m3」);
// PM 1.0 Circle Frame
tft.drawCircle(220,170,40, ILI9341_BLUE);
tft.setFontSize(1);
tft.setCursor(205,140);
tft.print(「PM1.0」);
tft.setFontSize(1);
tft.setCursor(205,195);
tft.print(「um/m3」);
// right side bar, referenced from: http://taqm.epa.gov.tw/taqm/tw/
tft.fillRectangle(290, 30+ 0*2, 10, 12*2, pm25color[0]); // 0~11
tft.fillRectangle(290, 30+12*2, 10, 12*2, pm25color[1]); // 12-23
tft.fillRectangle(290, 30+24*2, 10, 12*2, pm25color[2]); // 24-35
tft.fillRectangle(290, 30+36*2, 10, 6*2, pm25color[3]); // 36-41
tft.fillRectangle(290, 30+42*2, 10, 6*2, pm25color[4]); // 42-47
tft.fillRectangle(290, 30+48*2, 10, 6*2, pm25color[5]); // 48-53
tft.fillRectangle(290, 30+54*2, 10, 6*2, pm25color[6]); // 54-58
tft.fillRectangle(290, 30+59*2, 10, 6*2, pm25color[7]); // 59-64
tft.fillRectangle(290, 30+65*2, 10, 6*2, pm25color[8]); // 65-70
tft.fillRectangle(290, 30+71*2, 10, 10*2, pm25color[9]); // >=71
tft.setCursor(302, 30);
tft.setFontSize(1);
tft.print(「0」);
tft.setCursor(302, 30+36*2);
tft.print(「36」);
tft.setCursor(302, 30+54*2);
tft.print(「54」);
tft.setCursor(302, 30+71*2);
tft.print(「71」);
// bottom right text
tft.setCursor(210,230);
tft.setFontSize(1);
tft.print(「Powered by Realtek」);
updateValueToTftScreen();
}
void updateValueToTftScreen() {
tft.setCursor(60, 111);
tft.setFontSize(5);
tft.setForeground( getPm25Color(pm25) );
if (pm25 < 10) {
tft.print(」 「);
} else if (pm25 < 100) {
tft.print(」 「);
}
tft.print(pm25);
tft.setCursor(195,60);
tft.setFontSize(3);
if (pm100 < 10) {
tft.print(」 「);
} else if (pm100 < 100) {
tft.print(」 「);
}
tft.print(pm100);
tft.setCursor(198,160);
if (pm10 < 10) {
tft.print(」 「);
} else if (pm10 < 100) {
tft.print(」 「);
}
tft.print(pm10);
tft.setFontSize(1);
tft.setForeground(ILI9341_WHITE);
if (last_pm25 > 80) {
tft.fillRectangle(275, 80*2+30-3, 12, 8, ILI9341_BLACK);
} else {
tft.fillRectangle(275, last_pm25*2+30-3, 12, 8, ILI9341_BLACK);
}
if (pm25 > 80) {
tft.setCursor(275, 80*2+30-3);
} else {
tft.setCursor(275, pm25*2+30-3);
}
tft.print(「=>」);
}
uint16_t getPm25Color(int v) {
if (v < 12) {
return pm25color[0];
} else if (v < 24) {
return pm25color[1];
} else if (v < 36) {
return pm25color[2];
} else if (v < 42) {
return pm25color[3];
} else if (v < 48) {
return pm25color[4];
} else if (v < 54) {
return pm25color[5];
} else if (v < 59) {
return pm25color[6];
} else if (v < 65) {
return pm25color[7];
} else if (v < 71) {
return pm25color[8];
} else {
return pm25color[9];
}
}
Notes and Warnings
NA
AmebaILI9341::begin
Description
Initialize hardware SPI, pin mapping and screen configuration
Syntax
void AmebaILI9341::begin(void)
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
This method is required to run first before other operations on the display.
AmebaILI9341::setAddress
Description
Initialize image size and positioning on the display
Syntax
void AmebaILI9341::setAddress(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1)
Parameters
x0: leftmost coordinate of the image y0: top coordinate of the image x1: rightmost coordinate of the image y1: bottom coordinate of the image
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Do not use this to set the cursor, use the “setCursor” method instead.
AmebaILI9341::writecommand
Description
Write a single-byte command to display
Syntax
void AmebaILI9341::writecommand(uint8_t command)
Parameters
command: a single byte command
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::writedata
Description
Write 1 byte of data to display
Syntax
void AmebaILI9341::writedata(uint8_t data)
Parameters
data: 1 byte data
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Only use this method to write 1 byte at a time.
AmebaILI9341::setRotation
Description
Setting screen orientation, “0” for no rotation, “1” for 90 degrees rotation and so on so forth.
Syntax
void AmebaILI9341::setRotation(uint8_t m)/span> Parameters
m: one of the 4 rotation modes -> “0” for no rotation, “1” for 90⁰, “2” for 180⁰, “3” for 270⁰
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
if m=4, it’s equivalent to mode 0, and m=5 for mode 1, m=6 for mode 2 so on so forth.
AmebaILI9341::fillScreen
Description
Fill the entire screen with one color
Syntax
void AmebaILI9341::fillScreen(uint16_t color)
Parameters
color: a 16-bit color reference defined in AmebaILI9341.h
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Refer to AmebaILI9341.h for available colors.
AmebaILI9341::clr
Description
Fill the entire screen with a certain background-color
Syntax
void AmebaILI9341::clr(void)
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341
Notes and Warnings
background-color can be set by calling setBackground method.
AmebaILI9341::fillRectangle
Description
Fill a rectangular space with a color on the screen
Syntax
void AmebaILI9341::fillRectangle(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color)
Parameters
x: leftmost coordinate of the image y: top coordinate of the image w: width of the image h: height of the image color: the color of the image
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
NA
AmebaILI9341::drawPixel
Description
Turn on a pixel on the screen
Syntax
void AmebaILI9341::drawPixel(int16_t x, int16_t y, uint16_t color)
Parameters
x: leftmost coordinate of the image y: top coordinate of the image color: the color of the image
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::drawChar
Description
Draw character on the screen
Syntax
void AmebaILI9341::drawChar(unsigned char c) void AmebaILI9341::drawChar(int16_t x, int16_t y, unsigned char c, uint16_t _fontcolor, uint16_t _background, uint8_t _fontsize)
Parameters
x: leftmost coordinate of the image y: top coordinate of the image c: a character _fontcolor: font color _background: background color _fontsize: font size
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
In the actual example, the Print method is used to print a string of character on the screen instead of using this method.
AmebaILI9341::drawLine
Description
Draw a straight line on the screen
Syntax
void AmebaILI9341::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1) void AmebaILI9341::drawLine(int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t color)
Parameters
x0: leftmost coordinate of the image y0: top coordinate of the image x1: leftmost coordinate of the image y1: top coordinate of the image color: the color of the image
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::drawRectangle
Description
Draw a rectangular shape on the screen
Syntax
void AmebaILI9341::drawRectangle(int16_t x, int16_t y, int16_t w, int16_t h) void AmebaILI9341::drawRectangle(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color)
Parameters
x: leftmost coordinate of the image y: top coordinate of the image w: width of the image h: height of the image color: the color of the image
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::drawCircle
Description
Draw a circular shape on the screen
Syntax
void AmebaILI9341::drawCircle(int16_t x0, int16_t y0, int16_t r) void AmebaILI9341::drawCircle(int16_t x0, int16_t y0, int16_t r, uint16_t color)
Parameters
x0: leftmost coordinate of the image y0: top coordinate of the image r: radius of the image color: the color of the image
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
Include “AmebaServo.h” to use the class function.
AmebaILI9341::write
Description
Same as drawChar, write a character on the screen
Syntax
size_t AmebaILI9341::write(uint8_t c)
Parameters
c: a character to be written on the screen
Returns
Number of bytes written
Example Code
NA
Notes and Warnings
This an inherited method from Print class and is seldom used.
AmebaILI9341::getWidth
Description
Get the width of the image
Syntax
int16_t AmebaILI9341::getWidth(void)
Parameters
The function requires no input parameter.
Returns
Width of the image
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::getHeight
Description
Get the height of the image
Syntax
int16_t AmebaILI9341::getHeight(void)
Parameters
The function requires no input parameter.
Returns
Height of the image
Example Code
NA
Notes and Warnings
NA
AmebaILI9341::setCursor
Description
Set the cursor to a specific position on the screen
Syntax
void AmebaILI9341::setCursor(int16_t x, int16_t y)
Parameters
x: coordinate on the x-axis y: coordinate on the y-axis
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
NA
AmebaILI9341::setForeground
Description
Set foreground color
Syntax
void AmebaILI9341::setForeground(uint16_t color)
Parameters
color: one of the colors available in AmebaILI9341.h
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
NA
AmebaILI9341::setBackground
Description
Set background color
Syntax
void AmebaILI9341::setBackground(uint16_t _background)
Parameters
_background: one of the colors available in AmebaILI9341.h
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
NA
AmebaILI9341::setFontSize
Description
Set the font size of the characters printed on the screen.
Syntax
void AmebaILI9341::setFontSize(uint8_t size)
Parameters
size: font size, default 1 for smallest, 5 for largest font size
Returns
The function returns nothing.
Example Code
Example: PM25_ON_ILI9341_TFT_LCD
Details of the code are given in the previous section of AmebaILI9341:: AmebaILI9341.
Notes and Warnings
NA
AmebaILI9341::reset
Description
Reset the pin to High or Low
Syntax
void AmebaILI9341::reset(void)
Parameters
The function requires no input parameter.
Returns
The function returns nothing.
Example Code
NA
Notes and Warnings
NA
Class SPISettings_SPIClass
SPISettings Class
Members
Public Constructors |
|
---|---|
SPISettings::SPISettings |
Create a SPISettings object and set SPI clock speed, bit order and data mode |
SPISettings::SPISettings
SPIClass Class
Members
Public Constructors |
|
---|---|
SPIClass::SPIClass |
Constructs an SPI object |
Public Methods |
|
SPIClass::transfer |
Transfer data through SPI |
SPIClass::transfer16 |
Transfer a 16-bits data through SPI |
SPIClass::beginTransaction |
Set slave select pin and SPI initial settings |
SPIClass::endTransaction |
Stop SPI transaction |
SPIClass::begin |
Associate each SPI pin to Ameba pin using ameba HAL APIs |
SPIClass::end |
Stop SPI master mode |
SPIClass::setBitOrder |
Set MSB first or LSB first |
SPIClass::setDataMode |
Set to one of the four data modes |
SPIClass::setClockDivider |
Set to correct clock speed (no effect on Ameba) |
SPIClass::setDefaultFrequency |
Set default SPI frequency |
SPIClass::SPIClass
SPIClass::transfer
SPIClass::transfer16
SPIClass::beginTransaction
SPIClass::endTransaction
SPIClass::begin
SPIClass::end
SPIClass::setBitOrder
SPIClass::setDataMode
SPIClass::setClockDivider
SPIClass::setDefaultFrequency
Readme
The Ameba SPI related APIs and examples are works based on SPI Master library for arduino written by Cristian Maglie <c.maglie@arduino.cc> and Paul Stoffregen <paul@pjrc.com> (Transaction API).
These libraries are under GNU Lesser General Public License, version 2.1.
Sys
Wiring_OS_API
Wiring OS API
Members
Public Methods |
|
---|---|
os_thread_create_arduino |
Create a thread and add it to Active Threads and set it to state READY |
os_thread_get_id_arduino |
Return the thread ID of the current running thread |
os_thread_terminate_arduino |
Terminate execution of a thread and remove it from Active Threads |
os_thread_yield_arduino |
Pass control to next thread that is in state READY |
os_thread_set_priority_arduino |
Change priority of an active thread |
os_thread_get_priority_arduino |
Get current priority of an active thread |
os_signal_set_arduino |
Set the specified Signal Flags of an active thread |
os_signal_clear_arduino |
Clear the specified Signal Flags of an active thread |
os_signal_wait_arduino |
Wait for one or more Signal Flags to become signaled for the current RUNNING thread |
os_timer_create_arduino |
Create a timer |
os_timer_start_arduino |
Start or restart a timer |
os_timer_stop_arduino |
Stop the timer |
os_timer_delete_arduino |
Delete a timer that was created by os_timer_create |
os_semaphore_create_arduino |
Create and Initialize a Semaphore object used for managing resources |
os_semaphore_wait_arduino |
Wait until a Semaphore token becomes available |
os_semaphore_release_arduino |
Release a Semaphore token |
os_semaphore_delete_arduino |
Delete a Semaphore that was created by os_semaphore_create |
os_get_free_heap_size_arduino |
Return the available heap memory space when called |
os_thread_create_arduino
os_thread_get_id_arduino
os_thread_terminate_arduino
os_thread_yield_arduino
os_thread_set_priority_arduino
os_thread_get_priority_arduino
os_signal_set_arduino
os_signal_clear_arduino
os_signal_wait_arduino
os_timer_create_arduino
os_timer_start_arduino
os_timer_stop_arduino
os_timer_delete_arduino
os_semaphore_create_arduino
os_semaphore_wait_arduino
os_semaphore_release_arduino
os_semaphore_delete_arduino
os_get_free_heap_size_arduino
WDT
Class WDT
WDT Class
Members
Public Constructors |
|
---|---|
A public constructor should not be used as this class is intended to be a singleton class. Access member functions using the object instance named WDT. |
Public Methods |
|
---|---|
WDT:: InitWatchdog |
Initializes the watchdog, include time setting, and mode register |
WDT:: StartWatchdog |
Start the watchdog counting |
WDT:: StopWatchdog |
Stop the watchdog counting |
WDT:: RefreshWatchdog |
Refresh the watchdog counting to prevent WDT timeout |
WDT:: InitWatchdogIRQ |
Switch the watchdog timer to interrupt mode and register a watchdog timer timeout interrupt handler |
WDT:: InitWatchdog
/*
* This example describes how to use watchdog api.
* In this example, watchdog is setup to 5s timeout.
* Watchdog won’t bark if we refresh it before timeout in smallTask.
* The timer is also reloaded after refresh.
* Otherwise, while running bigTask, watchdog will restart system in default or call callback function if registered.
*/
#include 「wdt.h」
#define RUN_CALLBACK_IF_WATCHDOG_BARKS (0)
WDT wdt;
void setup() {
Serial.begin(115200);
wdt.InitWatchdog(5000); // setup 5s watchdog
#if RUN_CALLBACK_IF_WATCHDOG_BARKS
wdt.InitWatchdogIRQ(my_watchdog_irq_handler, 0);
#else
// system would restart in default when watchdog barks
#endif
wdt.StartWatchdog(); // enable watchdog timer
successfulTask();
failedTask();
while (1)
;
}
void loop() {
}
void successfulTask(void) {
Serial.println(」……doing small task……」);
for (int i = 0; i < 50000000; i++) // dummy task
asm(」 nop」);
Serial.println(「refresh watchdogrn」);
wdt.RefreshWatchdog();
}
/*
* Doing this task will lead to failed refresh the
* watchdog timer within the time limits of 5 seconds
*/
void failedTask(void) {
Serial.println(」……doing big task……」);
for (int i = 0; i < 10; i++) {
Serial.print(「doing dummy task #」);
Serial.println(i, DEC);
for (int j = 0; j < 50000000; j++) // dummy task
asm(」 nop」);
}
Serial.println(「refresh watchdogrn」);
wdt.RefreshWatchdog();
}
void my_watchdog_irq_handler(uint32_t id) {
printf(「watchdog barks!!!rn」);
WDG_Cmd(DISABLE);
}
WDT:: StartWatchdog
WDT:: StopWatchdog
WDT:: RefreshWatchdog
WDT:: InitWatchdogIRQ
WiFi
Class WiFi
WiFiClass Class
Members
Public Constructors |
|
---|---|
WiFiClass::WiFiClass |
Constructs a WiFiClass object and initializes the WiFi libraries and network settings |
Public Methods |
|
WiFiClass::firmwareVersion |
Get firmware version |
WiFiClass:: begin |
Start Wifi connection for OPEN networks |
WiFiClass:: config |
Configure network IP settings |
WiFiClass:: setDNS |
Set the DNS server IP address to use |
WiFiClass:: disconnect |
Disconnect from the network |
WiFiClass:: macAddress |
Get the interface MAC address |
WiFiClass:: localIP |
Get the interface IP address |
WiFiClass:: subnetMask |
Get the interface subnet mask address |
WiFiClass:: gatewayIP |
Get the gateway IP address |
WiFiClass:: SSID |
Return the current SSID associated with the network |
WiFiClass:: BSSID |
Return the current BSSID associated with the network |
WiFiClass:: RSSI |
Return the current RSSI (Received Signal Strength in dBm) associated with the network |
WiFiClass:: encryptionType |
Return the Encryption Type associated with the network |
WiFiClass:: scanNetworks |
Start scan WiFi networks available |
WiFiClass:: SSID |
Return the SSID discovered during the network scan |
WiFiClass:: encryptionType |
Return the encryption type of the networks discovered during the scanNetworks |
WiFiClass:: encryptionTypeEx |
Return the security type and encryption type of the networks discovered during the scanNetworks |
WiFiClass:: RSSI |
Return the RSSI of the networks discovered during the scanNetworks |
WiFiClass:: status |
Return Connection status |
WiFiClass:: hostByName |
Resolve the given hostname to an IP address |
WiFiClass:: apbegin |
Start AP mode |
WiFiClass:: disablePowerSave |
Disable power-saving mode |
WiFiClass::WiFiClass
WiFiClass::firmwareVersion
#include <WiFi.h>
// char ssid[] = 「yourNetwork」; // your network SSID (name)
// char pass[] = 「secretPassword」; // your network password
char ssid[] = 「SINGTEL-D45F」; // your network SSID (name)
char pass[] = 「mooxuteeth」; // your network key
int status = WL_IDLE_STATUS; // the Wifi radio’s status
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to WPA SSID: 「);
Serial.println(ssid);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// you’re connected now, so print out the data:
Serial.print(「You’re connected to the network」);
printCurrentNet();
printWifiData();
}
void loop() {
// check the network connection once every 10 seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print(「MAC address: 「);
Serial.print(mac[0], HEX);
Serial.print(「:」);
Serial.print(mac[1], HEX);
Serial.print(「:」);
Serial.print(mac[2], HEX);
Serial.print(「:」);
Serial.print(mac[3], HEX);
Serial.print(「:」);
Serial.print(mac[4], HEX);
Serial.print(「:」);
Serial.println(mac[5], HEX);
}
void printCurrentNet() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print the MAC address of the router you’re attached to:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print(「BSSID: 「);
Serial.print(bssid[5], HEX);
Serial.print(「:」);
Serial.print(bssid[4], HEX);
Serial.print(「:」);
Serial.print(bssid[3], HEX);
Serial.print(「:」);
Serial.print(bssid[2], HEX);
Serial.print(「:」);
Serial.print(bssid[1], HEX);
Serial.print(「:」);
Serial.println(bssid[0], HEX);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.println(rssi);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print(「Encryption Type:」);
Serial.println(encryption, HEX);
Serial.println();
}
WiFiClass::begin
WiFiClass::config
WiFiClass::setDNS
WiFiClass::disconnect
WiFiClass::macAddress
WiFiClass::localIP
WiFiClass::subnetMask
#include <WiFi.h>
char ssid[] = 「SINGTEL-D45F_5G」; // the name of your network
int status = WL_IDLE_STATUS; // the Wifi radio’s status
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to open SSID: 「);
Serial.println(ssid);
status = WiFi.begin(ssid);
// wait 10 seconds for connection:
delay(10000);
}
// you’re connected now, so print out the data:
Serial.print(「You’re connected to the network」);
printCurrentNet();
printWifiData();
}
void loop() {
// check the network connection once every 10 seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print(「MAC address: 「);
Serial.print(mac[0], HEX);
Serial.print(「:」);
Serial.print(mac[1], HEX);
Serial.print(「:」);
Serial.print(mac[2], HEX);
Serial.print(「:」);
Serial.print(mac[3], HEX);
Serial.print(「:」);
Serial.print(mac[4], HEX);
Serial.print(「:」);
Serial.println(mac[5], HEX);
// print your subnet mask:
IPAddress subnet = WiFi.subnetMask();
Serial.print(「NetMask: 「);
Serial.println(subnet);
// print your gateway address:
IPAddress gateway = WiFi.gatewayIP();
Serial.print(「Gateway: 「);
Serial.println(gateway);
}
void printCurrentNet() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print the MAC address of the router you’re attached to:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print(「BSSID: 「);
Serial.print(bssid[5], HEX);
Serial.print(「:」);
Serial.print(bssid[4], HEX);
Serial.print(「:」);
Serial.print(bssid[3], HEX);
Serial.print(「:」);
Serial.print(bssid[2], HEX);
Serial.print(「:」);
Serial.print(bssid[1], HEX);
Serial.print(「:」);
Serial.println(bssid[0], HEX);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.println(rssi);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print(「Encryption Type:」);
Serial.println(encryption, HEX);
}
WiFiClass::gatewayIP
WiFiClass::SSID
WiFiClass::BSSID
WiFiClass::RSSI
WiFiClass::encryptionType
WiFiClass::scanNetworks
#include <WiFi.h>
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// Print WiFi MAC address:
printMacAddress();
}
void loop() {
// scan for existing networks:
Serial.println(「Scanning available networks…」);
listNetworks();
delay(10000);
}
void printMacAddress() {
// the MAC address of your Wifi shield
byte mac[6];
// print your MAC address:
WiFi.macAddress(mac);
Serial.print(「MAC: 「);
Serial.print(mac[0], HEX);
Serial.print(「:」);
Serial.print(mac[1], HEX);
Serial.print(「:」);
Serial.print(mac[2], HEX);
Serial.print(「:」);
Serial.print(mac[3], HEX);
Serial.print(「:」);
Serial.print(mac[4], HEX);
Serial.print(「:」);
Serial.println(mac[5], HEX);
}
void listNetworks() {
// scan for nearby networks:
Serial.println(」* Scan Networks *」);
int numSsid = WiFi.scanNetworks();
if (numSsid == -1) {
Serial.println(「Couldn’t get a wifi connection」);
while (true);
}
// print the list of networks seen:
Serial.print(「number of available networks:」);
Serial.println(numSsid);
// print the network number and name for each network found:
for (int thisNet = 0; thisNet < numSsid; thisNet++) {
Serial.print(thisNet);
Serial.print(」) 「);
Serial.print(WiFi.SSID(thisNet));
Serial.print(」tSignal: 「);
Serial.print(WiFi.RSSI(thisNet));
Serial.print(」 dBm」);
Serial.print(」tEncryptionRaw: 「);
printEncryptionTypeEx(WiFi.encryptionTypeEx(thisNet));
Serial.print(」tEncryption: 「);
printEncryptionType(WiFi.encryptionType(thisNet));
}
}
void printEncryptionTypeEx(uint32_t thisType) {
/* Arduino wifi api use encryption type to mapping to security type.
* This function demonstrate how to get more richful information of security type.
*/
switch (thisType) {
case SECURITY_OPEN:
Serial.print(「Open」);
break;
case SECURITY_WEP_PSK:
Serial.print(「WEP」);
break;
case SECURITY_WPA_TKIP_PSK:
Serial.print(「WPA TKIP」);
break;
case SECURITY_WPA_AES_PSK:
Serial.print(「WPA AES」);
break;
case SECURITY_WPA2_AES_PSK:
Serial.print(「WPA2 AES」);
break;
case SECURITY_WPA2_TKIP_PSK:
Serial.print(「WPA2 TKIP」);
break;
case SECURITY_WPA2_MIXED_PSK:
Serial.print(「WPA2 Mixed」);
break;
case SECURITY_WPA_WPA2_MIXED:
Serial.print(「WPA/WPA2 AES」);
break;
}
}
void printEncryptionType(int thisType) {
// read the encryption type and print out the name:
switch (thisType) {
case ENC_TYPE_WEP:
Serial.println(「WEP」);
break;
case ENC_TYPE_TKIP:
Serial.println(「WPA」);
break;
case ENC_TYPE_CCMP:
Serial.println(「WPA2」);
break;
case ENC_TYPE_NONE:
Serial.println(「None」);
break;
case ENC_TYPE_AUTO:
Serial.println(「Auto」);
break;
}
}
WiFiClass::SSID
WiFiClass::encryptionType
WiFiClass::encryptionTypeEx
WiFiClass::RSSI
WiFiClass::status
WiFiClass::hostByName
WiFiClass::apbegin
#include
char ssid[] = 「yourNetwork」; //Set the AP’s SSID
char pass[] = 「Password」; //Set the AP’s password
char channel[] = 「1」; //Set the AP’s channel
int status = WL_IDLE_STATUS; // the Wifi radio’s status
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// attempt to start AP:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to start AP with SSID: 「);
Serial.println(ssid);
status = WiFi.apbegin(ssid, pass, channel);
delay(10000);
}
//AP MODE already started:
Serial.println(「AP mode already started」);
Serial.println();
printWifiData();
printCurrentNet();
}
void loop() {
// check the network connection once every 10 seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print your subnet mask:
IPAddress subnet = WiFi.subnetMask();
Serial.print(「NetMask: 「);
Serial.println(subnet);
// print your gateway address:
IPAddress gateway = WiFi.gatewayIP();
Serial.print(「Gateway: 「);
Serial.println(gateway);
Serial.println();
}
void printCurrentNet() {
// print the SSID of the AP:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print the MAC address of AP:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print(「BSSID: 「);
Serial.print(bssid[0], HEX);
Serial.print(「:」);
Serial.print(bssid[1], HEX);
Serial.print(「:」);
Serial.print(bssid[2], HEX);
Serial.print(「:」);
Serial.print(bssid[3], HEX);
Serial.print(「:」);
Serial.print(bssid[4], HEX);
Serial.print(「:」);
Serial.println(bssid[5], HEX);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print(「Encryption Type:」);
Serial.println(encryption, HEX);
Serial.println();
}
WiFiClass::disablePowerSave
Class WiFiClient
WiFiClient Class
Members
Public Constructors |
|
---|---|
WiFiClient::WiFiClient |
Constructs a WiFiClient instance that connects to the specified IP address and port. |
Public Methods |
|
WiFiClient::connect |
Connect to the IP address and port |
WiFiClient::write |
Write a single byte into the packet |
WiFiClient::available |
Number of bytes remaining in the current packet |
WiFiClient::read |
Read a single byte from the current packet |
WiFiClient:: peek |
Return the next byte from the current packet without moving on to the next byte |
WiFiClient:: flush |
Finish reading the current packet |
WiFiClient::stop |
Stop client connection |
WiFiClient::connected |
Check if client is connected, return 1 if connected, 0 if not |
WiFiClient::setRecvTimeout |
Set receiving timeout |
WiFiClient::WiFiClient
#include <WiFi.h>
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「password」; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
//IPAddress server(64,233,189,94); // numeric IP for Google (no DNS)
char server[] = 「www.google.com」; // name address for Google (using DNS)
WiFiClient client;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
;
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to SSID: 「);
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(「Connected to wifi」);
printWifiStatus();
Serial.println(」nStarting connection to server…」);
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println(「connected to server」);
// Make a HTTP request:
client.println(「GET /search?q=ameba HTTP/1.1」);
client.println(「Host: www.google.com」);
client.println(「Connection: close」);
client.println();
}
}
void loop() {
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// if the server’s disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println(「disconnecting from server.」);
client.stop();
// do nothing forevermore:
while (true);
}
}
void printWifiStatus() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.print(rssi);
Serial.println(」 dBm」);
}
WiFiClient::connect
WiFiClient::write
WiFiClient::available
WiFiClient::read
WiFiClient::peek
WiFiClient::flush
WiFiClient::stop
WiFiClient::connected
WiFiClient::setRecvTimeout
Class WiFiServer
WiFiServer Class
Members
Public Constructors |
|
---|---|
WiFiServer::WiFiServer |
Constructs a WiFiServer object and creates a server that listens for incoming connections on the specified port |
Public Methods |
|
WiFiServer::available |
Gets a client that is connected to the server and has data available for reading. The connection persists when the returned client object goes out of scope; you can close it by calling the client.stop() |
WiFiServer::begin |
Tells the server to begin listening for incoming connections |
WiFiServer::write |
Write data to all the clients connected to a server |
WiFiServer::WiFiServer
#include <WiFi.h>
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「secretPassword」; // your network password
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
WiFiServer server(5000);
void setup() {
Serial.begin(9600); // initialize serial communication
pinMode(9, OUTPUT); // set the LED pin mode
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
while (true); // don’t continue
}
String fv = WiFi.firmwareVersion();
if ( fv != 「1.1.0」 )
Serial.println(「Please upgrade the firmware」);
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print(「Attempting to connect to Network named: 「);
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
server.begin(); // start the tcp server on port 5000
printWifiStatus(); // you’re connected now, so print out the status
}
char buffer[256];
void loop() {
WiFiClient client = server.available();
while (client.connected()) {
memset(buffer, 0, 256);
int n = client.read((uint8_t*)(&buffer[0]), sizeof(buffer));
if (n > 0) {
for (int i=0; i<n; i++) {
Serial.print(buffer[i]);
}
n = client.write(buffer, n);
if (n <= 0) break;
}
}
client.stop();
}
void printWifiStatus() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.print(rssi);
Serial.println(」 dBm」);
}
WiFiServer::available
WiFiServer::begin
WiFiServer::write
Class WiFiSSLClient
WiFiSSLClient Class
Members
Public Constructors |
|
---|---|
WiFiSSLClient::WiFiSSLClient |
Constructs a WiFiSSLClient instance that always connects in SSL to the specified IP address and port |
Public Methods |
|
WiFiSSLClient::connect |
Connect to the IP address and port |
WiFiSSLClient::write |
Write a single byte into the packet |
WiFiSSLClient::available |
Number of bytes remaining in the current packet |
WiFiSSLClient::read |
Read a single byte from the current packet |
WiFiSSLClient:: peek |
Return the next byte from the current packet without moving on to the next byte |
WiFiSSLClient:: flush |
Finish reading the current packet |
WiFiSSLClient::stop |
Stop SSL client connection |
WiFiSSLClient::connected |
Check if SSL client is connected, return 1 if connected, 0 if not |
WiFiSSLClient:: setRootCA |
Set Root CA for authentication |
WiFiSSLClient:: setClientCertificate |
Set certificate of the client |
WiFiSSLClient::setRecvTimeout |
Set receiving timeout |
WiFiSSLClient::setPreSharedKey |
Set the pre shared key (PSK) to use for authentication |
WiFiSSLClient::WiFiSSLClient
#include
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「secretPassword」;// your network password (use for WPA, or WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
char server[] = 「www.google.com」; // name address for Google (using DNS)
//unsigned char test_client_key[] = 「」; //For the usage of verifying client
//unsigned char test_client_cert[] = 「」; //For the usage of verifying client
//unsigned char test_ca_cert[] = 「」; //For the usage of verifying server
WiFiSSLClient client;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to SSID: 「);
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid,pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(「Connected to wifi」);
printWifiStatus();
Serial.println(」nStarting connection to server…」);
// if you get a connection, report back via serial:
if (client.connect(server, 443)) { //client.connect(server, 443, test_ca_cert, test_client_cert, test_client_key)
Serial.println(「connected to server」);
// Make a HTTP request:
client.println(「GET /search?q=realtek HTTP/1.0」);
client.println(「Host: www.google.com」);
client.println(「Connection: close」);
client.println();
}
else
Serial.println(「connected to server failed」);
}
void loop() {
// if there are incoming bytes available
// from the server, read them and print them:
while (client.available()) {
char c = client.read();
Serial.write(c);
}
// if the server’s disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println(「disconnecting from server.」);
client.stop();
// do nothing forevermore:
while (true);
}
}
void printWifiStatus() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print(「MAC address: 「);
Serial.print(mac[0], HEX);
Serial.print(「:」);
Serial.print(mac[1], HEX);
Serial.print(「:」);
Serial.print(mac[2], HEX);
Serial.print(「:」);
Serial.print(mac[3], HEX);
Serial.print(「:」);
Serial.print(mac[4], HEX);
Serial.print(「:」);
Serial.println(mac[5], HEX);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.print(rssi);
Serial.println(」 dBm」);
}
WiFiSSLClient::connect
WiFiSSLClient::write
WiFiSSLClient::available
WiFiSSLClient::read
WiFiSSLClient::peek
WiFiSSLClient::flush
WiFiSSLClient::stop
WiFiSSLClient::connected
WiFiSSLClient::setRootCA
WiFiSSLClient::setClientCertificate
WiFiSSLClient::setRecvTimeout
WiFiSSLClient::setPreSharedKey
Class WiFiUdp
WiFiUDP Class
Members
Public Constructors |
|
---|---|
WiFiUDP::WiFiUDP |
Constructs a WiFiUDP instance of the WiFi UDP class that can send and receive UDP messages |
Public Methods |
|
WiFiUDP:: begin |
initialize, start listening on the specified port. Returns 1 if successful, 0 if there are no sockets available to use |
WiFiUDP:: stop |
Finish with the UDP socket |
WiFiUDP:: beginPacket |
Start building up a packet to send to the remote host-specific in IP and port |
WiFiUDP:: endPacket |
Finish off this packet and send it |
WiFiUDP:: write |
Write a single byte into the packet |
WiFiUDP:: writeImmediately |
Send packet immediately from the buffer |
WiFiUDP:: parsePacket |
Start processing the next available incoming packet |
WiFiUDP::available |
Number of bytes remaining in the current packet |
WiFiUDP::read |
Read a single byte from the current packet |
WiFiUDP:: peek |
Return the next byte from the current packet without moving on to the next byte |
WiFiUDP:: flush |
Finish reading the current packet |
WiFiUDP:: remoteIP |
Return the IP address of the host who sent the current incoming packet |
WiFiUDP:: remotePort |
Return the port of the host who sent the current incoming packet |
WiFiUDP:: setRecvTimeout |
Set receiving timeout |
WiFiUDP::WiFiUDP
#include <WiFi.h>
#include <WiFiUdp.h>
int status = WL_IDLE_STATUS;
char ssid[] = 「yourNetwork」; // your network SSID (name)
char pass[] = 「secretPassword」; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
unsigned int localPort = 2390; // local port to listen on
char packetBuffer[255]; //buffer to hold incoming packet
char ReplyBuffer[] = 「acknowledged」; // a string to send back
WiFiUDP Udp;
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println(「WiFi shield not present」);
// don’t continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != 「1.1.0」) {
Serial.println(「Please upgrade the firmware」);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print(「Attempting to connect to SSID: 「);
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid,pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println(「Connected to wifi」);
printWifiStatus();
Serial.println(」nStarting connection to server…」);
// if you get a connection, report back via serial:
Udp.begin(localPort);
}
void loop() {
// if there’s data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize) {
Serial.print(「Received packet of size 「);
Serial.println(packetSize);
Serial.print(「From 「);
IPAddress remoteIp = Udp.remoteIP();
Serial.print(remoteIp);
Serial.print(」, port 「);
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
int len = Udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
}
Serial.println(「Contents:」);
Serial.println(packetBuffer);
// send a reply, to the IP address and port that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
}
}
void printWifiStatus() {
// print the SSID of the network you’re attached to:
Serial.print(「SSID: 「);
Serial.println(WiFi.SSID());
// print your WiFi shield’s IP address:
IPAddress ip = WiFi.localIP();
Serial.print(「IP Address: 「);
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print(「signal strength (RSSI):」);
Serial.print(rssi);
Serial.println(」 dBm」);
}
WiFiUDP::begin
WiFiUDP::stop
WiFiUDP::beginPacket
WiFiUDP::endPacket
WiFiUDP::write
WiFiUDP::writeImmediately
WiFiUDP::parsePacket
WiFiUDP::available
WiFiUDP::read
WiFiUDP::peek
WiFiUDP::flush
WiFiUDP::remoteIP
WiFiUDP::remotePort
WiFiUDP::setRecvTimeout
Readme
WiFi.cpp
WiFi.h
WiFiServer.cpp
WiFiServer.h
WiFiUdp.cpp
WiFiUdp.h
Wire
Class TwoWire
TwoWire Class
Members
Public Constructors |
|
---|---|
TwoWire::TwoWire |
Constructs a TwoWire object |
Public Methods |
|
TwoWire::begin |
Initialize I2C master/slave |
TwoWire::setClock |
Set I2C frequency |
TwoWire::beginTransmission |
Begin I2C transmission |
TwoWire::endTransmission |
End I2C transmission |
TwoWire::requestFrom |
Set I2C requestFrom |
TwoWire::write |
Write data to I2C |
TwoWire::available |
Check if I2C is available |
TwoWire::read |
Read data from I2C |
TwoWire::peek |
Read peek from I2C |
TwoWire::flush |
Do nothing, use, and transmission(..) to force data transfer |
TwoWire::onReceive |
Callback function when I2C on receive |
TwoWire::onRequest |
Callback function when I2C on request |
TwoWire::TwoWire
#include <Wire.h>
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
}
byte x = 0;
void loop() {
Wire.beginTransmission(8); // transmit to device #8
Wire.write(「x is 「); // sends five bytes
Wire.write(x); // sends one byte
Wire.endTransmission(); // stop transmitting
x++;
delay(500);
}
Example: MasterReader
#include <Wire.h>
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
Serial.begin(9600); // start serial for output
}
void loop() {
Wire.requestFrom(8, 6); // request 6 bytes from slave device #8
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);
}
This example demonstrates the use of the wire library reads data from an I2C/TWI slave device.
TwoWire::begin
TwoWire::setClock
TwoWire::beginTransmission
TwoWire::endTransmission
WARNING: Nothing in the library keeps track of whether the bus tenure has been properly ended with a STOP. It is very possible to leave the bus in a hung state if no call to endTransmission(true) is made. Some I2C devices will behave oddly if they do not see a STOP.
If the input parameter is void, this provides backward compatibility with the original definition, and expected behavior, of endTransmission.
TwoWire::requestFrom
TwoWire::write
TwoWire::available
TwoWire::read
TwoWire::peek
TwoWire::flush
TwoWire::onReceive
TwoWire::onRequest
Wire_Readme
The Ameba LCD related api and example are works based on “New LiquidCrystal library” (https://bitbucket.org/fmalpartida/new-liquidcrystal/).
These include,
These files inherit the licence of “New LiquidCrystal Library” which are under a Creative Commons Attribution-ShareAlike 3.0 Unported License. CC BY-SA 3.0.
Resources
Links
支援
常見問題
如何購買 Ameba RTL8722DM Board?
請參考 購買連結。
RTL8722CSM/RTL8722DM 支持哪些藍牙標準?
兩者皆支援 BLE 5.0。 Classic Bluetooth (BR/EDR) 則不支援。
支持哪些BLE設備?
RTL8722CSM/RTL8722DM 可當作 BLE Central 或 BLE Peripheral 設備。
RTL8722CSM /RTL8722DM上的所有接腳都可用嗎?
不,標有“NC”的未連接到任何接腳,因此無法使用。
RTL8722CSM/RTL8722DM 有支援 XIP (execute in place)嗎?
有支援。
RTL8722CSM 有支援 5G WiFi 嗎?
不,只有 RTL8722DM 支援雙頻 2.4G + 5G WiFi。 RTL8722CSM 只有支援單頻 2.4G WiFi。
如何進入下載模式?
按住UART DOWNLOAD按鈕,然後按下RESET按鈕並放開UART DOWNLOAD和RESET按鈕。
故障排除
無法找到藍牙裝置RTL8722CSM/RTL8722DM
請確保天線連接正確。 檢查您的程式碼有確認正確的藍牙配置。
程式碼操作不如預期
嘗試使用``printf()`` 和
Serial.print()
語法除錯。 如果問題仍然存在,您可以在論壇尋求幫助
連接到RTL8722CSM / RTL8722DM UART後,為什麼串行終端上沒有輸出?
RTL8722CSM / RTL8722DM 默認配置為115200波特率,請檢查串行終端是否配置為115200。
程序無法下載到RTL8722CSM / RTL8722DM中
- 請按照以下步驟正確下載。
請進入下載模式。 進入下載模式時,開發版綠色LED指示燈將閃爍。
下載過程中,開發版紅色LED指示燈將閃爍。
下載成功後,Arduino IDE會出現通知。
WiFi有時信號較弱
RTL8722CSM / RTL8722DM 的預設天線使用I-Pex連接器。 請更換/連接I-Pex連接器天線。
為什麼開發版無法上電?
請確認已連接電阻R43旁的連接器J38。 該連接器用於將電源鏈接到IC。
遇到開發板連接到電腦的驅動程式問題?
請參考下列USB 驅動程式 https://ftdichip.com/drivers /。
MicroPython SDK
歡迎來到 Ameba MicroPython 綫上文檔
快速入門手冊
Ameba MicroPython: 適用於 RTL8722DM 的快速入門手冊
環境配置
AmebaD RTL8722CSM/RTL8722DM MicroPython SDK 目前支持 Windows 10 和 Linux 操作系統。
AmebaD RTL8722CSM/RTL8722DM介紹
Ameba是一個易於編程的微控制器平台,可用於開發各種物聯網應用程序。AmebaD有各種外圍接口,包括WiFi, BLE, GPIO, I2C, UART, SPI, PWM, ADC。通過這些接口,AmebaD可以連接LED、開關、壓力計、濕度計、PM2.5粉塵傳感器等電子元件。
Ameba所收集的數據可以通過WiFi無線上傳,並被智能設備上的應用程序使用,實現物聯網的應用。
AmebaD和Arduino Uno的尺寸類似,如上圖所示,並且AmebaD上的引腳與Arduino Uno兼容。
引脚名 |
GPIO |
ADC |
PWM |
UART |
SPI |
I2C |
|
---|---|---|---|---|---|---|---|
D00 |
GPIOB_2 |
✓ |
ADC5 |
UART3_RX(b) |
|||
D01 |
GPIOB_1 |
✓ |
ADC4 |
UART3_TX(b) |
|||
D02 |
GPIOB_3 |
✓ |
ADC6 |
||||
D03 |
GPIOB_31 |
✓ |
|||||
D04 |
GPIOB_30 |
✓ |
|||||
D05 |
GPIOB_28 |
✓ |
|||||
D06 |
GPIOB_29 |
✓ |
|||||
D07 |
NC |
||||||
D08 |
GPIOB_22 |
✓ |
PWM14 |
||||
D09 |
GPIOB_23 |
✓ |
PWM15 |
||||
D10 |
GPIOB_21 |
✓ |
PWM13 |
UART0_RTS(b) |
SPI0_CS |
||
D11 |
GPIOB_18 |
✓ |
PWM10 |
UART0_RX(b) |
SPI0_MOSI |
||
D12 |
GPIOB_19 |
✓ |
PWM11 |
UART0_TX(b) |
SPI0_MISO |
||
D13 |
GPIOB_20 |
✓ |
PWM12 |
UART0_CTS(b) |
SPI0_CLK |
||
D14 |
GPIOA_7 |
✓ |
UART2_TX(log) |
||||
D15 |
GPIOA_8 |
✓ |
UART2_RX(log) |
||||
D16 |
GPIOA_25 |
✓ |
PWM4 |
UART3_RX(a) |
I2C0_SCL |
||
D17 |
GPIOA_26 |
✓ |
PWM5 |
UART3_TX(a) |
I2C0_SDA |
||
D18 |
GPIOB_7 |
✓ |
ADC3 |
PWM17 |
SPI1_CS |
||
D19 |
GPIOB_6 |
✓ |
ADC2 |
SPI1_CLK |
|||
D20 |
GPIOB_5 |
✓ |
ADC1 |
PWM9 |
SPI1_MISO |
||
D21 |
GPIOB_4 |
✓ |
ADC0 |
PWM8 |
SPI1_MOSI |
||
D22 |
GPIOA_28 |
✓ |
|||||
D23 |
GPIOA_24 |
✓ |
PWM3 |
UART0_CTS(a) |
I2C1_SDA |
||
D24 |
GPIOA_23 |
✓ |
PWM2 |
UART0_RTS(a) |
I2C1_SCL |
||
D25 |
GPIOA_22 |
✓ |
UART0_RX(a) |
||||
D26 |
GPIOA_21 |
✓ |
UART0_TX(a) |
||||
D27 |
GPIOA_20 |
✓ |
|||||
D28 |
GPIOA_19 |
✓ |
備註
RTL8722 MicroPython 移植簡介
基本背景
REPL
代表Read-Evaluation-Print-Loop,它是一個交互式提示,可用於存取和控制微控制器。
REPL
具有其他強大的特色,例如tab處理,行編輯,自動縮排,輸入歷史記錄等。 它的基本功能類似於標準的 Python IDLE,但是運行在微控制器上。
要使用 REPL
,只需在PC上打開任何串行終端軟件(最常用的工具是 TeraTerm, Putty 等),然後連接到微控制器的串行端口,然後將波特率設置為 115200
,然後手動重置開發板,即可看到 >>>
MicroPython提示符出現在終端畫面上。 您就可以在REPL上輸入任何Python腳本。
建議多嘗試使用 “ help()
” 函數以獲得更多資訊。例如,微控制器上電並顯示REPL後,只需鍵入
>>> help()
You will see a help page giving you more details about this port; also if you type
>>> help(modules)
它將列出所有可用的內建模塊供您使用。
此外,如果您想了解有關模塊的更多資訊,例如可用的API和CONSTANT,只需鍵入以下代碼來獲取該模塊的詳細信息。
>>> help(the module of your interest)
讓我們以Pin模塊(GPIO)為例:
>>> help(Pin)
object <class 'Pin'> is of type type
id -- <function>
init -- <function>
value -- <function>
off -- <function>
on -- <function>
toggle -- <function>
board -- <class 'board'>
IN -- 0
OUT -- 1
PULL_NONE -- 0
PULL_UP -- 1
PULL_DOWN -- 2
REPL 快捷鍵
Ctrl + d
MicroPython將執行軟件重啟,這在您的微控制器表現異常時非常有用。並且將再次執行 “boot.py” 中的腳本。請注意,這只會重置MicroPython interpreter 而不重置硬件,所有先前配置的硬件將保持原樣,直到您手動重置開發板為止。
Ctrl + e
此快捷鍵會將
REPL
設置粘貼模式,在粘貼模式下,可以一次將一大部分的代碼粘貼到REPL中,而無需一行一行地執行代碼。 適合當您找到MicroPython庫並希望通過複製和貼上立即對其進行測試時。Ctrl + b
此快捷鍵會將
REPL
重置為普通模式, 您可以利用該指令解決某些模式下的卡死。Ctrl + c
此熱鍵可幫助您快速取消任何輸入並另起一行
設置開發環境
步驟1: 安裝驅動程序
首先,通過Micro USB將AmebaD連接到電腦:
步驟2: 安裝相關工具
對於Windows用戶,請安裝串行終端軟件。 最常見的串行終端是 Tera Term
和 Putty
,在這裡我們建議使用 Tera Term
,可以從網路下載。
對於希望從頭開始編譯MicroPython的用戶,請確保安裝 Cygwin
,這是在Windows系統上運行的類似Linux的環境。選擇 Cygwin
安裝程序時,我們建議使用 Cygwin
32位元版本。在 Cygwin
安裝期間,安裝程序將提示用戶是否安裝其他軟件,請確保從“ Devel
”類別中選擇 make
的GNU版本(請參見下圖),然後選擇最新版本。
另外,在固件編譯過程中需要 Python3,因此請確保從其官方網站下載最新的 Python3,並在安裝過程中要求時將其添加為環境變量。
對於Linux用戶,請使用 apt-get
安裝命令安裝您選擇的串行終端軟件。 在這裡,我們建議使用 picocom
。
對於有興趣在C語言中開發 MicroPython 模塊的用戶,請確保安裝了至少 3.82 或更高版本的 GNU make 軟件以及 Python3。
將固件上傳到Ameba
步驟2: 進入 UART 下載模式
請先按住 UART_DOWNLOAD
按鈕,然後按 RESET
按鈕。 如果成功,您應該在 Ameba 上看到綠色的 LED 閃爍。
步驟3: 運行 “Double-Click-Me-to-Upload”
顧名思義,雙擊該文件以運行它,然後按照屏幕上顯示的說明更新 Ameba 的串行COM端口,這樣上傳就可以成功進行。 上傳成功後,您將在屏幕上看到一行日誌 – “All images are sent successfully”。
嘗試第一個範例
步驟1: 打開 REPL
REPL 代表 讀取(Read) ,評估(Evaluation) ,打印(Print) 和 循環(Loop),它是 MicroPython 的終端,供用戶控制微控制器
打開Tera Term後,如上圖所示選擇“Serial”,然後使用下拉列表選擇 Ameba 的串行端口,然後單擊“OK”。 如果您的串行終端未配置為 115200
波特率,建議將 115200
設定為默認設置。
現在已經連接了串行端口,在 Ameba 上按一下 RESET
按鈕,如下所示會看到 MicroPython 的歡迎頁面。
過程為Ameba首先檢查其校準數據,然後啟動MicroPython的固件,接著再運行 boot.py
Python腳本和導入的內建python庫。
現在試著輸入
>>> help()
查看更多信息,然後輸入
>>> help(modules)
檢查所有現成可用的python庫。
步驟2: 執行WiFi掃描範例
由於大多數外圍設備的範例都需要額外的硬件才能顯示該範例是否正常運行,因此我們將僅以WiFi掃描範例為例,來了解使用MicroPython控制WiFi是十分容易的。
現在,請複製並貼上以下代碼,或手動將其輸入 Tera Term
,然後按“Enter”。
from wireless import WLAN
wifi = WLAN(mode = WLAN.STA)
wifi.scan()
您應該能夠看到返回周圍無線網絡的結果
(完結)
資源下載
版本記錄
版本 1.0.2 release - 2021/10/14
特徵
添加 MacOS 工具鏈以支援在 MacOS 上構建
RTL8722DM MINI 的預測試通過
API 更新
使用新的 API 更新 PWM 模組
重新構建 SDFS 模組,並在沒有 SD 卡時刪除警告
其他
更新無線局域網和其他庫
更新 readme 文檔
版本 1.0.1 release - 2021/06/07
特徵
添加了對固件上傳(非編譯)的 MacOS 支援
修復了迴圈的 PWM API 問題
Implemented SDFS (SD FileSystem) module [Currently only support RTL8722DM_mini]
更新歡迎消息和説明消息
更新 Ameba SDK 和 庫
固定網路和 WLAN 安全問題
修復與WiFi相關的錯誤
更新 readme 文檔
修復與WiFi相關的錯誤
版本 1.0.0 release - 2020/11/11
特徵
OS Support Windows and Linux
WiFi
Socket
ADC
內置説明
修復與WiFi相關的錯誤
版本 0.0.1 alpha release - 2020/09/29
特徵
基本功能移植
實現 REPL 和基本終端功能
為 RTL8722 添加了引腳映射
添加了外設幫助程式模組:
GPIO
RTC
Time and Delay
PWM
Timer
UART
I2C
SPI
範例演示
週邊硬體相關範例
[RTL8722CSM] [RTL8722DM] ADC - 讀取電位器數值
材料準備
Ameba x 1
電位器 x 1
範例說明
這裏我們把ameba連接到一個電位器上來讀取它的數值,連接方式如下:
複製粘貼以下代碼到REPL上
1import socket
2a = ADC(0)
3a.read()
[RTL8722CSM] [RTL8722DM] GPIO - 閃爍LED
材料準備
Ameba x 1
LED x 1
電阻(阻值200歐姆)x 1
範例說明
閃爍LED是開始瞭解並使用MicroPython最好示例。
首先,如下圖所示將PB_22引脚連接到與限流電阻串聯的LED的陽極引脚,再將GND連接到LED的陰極引脚:
然後,複製以下代碼並在 REPL
界面中按 Ctrl + E
進入 REPL
的粘貼模式(有關 REPL
和粘貼模式的更多信息,請前往“../getting_started/getting_started”頁面)。如果使用 Tera Term
,只需右鍵單擊終端的任何空白處即可將代碼粘貼到 REPL
,然後按 Ctrl + D
執行代碼。
from machine import Pin
a = Pin("PB_22", Pin.OUT)
a.value(1)
time.sleep_ms(500)
a.value(0)
time.sleep_ms(500)
a.on()
time.sleep_ms(500)
a.off()
time.sleep_ms(500)
a.toggle()
time.sleep_ms(500)
a.toggle()
[RTL8722CSM] [RTL8722DM] I2C - 發送與接收
材料準備
Ameba x 1
Arduino UNO x 1
範例說明
I2C是一個微控制器上非常常見的模塊,它只需要兩根綫就可以實現最大3.4Mbps的傳輸速度。它使用主從模式,一個主機可以同時連接最多128個從機,因此經常用在微控制器與感應器之間的數據傳輸。
這裏我們使用ameba作爲主機來連接從機Arduino UNO,來驗證I2C的發送和接受。
在連接之前,請先將以下代碼上傳到Arduino UNO中 “Examples -> Wire -> Slave_receiver”
接下來,請按以下所示來連接,此處我們選擇PA_26 作爲 SDA引脚,PA_25 作爲 SCL.
備註
目前僅支持一組I2C在MicroPython上使用,引脚如下
编号 |
SDA |
SCL |
---|---|---|
0 |
PA_26 |
PA_25 |
請一行接一行地複製粘貼以下代碼到REPL上,來觀察代碼效果。
1from machine import Pin, I2C
2i2c = I2C(scl = "PA_25", sda = "PA_26", freq=100000) # configure I2C with pins and freq. of 100KHz
3i2c.scan()
4i2c.writeto(8, 123) # send 1 byte to slave with address 8
5i2c.readfrom(8, 6) # receive 6 bytes from slave
[RTL8722CSM] [RTL8722DM] PWM - LED 漸變
材料準備
Ameba x 1
LED x 1
電阻(220歐姆) x 1
範例說明
PWM脈寬調變控制輸出脈波週期來實現對LED亮度和馬達的控制。 下面是我們用LED來展示PWM是如何來實做的。
連接PA_26至LED的正極和電阻串聯在一起, 然後GND接至LED負極。如圖所示
然後, 逐行複製下面的代碼去REPL並觀察結果, LED會慢慢的漸變明亮。
1from machine import Pin, PWM
2import time
3p = PWM(pin = "PA_26")
4# 0 duty cycle thus output 0
5p.write(0.0)
6# 10% duty cycle
7p.write(0.1)
8# 50% duty cycle
9p.write(0.5)
10# 100% duty cycle
11p.write(1.0)
[RTL8722CSM] [RTL8722DM] RTC -時間顯示
材料準備
Ameba x 1
範例說明
RTC 模組會幫助微控制器來追蹤時間,是時間模組必須的一部分。我們在這裏有一個示例,來展示如何來得到本地時間和上傳時間。
複製下面的代碼貼至REPL,觀察結果。
1rtc = RTC()
2rtc.datetime() # get date and time
3rtc.datetime((2020, 12, 31, 4, 23, 58, 59, 0)) # set a specific date and time (year, month, day, weekday(0 for Monday), hour, minute, second, total seconds)
4rtc.datetime() # check the updated date and time
[RTL8722CSM] [RTL8722DM] Socket - Echo服務器與客戶端
材料準備
Ameba x 2
範例說明
WiFi連接完成後即可使用Socket來使用網路。 Socket就像一個假想的乙太網路介面,你可以用它把你的PC連接到互聯網上的服務器上,比如Google或Github。
即使是像HTTP這樣的應用層協議也是建立在socket之上的。一旦給定了IP地址和端口號,就可以自由地連接到遠程設備並與其進行通信。連接流程如下圖所示。
下面是一個使用服務器socket和客戶端socket互相傳送消息的範例,要使用這個範例,您需要兩個ameba RTL8722來運行MicroPython,在REPL 的paste模式下分別將下面的代碼複製並粘貼到兩個 Ameba 設備中。
以下是 服務器 代碼
1import socket
2from wireless import WLAN
3wifi = WLAN(mode = WLAN.STA)
4wifi.connect(ssid = "YourWiFiSSID", pswd = "YourWiFiPassword") # change the ssid and pswd to yours
5s = socket.SOCK()
6port = 5000
7s.bind(port)
8s.listen()
9conn, addr = s.accept()
10while True:
11 data = conn.recv(1024)
12 conn.send(data+"from server")
以下是 客戶端 代碼
1import socket
2from wireless import WLAN
3wifi = WLAN(mode = WLAN.STA)
4wifi.connect(ssid = "YourWiFiSSID", pswd = "YourWiFiPassword") # change the ssid and pswd to yours
5c = socket.SOCK()
6# make sure to check the server IP address and update in the next line of code
7c.connect("your server IP address", 5000)
8c.send("hello world")
9data = c.recv(1024)
10print(data)
[RTL8722CSM] [RTL8722DM] Socket - 從HTTP網站獲取信息
材料準備
Ameba x 1
範例說明
創建socket後,我們可以訪問HTTP網站並從中獲取信息。
在粘貼模式下,將以下代碼複製並粘貼到REPL中。
1import socket
2from wireless import WLAN
3wifi = WLAN(mode = WLAN.STA)
4wifi.connect(ssid = "YourWiFiSSID", pswd = "YourPassword") # change the ssid and pswd to yours
5def http_get(url):
6 _, _, host, path = url.split('/', 3)
7 c = socket.SOCK()
8 # We are visiting MicroPython official website's test page
9 c.connect(host, 80)
10 c.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
11 while True:
12 data = c.recv(100)
13 if data:
14 print(str(data,'utf8'), end='')
15 else:
16 break
17http_get('http://micropython.org/ks/test.html')
[RTL8722CSM] [RTL8722DM] SPI - 作爲從設備接收消息
材料準備
Ameba x 1
Arduino UNO x 1
範例說明
SPI是一種快速且强大的通訊協議,並通常在微處理器中被用來接受傳感器的數據或輸出圖像訊號。在這個示例中將示範ameba如何透過MicroPython以從屬模式接收數據。
在通訊連接建立之前,需要先將以下代碼燒錄到Arduino UNO。
1///////////////////////
2// SPI Master Write //
3///////////////////////
4#include <SPI.h>
5void setup (void) {
6 Serial.begin(115200); //set baud rate to 115200 for usart
7 digitalWrite(SS, HIGH); // disable Slave Select
8 SPI.begin ();
9}
10void loop (void) {
11 char c;
12 digitalWrite(SS, LOW); // enable Slave Select
13 // send test string
14 for (const char * p = "Hello, world!\r" ; c = *p; p++) {
15 SPI.transfer(c);
16 Serial.print(c);
17 }
18 Serial.println();
19 digitalWrite(SS, HIGH); // disable Slave Select
20 delay(2000);
21}
Arduino UNO將以如下圖所示的連接方式和Ameba連接,我們使用第“0”組SPI作爲從機, 並將Arduino UNO當作SPI的主機。
然後複製以下代碼並粘貼到REPL的粘貼模式窗口,並等待代碼生效。
1from machine import SPI
2s1= SPI(0 , mode = SPI.SLAVE)
3for i in range(14):
4chr(s1.read())
[RTL8722CSM] [RTL8722DM] Time - 延遲和計時
材料準備
Ameba x 1
範例說明
MicroPython 提供了很多函數來處理延遲和計時,以下是一些示例。
複製下面的代碼至REP來觀察結果。
1import time
2time.sleep(1) # sleep for 1 second
3time.sleep_ms(500) # sleep for 500 milliseconds
4time.sleep_us(10) # sleep for 10 microseconds
5start = time.ticks_ms() # get millisecond counter
[RTL8722CSM] [RTL8722DM] Timer -週期性定時器
材料準備
Ameba x 1
範例說明
這裏有3個定時器可以使用, 全部是32kHz, 分別是定時器1/2/3。我們使用定時器1來示範一個週期性定時器是怎樣工作的。
複製下面最初的3行代碼至REPL來查看結果。
1from machine import Timer
2t = Timer(1) # Use Timer 1/2/3 only
3t.start(2000000, t.PERIODICAL) # Set GTimer fired periodically at duration of 2 seconds, printing text on the terminal
4# To stop the periodical timer, type
5t.stop()
–timer triggered. to stop: type t.stop()–
的log將在終端中每隔 2 秒顯示一次[RTL8722CSM] [RTL8722DM] UART - 發送和接收
材料準備
Ameba x 1
USB轉TTL串行模塊 x 1
範例說明
UART是一種非常通用的通信協議,是微控制器的一個重要組成部分。USB轉TTL串行傳輸模塊是一種可以將UART信號轉換為USB信號的集成電路,以便我們可以在PC上看到UART日誌。該模塊經常用於包括Ameba在內的許多開發板上。 但是,該模塊在Ameba上的功能被保留用於LOG UART和固件上傳,所以我們需要其他獨立模塊在Ameba和PC之間進行通信。
當前有2組UART引脚供MicroPython用戶使用,它們分別是
Unit |
傳輸引脚 |
接收引脚 |
---|---|---|
0 |
PA_21 |
PA_22 |
3 |
PA_26 |
PA_25 |
PA_21
和 PA_22
然後,將以下代碼逐行複制並粘貼到REPL中,以查看其效果。
1from machine import UART
2uart = UART(tx="PA_21", rx= "PA_22")
3uart.init()
4uart.write('hello')
5uart.read(5) # read up to 5 bytes
[RTL8722DM_MINI] SDFS 資料編輯
材料準備
Ameba RTL8722DM_MINI x 1
MicroSD卡 x 1 (SD卡必須 < 32GB,格式設置為 fatfs)
範例說明
SD文件系統模塊支持SD卡數據操作。可以隨時控制和查看文件,並將它們保存在非揮發性記憶體中。
將以下代碼逐行複制粘貼到REPL中來使用。
1from machine import SDFS
2s=SDFS() # create a short form
3s.create("ameba.txt") # create a file named "ameba.txt"
4s.write("ameba.txt", "ameba supports sd card file system!") # write a string to the file just created
5s.read("ameba.txt") # read the content from the same file
6s.rm("ameba.txt") # delete the file
備註
不需要打開或關閉文件,API 會自動為您完成。
網路相關範例
[RTL8722CSM] [RTL8722DM] WiFi - WiFi 連接
材料準備
Ameba x 1
範例說明
Ameba可以使用開放安全性或WPA2安全類型連接到WiFi接入點,WPA2安全類型是家用無線路由器中最常用的安全類型。
在這裡我們將使用下面的代碼連接到WiFi接入點,將以下代碼逐行複制並粘貼到REPL中,以查看其作用。
1from wireless import WLAN
2wifi = WLAN(mode = WLAN.STA)
3wifi.connect(ssid = "YourWiFiName", pswd = "YourWiFiPassword")
[RTL8722CSM] [RTL8722DM] WiFi - WiFi 掃描
材料準備
Ameba x 1
範例說明
WiFi掃描功能可以幫助我們快速發現周圍有哪些WiFi網絡。
該範例不需要任何其他硬件,因此只需複製以下代碼並將其粘貼到REPL中即可查看其作用。
1from wireless import WLAN
2wifi = WLAN(mode = WLAN.STA)
3wifi.scan()
開發板 HDK
開發板
RTL8722DM 模組
API 文档
RTL8722DM MicroPython 线上 API 文档
ADC
API 文檔
構造函數
unit
: 組號,每個組號對應一個引脚. 請查閱圖表來瞭解更多。
Unit |
Pin |
---|---|
0 |
PB_4 |
1 |
PB_5 |
2 |
PB_6 |
3 |
PB_7 |
4 |
PB_1 |
5 |
PB_2 |
6 |
PB_3 |
方法
I2C
API 文档
构造函数
unit_id
: 硬件I2C的组号, 如不填则使用默认值"sda_pin"
: SDA引脚名"scl_pin"
: SCL引脚名frequency
: I2C 的运行频率, 如不填则使用默认值
備註
所有选填参数的默认值如下
参数 |
Default |
---|---|
默认值 |
0 |
Frequency |
100000 (Hz) |
方法
buf: 一个string / array /byte array 类型的缓存器
flag: 一个布尔标记, 如果是True则在数据末尾发送 NACK, 反则反之
buf: 一个string / array /byte array 类型的缓存器
addr: 读取的地址
len: 要读取的数据长度
stop: 布尔标记,若True则在传输结束发送STOP字节
addr: 读取的地址
buf: 一个string / array /byte array 类型的缓存器
stop: 布尔标记,若True则在传输结束发送STOP字节
addr: 写入的地址
value: 要发送的整数数值
stop: 布尔标记,若True则在传输结束发送STOP字节
Pin
API 文档
构造函数
「pin_name」`: 引脚名称,必须为字符串格式,可使用 help(Pin.board) 查看所有引脚的名称
方向
Pin.IN
– 输入引脚Pin.OUT
- 输出引脚
模式
Pin.PULL_NONE
– 没有上拉电阻或下拉电阻Pin.PULL_UP
– 启用上拉电阻Pin.PULL_DOWN
– 启用下拉电阻默认值 –
Pin.PULL_NONE
value
: 初始值,并且仅适用于输出,例如value = 1
。默认值value = 0
.
方法
输出 number 数值
number 的数值可以是 0 或者 1, 用来表示逻辑状态的 0 或 1
检查当前引脚状态
当没有数值输入时,无论引脚配置方向,此方法都会查看当前引脚的逻辑状态(0/1)
PWM
API 文档
构造函数
unit
: PWM的号码, 如果没有填写预设是0"pin_name"
: pin的名字, 此名字必须是string格式. 参考下列PWM支持的pins
備註
方法
dutycycle_float: 浮点duty cycle,可以从0.0(0%)到1.0(100%)
RTC
API 文檔
构造函数
方法
- 如果没有输入任何参数,会返还本地时间。格式如下:(年, 月, 日, 时, 分, 秒, 周[0-6表示周一到周日],年[1-366])。
- 如果是输入一个8位数组的参数,会更新本地时间。格式和上面一致。
SDFS
API 文檔
構造函數
sdfs
object and configure it to the given mode. This then allows you to navigate through the SD card and read/write files as you see.備註
No parameter is required
Methods
folder name: the name of the new folder/directory you wish to create, it must be a string less than 128 characters
folder name: the name of the folder/directory you wish to navigate to, it must be a string less than 128 characters
備註
Key in “/” as the parameter to this API would navigate back to the root directory.
folder name or file name: the name of the folder or file you wish to delete, it must be a string less than 128 characters
file name: The name of the file you wish to create.
file name: The name of the file you wish to read.
string: The data you wish to write.
file name: The name of the file you wish to read.
Socket
API 文檔
构造函数
domain
: 地址域类型. 默认为AF_INET
AF_INET
: IPv4,常见的IP地址,以点为分隔符,正在渐渐被IPv6取代AF_INET6
: IPv6,以冒号为分隔符的IP地址
type
: 类型, 默认为SOCK_STREAM
SOCK_STREAM
: TCP 类型SOCK_DGRAM
: UDP 类型
方法
host: 字符串格式的服务器地址
port: 整数格式的端口号
port: 整数格式的端口号
length: 预期接收的数据长度
buffer: 一个array/bytearray/string 类型的缓存器
seconds: timeou时间(秒)
SPI
API 文檔
构造函数
unit_id
: 表示SPI硬件的ID, 如果保留空白,则采用默认值baudrate
: SPI传输速度polarity
: 决定SPI工作模式的变量 (不推荐使用)phase
: 决定SPI工作模式的变量 (不推荐使用)databits
: 数据字节数量Firstbit
: 决定首字节是最高有效位 (MSB)或最低有效位 (LSB)miso`
: miso 引脚 (不推荐使用)mosi
: mosi 引脚 (不推荐使用)sck
: clock 引脚 (不推荐使用)mode
: 决定MASTER 模式或是SLAVE 模式
備註
所有选填参数的初始值设定如下表所示:
参数 |
默认值 |
---|---|
Baudrate |
2000000 Hz |
Polarity |
Inactive_low |
Phase |
Toggle_middle |
Databits |
8 |
Firstbit |
MSB |
Miso |
N.A. |
Mosi |
N.A. |
Sck |
N.A. |
Mode |
MASTER |
目前Ameba D支持并提供2对SPI供使用:
unit |
MOSI |
MISO |
SCK |
CS |
---|---|---|---|---|
0 |
PB_18 |
PB_19 |
PB_20 |
PB_21 |
1 |
PB_4 |
PB_5 |
PB_6 |
PB_7 |
備註
上述所有SPI组号都支持主机模式(Master),但是仅有 第 0 组
适用于从机模式.
方法
value: 将写入SPI bus的一个整数数值
Time
API 文檔
构造函数
N.A.
方法
seconds: 秒数,必须是整数
milliseconds: 毫秒数,必须是整数
microseconds: 微秒数,必须是整数
time.localtime()
。它的参数是一个按照 time.localtime()
来表达的完整8项元组。它会返还一个整数,此整数是从2000年一月一日到现在的秒数。tuple: 一个来表达的完整8项元组
ticks_add()
, ticks_diff()
一起使用。starting_ticks: 从
ticks_ms()
拿到的毫秒数时间ticks_added: 要增加的ticks
end_ticks
时间和 starting_ticks
时间的差值。end_ticks: 从
ticks_ms()
拿到的毫秒数时间starting_ticks: 从
ticks_ms()
拿到的毫秒数时间
Timer
API 文檔
构造函数
unit
: 可以是 1 / 2 / 3, 对应定时器 1 / 2 / 3
方法
microseconds: 微秒数间隔,必须是整数。
type: 单次,或周期性定时器。
duration_us: 时间长度,计量单位是微秒us。
UART
API 文檔
构造函数
unit
: 代表可使用UART引脚组的ID,可输入0或3baudrate
: 在Ameba上使用115200databits
: 数据字节的数量,通常为7到8个字节stopbits
: 停止位的字节数量,通常为1字节,1.5字节或2 字节paritybit
: 用于奇偶校验,数值通常为none(无),odd(奇)或even(偶)timeout
: 计算UART在超时(timeout)之前等待的时间 (以毫秒为单位)tx_pin
: 发送端引脚,通常与接受器的RX引脚连接rx_pin
: 接收端引脚,通常与发送器的TX引脚连接
備註
并非所有参数都是必需的,因此如果不填,MicroPython将采用其默认值,下表为所有选填参数的默认值
参数 |
默认值 |
---|---|
Unit |
0 |
Baudrate |
115200 |
Databits |
8 |
Stopbits |
1 |
Paritybit |
0 |
Timeout |
10 (ms) |
方法
length: 接收数据的长度
buffer: 字节缓存区,可以存放的数据类型有字符串类型,整型等其他类型。
当没有传入任何参数,该方法检查UART中断请求(IRQ)的状态,如果启用了IRQ,它将返回True;如果禁用IRQ,则返回False
通过传入True/False来启用/禁用UART IRQ处理程序
function: 在Python中定义的函数或lambda函数
WiFi
API 文檔
Constructors
mode
:WLAN.STA
是 station 模式
方法
ssid: WiFi 网络的名称
pswd: WiFi网络的密码
security: WiFi网络的安全协议
備註
如果没有填写选填的参数,会使用下面的预设数值。
参数 |
默认值 |
---|---|
pswd |
NULL |
security |
WPA2_AES_PSK |
備註
pswd
,security = WLAN.OPEN
。相關資源
支援
常見問題
什麼是MicroPython以及如何使用它?
有關更多資訊,請參考 MicroPython官方網站 。
可以使用所有的Python標準函式庫嗎?
不可以,MicroPython僅支持Python標準函式庫的一小部分。但是可以通過將標準的python庫移植到MicroPython來使用。
RTL8722CSM / RTL8722DM上的所有引腳都可用嗎?
不可以,那些標有“NC”的因未連接到任何引腳,因此無法使用。
RTL8722CSM是否支持5G WiFi?
否。僅RTL8722DM支持雙頻2.4G + 5G WiFi。 RTL8722CSM僅支持單頻段2.4G WiFi。
如何進入下載模式?
按住UART DOWNLOAD按鈕。 然後按下RESET按鈕並釋放UART DOWNLOAD和RESET按鈕。
故障排除
MicroPython 韌體編譯失敗
在構建過程中,某些用戶可能會遇到導致過程暫停的錯誤,這是由於缺少系統環境設置而導致的,可以通過以下方法進行修復。
與python相關的錯誤
預設下,MicroPython使用 Python3 運行 MicroPython kernal 的構建腳本,如果遇到與python相關的錯誤,可能是因為 Python3 檔案相關路徑未添加到系統環境變量中。
但是,如果已經添加了環境變量,但是構建依舊無法完成,則可以嘗試
重新啟動電腦
在終端上輸入“python”,如果顯示的python是 Python3,則請添加`PYTHON = python`到“port/rtl8722”文件夾路徑下“Makefile”的第二行與MPY-CROSS相關的錯誤
如果構建過程停止並顯示錯誤為mpy-cross,則需要執行以下步驟
到“MicroPython_RTL8722/mpy-cross”文件夾下
打開您的Cygwin/Linux終端,然後輸入`make`等待MicroPython Cross Compiler的構建完成,然後應該可以修復錯誤
程式碼未按預期運行
嘗試使用 print( ) 函數調試程序,並在API頁面詳細了解每個API。
為什麼不斷從REPL收到“syntax error”?
請注意MicroPython僅支持 Python3 語法
如何將Python腳本上傳到Ameba開發板?
有3種方式將Python代碼上傳到Ameba開發板
通過REPL normal模式
在一般的REPL模式下,您可以逐行粘貼代碼到REPL上並按順序執行它們,但是請注意,在使用條件檢查或循環時(例如“if”或“while”),代碼將被自動縮排,不正確的縮排將導致腳本錯誤。
通過REPL paste模式
在一般的REPL模式下,按“Ctrl” +“e”可以進入paste模式,paste模式僅允許粘貼完整的程式碼,粘貼不完整的程式碼或編輯會導致語法錯誤。
通過mp_frozenmodules
將python腳本放入“rtl8722”路徑下的“mp_frozenmodules”文件夾中,您的程式碼將被嵌入到MicroPython固件中並上傳到Ameba,接著您只需導入python腳本的名稱即可使用它。
連接到RTL8722CSM / RTL8722DM UART後,為什麼串行終端上沒有輸出結果?
RTL8722CSM / RTL8722DM 默認配置為
115200`
baudrate,請檢查串行終端是否配置為115200
。
程序沒有被下載到RTL8722CSM / RTL8722DM中?
- 請按照以下步驟正確下載:
進入下載模式。 進入下載模式時,開發板上的綠色LED會閃爍
下載固件時,開發板上的紅色LED將閃爍
成功下載後,您將看到類似“All images sent successfully”的訊息
爲什麽有時WiFi信號較弱?
RTL8722CSM / RTL8722DM的天線預設是使用 I-Pex 接口。 請更換/連接I-Pex 接口的天線。
為什麼我的開發板無法上電?
請確保已連接電阻R43旁的connector J38。 該連接器用於將電源鏈接到IC。
遇到開發板連接到電腦的驅動程式問題?
請參考下列USB 驅動程式 https://ftdichip.com/drivers /。
瑞昱標準 SDK
入門指南
GCC 開發環境的設置
Cygwin
用作 GCC 開發環境。Cygwin 是 GNU 和開源工具的集合,類似於提供 Linux 相關的功能在 Windows 平台上使用。Cygwin
。Cygwin
package 過程中, 如下圖所示在 Select Packages 頁面中選擇 Devel -> make 與 Math -> bc 功能。備註
對於 Linux,請參考 AN0400 Ameba-D Application Note v12.pdf 來建立GCC開發環境。
Ameba-D 開發板的相關介紹
Ameba-D 開發板的硬件圖如下所示:
連接串口
SecureCRT
、Teraterm
與 Putty
等終端工具查看串口訊息。在 Ameba-D 上建立第一個 GCC 項目
以下步驟供首次開發人員在現有 RTK SDK 下構建GCC項目。
Cygwin
終端,並使用 $ cd
命令將目錄更改為 Ameba-D SDK 的 KM0 或 KM4 項目目錄。備註
需要將 {path}
替換成自己的 SDK 位置,並在 SDK 位置前面添加前綴 “cygdrive”
,以便 Cygwin
可以訪問您的文件系統。
$ cd /cygdrive/{path}/project/realtek_amebaD_va0_example/GCC-RELEASE/project_lp
$ cd /cygdrive/{path}/project/realtek_amebaD_va0_example/GCC-RELEASE/project_hp
對於 Linux,請打開自己的終端,然後使用 $ cd
命令將目錄更改為 Ameba-D SDK 的 KM0 或 KM4 項目目錄。
$ cd /{path}/project/realtek_amebaD_va0_example/GCC-RELEASE/project_lp
$ cd /{path}/project/realtek_amebaD_va0_example/GCC-RELEASE/project_hp
要構建一般固件的SDK,只需在Cygwin(Windows)或終端(Linux)上相應目錄下使用命令。KM0 project 對於 KM0,如果終端輸出訊息包含 “km0_image2_all.bin”
和 “Image manipulating end”
,則表示固件已成功構建,如下所示。
$ make clean
然後重新執行 make
。KM4 專案 對於 KM4,如果終端輸出訊息包含 “km0_image2_all.bin”
和 “Image manipulating end”
,則表示固件已成功構建,如下所示。
$ make clean
然後重新執行 make。project/realtek_amebaD_va0_example/GCC-RELEASE/project_hp/asdk/image
下,如下圖所示。下載固件至 Ameba-D
瑞昱提供了 Image Tool 在 Windows 中可以方便下載固件
假設 PC 上的 Image Tool 是服務器,它將通過 UART 將固件檔案發送到 Ameba(客戶端)。要將檔案從服務器下載到客戶端,客戶端必須首先進入 UART download 模式。
進入 UART_DOWNLOAD 模式
按下 UART DOWNLOAD 按鈕並保持按下狀態
重新打開電源,或按重置按鈕
放開 UART DOWNLOAD 按鈕
現在Ameba 板 進入 UART_DOWNLOAD 模式並準備接收數據。
點選 UI上 的 Chip Select(紅色),然後選擇芯片(AmebaD 或 AmebaZ)
選擇相應的串行端口和傳輸波特率, 默認波特率是 1.5Mbps(推薦)
點選瀏覽按鈕以選擇要編程的固件(km0_boot_all.bin / km4_boot_all.bin / km0_km4_image2.bin)與其位址
- 固件位址為
{path}\project\realtek_amebaD_va0_example\GCC-RELEASE\project_lp\asdk\image
與{path}\project\realtek_amebaD_va0_example\GCC-RELEASE\project_hp\asdk\image
,為自己電腦上項目的位址。 默認目標地址是SDK默認固件地址,您可以直接使用它。
點選下載按鈕 進度條將顯示每個固件的傳輸進度並且可以從日誌窗口獲取操作成功消息或錯誤消息。
資源下載
版本紀錄
版本 1.0.0 – 2021/10/12
硬體資訊:
中央處理器: 32 位 KM4(Arm Cortex-M33 相容)和 32 位 KM0(Arm Cortex-M23 相容)
記憶體:512KB 單片記憶體 + 4MB 單片記憶體
特徵:
集成 802.11a/n 無線局域網 SoC
USB 主機/設備
SD Host
BLE5.0
Codec
LCDC
Key Matrix
1 PCM interface
4 UART interface
1 I2S Interface
2 I2C interface
7 ADC
17 PWM
Max 54 GPIO
開發板 HDK
AmebaD HDK 資源下載
支援
常見問題
如何購買 Ameba RTL8722DM Board?
請參考 購買連結。
故障排除
遇到開發板連接到電腦的驅動程式問題?
請參考下列USB驅動程式 https://ftdichip.com/drivers/。
小訣竅