欢迎来到 Ameba IoT 家族 SDK 线上文档!
Arduino SDK
AMB21 (RTL8722DM)
Welcome to AMB21 Arduino online documentation.
Getting Started
Ameba ARDUINO: Getting Started with AMB21
Required Environment
AMB21 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[AMB21 / AMB22]
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 |
✓ |
✓ |
||||
D09 |
GPIOB_23 |
✓ |
✓ |
||||
D10 |
GPIOB_21 |
✓ |
✓ |
UART0_RTS(b) |
SPI0_CS |
||
D11 |
GPIOB_18 |
✓ |
✓ |
UART0_RX(b) |
SPI0_MOSI |
||
D12 |
GPIOB_19 |
✓ |
✓ |
UART0_TX(b) |
SPI0_MISO |
||
D13 |
GPIOB_20 |
✓ |
✓ |
UART0_CTS(b) |
SPI0_CLK |
||
D14 |
GPIOA_7 |
✓ |
UART2_TX(log) |
||||
D15 |
GPIOA_8 |
✓ |
UART2_RX(log) |
||||
D16 |
GPIOA_25 |
✓ |
✓ |
UART3_RX(a) |
I2C0_SCL |
||
D17 |
GPIOA_26 |
✓ |
✓ |
UART3_TX(a) |
I2C0_SDA |
||
D18 |
GPIOB_7 |
✓ |
ADC3 |
✓ |
SPI1_CS |
||
D19 |
GPIOB_6 |
✓ |
ADC2 |
SPI1_CLK |
|||
D20 |
GPIOB_5 |
✓ |
ADC1 |
✓ |
SPI1_MISO |
||
D21 |
GPIOB_4 |
✓ |
ADC0 |
✓ |
SPI1_MOSI |
||
D22 |
GPIOA_28 |
✓ |
|||||
D23 |
GPIOA_24 |
✓ |
✓ |
UART0_CTS(a) |
I2C1_SDA |
||
D24 |
GPIOA_23 |
✓ |
✓ |
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 AMB21 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 AMB21, and the examples of Arduino can run on AMB21 too. Arduino IDE can be downloaded in the Arduino website.
When the installation is finished, open Arduino IDE. To set up AMB21 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-M33 @200MHz)” in the list, click “Install”, then the Arduino IDE starts to download required files for AMB21.
“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-M33 @200MHz)”` in the list, click “Install”, then the Arduino IDE starts to download required files for AMB21.
Finally, we select AMB21 as current connected board in “Tools” -> “Board” -> “Ameba ARM (32-bits) Boards” ->” AMB21”:
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 Support page.
Release History
Version 3.1.2 - 2021/12/28
Feature:
Update SimpleWebServerWiFi example
Support BW16
API Updates:
Update Wlan related naming from “AmebaWiFi” become “WiFi”
Update RTC library for minor bug fix
Misc:
Update all Fritzing files for new name updates
AMB21, AMB22, AMB23, and BW16
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
AMB21 (RTL8722DM/CSM) Supported ARDUINO built-in example table
There are many built-in examples in Arduino. In the table below, we list all examples that are compatible with Ameba.
Category |
Name |
Comment |
Remarks |
---|---|---|---|
01. Basics |
AnalogReadSerial |
Connect potentiometer to 3.3V. |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
BareMinimum |
|||
Blink |
Pin LED_BUILTIN sets to pin D8. |
||
DigitalReadSerial |
|||
Fade |
|||
ReadAnalogVoltage |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
02. Digital |
BlinkWithoutDelay |
Pin LED_BUILTIN sets to pin D8. |
|
Button |
Connect LED to pin D13. |
||
Debounce |
Connect LED to pin D13. |
||
Digital InputPullup |
Connect LED to pin D13. |
||
StateChange Detection |
Connect LED to pin D13. |
||
toneKeyboard |
|||
toneMelody |
|||
toneMultiple |
|||
tonePitch Follower |
|||
03. Analog |
Analog InOutSerial |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
|
AnalogInput |
Connect LED to pin D13. |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
|
Analog Write Mega |
|||
Calibration |
Connect another LED to pin D13. |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
|
Fading |
|||
Smoothing |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
04. Communication |
ASCIITable |
||
Dimmer |
|||
Graph |
Connect potentiometer to 3.3V. |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
|
Midi |
Use Serial1 and pin D26, or use Serial2 and pin D17. |
||
MultiSerial |
|||
PhysicalPixel |
|||
Read ASCIIString |
|||
SerialCallResponse |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
SerialCallResponse ASCII |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
SerialEvent |
|||
Serial Passthrough |
Serial options, Serial1 or Serial2. |
||
Virtual ColorMixer |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
05. Control |
Arrays |
Use pins D1, D2, D3, D4, D5, D6. |
|
ForLoop Iteration |
Use pins D1, D2, D3, D4, D5, D6. |
||
IfStatement Conditional |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
switchCase |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
switchCase2 |
Use pins D1, D2, D3, D4, D5, D6. |
||
While Statement Conditional |
Connect another LED to pin D13. |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
|
06. Display |
barGraph |
Use another pin to replace pin D7. |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
RowColumn Scanning |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
07. Strings |
Character Analysis |
||
StringAddition Operator |
|||
StringAppend Operator |
|||
String CaseChanges |
|||
String Characters |
|||
StringComparision Operators |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
StringIndexOf |
|||
StringLength |
|||
StringLengthTrim |
|||
StringReplace |
|||
StringStartsWith EndsWith |
|||
StringSubstring |
|||
StringToInt |
Network Examples
BLE - BLE Battery Service
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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.
AMB21 / AMB22:
AMB23:
BW16:
“Files” -> “Examples” -> “AmebaBLE” ->
“DHT_over_BLEUart”
.BLE – PWM over BLE UART
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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).
AMB21 /AMB22:
AMB23:
BW16:
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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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.
HTTP - Retrieve HTTP websites from the Internet
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
HTTP - Set up Server to Control LED
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Breadboard x 1
LED x 1
1KΩ Resistor x 1
Procedure
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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.HTTP - Set up Server to Get the Ameba Status
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.HTTP - Use IFTTT for Web Service
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 [AMB21 / AMB22 / AMB23 / BW16] 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.
IPv6 – Ameba as IPv6 Server/Client over TCP
Materials
AmebaD [AMB21 / AMB22 / AMB23 / 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 [AMB21 / AMB22 / AMB23 / 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,
MDNS - Set up mDNS Client on Arduino IDE
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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);
MQTT - Set up MQTT Client to Communicate with Broker
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 [AMB21 / AMB22 / AMB23 / BW16] 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.
MQTT - Set up MQTT Client over TLS
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Example
“File” -> “Examples” ->
“AmebaMQTTClient” -> “MQTT_TLS”
MQTT - Use Amazon AWS IoT Shadow Service
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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);
MQTT - Use Google Cloud IoT
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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);
MQTT - Upload PM2.5 Data to LASS System
Intro to LASS
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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
.NTP - Retrieve Universal Time (UTC) by NTPClient library
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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();
WiFi - Approximate UDP Receive Delay
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
WiFi - Approximate UDP Sending Delay
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
WiFi - Approximate UDP Receive Timeout
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
WiFi - Connect to WiFi networks
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.WiFi - Retrieve Universal Time (UTC) by UDP
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Example
“File” -> “Examples” -> “AmebaWiFi” -> “WiFiUdpNtpClient”
WiFi - Scan the surrounding WiFi networks
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Antenna x 1
AmebaD [:raw-html:`<p style=”color:#1A76B4;”>AMB21(RTL8722DM/CSM)</p>` / AMB23(RTL8722DM_MINI) / BW16(RTL8729DN)] 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.WiFi - Set up Server to communicate
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.WiFi - Set up Client to Retrieve Google Search Information
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.WiFi - Set up UDP Server to Communicate
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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()
.WiFi - Set up WiFi 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 [AMB21 / AMB22 / AMB23 / BW16] 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:
WiFi - Set up SSL Client for HTTPS Communication
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
Components Used
Humidity & temperature sensor
|
Distance measurement function
|
TFT LCD display with SPI interface
|
|
QVGA TFT LCD display module
|
High-quality GPS positioning module
|
Servo with high output power
|
Peripheral Examples
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
AmebaD [AMB21 / AMB22] 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
Audio Codec – Basic Input Output
Materials
AmebaD [AMB21 / AMB22 / AMB23] 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 [AMB21 / AMB22 / AMB23] x 1
Example
"Files" -> "Examples" -> “AmebaAudioCodec” -> “FFT”
.Audio Codec - Input FFT
Materials
AmebaD [AMB21 / AMB22 / AMB23] 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 [AMB21 / AMB22 / AMB23] x 1
3.5mm TRS/TRRS breakout x 1 (e.g., Adafruit 2791 / Sparkfun 11570)
Example
Procedure
Open the example, "Files" -> "Examples" -> “AmebaAudioCodec” ->
“OutputSineWave”
.
E-Paper - Display Images
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
Front view of the e-Paper Module:
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
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 [AMB21 / AMB22 / AMB23 / BW16] x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
Front view of the e-Paper Module:
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
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 [AMB21 / AMB22 / AMB23 / BW16] x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
Front view of the e-Paper Module:
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
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
Flash Memory - Store data in FlashEEProm
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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);
GPIO - Measure Distance By Ultrasound Module
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
HC-SR04 Ultrasonic x 1
Dropping resistor or Level converter
Example
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 Wiring Diagram:
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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 - Measure Temperature and Humidity
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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 [AMB21 / AMB22 / AMB23 / BW16] 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”
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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.
GTimer - Using The Periodic GTimer
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / 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);
GTimer - Using the One-Time Gtimer
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / 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.
I2C - Send Data to Arduino UNO
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 [AMB21 / AMB22 / AMB23 / BW16] 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
AMB21/ AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 Wiring Diagram:
Code Reference
I2C - Display Data On LCD Screen
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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 - Receive Data from Arduino UNO
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.IR - Transmit IR NEC Raw Data And Decode
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16 ] 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.
Figure 11 and Figure 12 shows the pin configuration of IR Emitter and Receiver with Ameba RTL8720DN (BW16).
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
Power Save - Deep Sleep Mode
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Example
Introduction
Ameba-D supports 2 low power modes which are deepsleep mode and sleep mode. Deep Sleep mode turns off more power domain than sleep mode. The power consumption of Deep Sleep mode is around 7μA to 8μA as compared to normal state which is around 22mA. This example describes how to enter Deep Sleep mode and configure the wakeup source
AON Timer(SET_DS_AON_TIMER_WAKEUP);
AON GPIO pins(SET_AONWAKEPIN_WAKEUP);
RTC Timer(SET_DS_RTC_WAKEUP);
AON_TIMER_SLEEP_DURATION
SET_AON_GPIO_WAKEUP_GPIOA25
or the pin that you want to use as shown in the picture belowDS_RTC_ALARM_DAY
,
DS_RTC_ALARM_HOUR
, DS_RTC_ALARM_MIN
, and DS_RTC_ALARM_SEC
AON Timer
AON GPIO Pin
RTC Timer
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
Power Save - Deep Sleep for DHT and E-paper
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON_TIMER_SLEEP_DURATION
SET_AON_GPIO_WAKEUP_GPIOA25
or the pin that you want to use as shown in the picture below.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 for DHT and LCD
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON_TIMER_SLEEP_DURATION
SET_AON_GPIO_WAKEUP_GPIOA25
or the pin that you want to use as shown in the picture below.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 [AMB21 / AMB22 / AMB23 / BW16] 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.
LOGUART(SET_TL_UART_WAKEUP);
RTC Timer(SET_TL_RTC_WAKEUP);
AON pins(SET_AON_WAKEPIN_WAKEUP);
LOGUART
RTC Timer
AON GPIO Pins
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
PWM - Play Music by Buzzer
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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:
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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 - Servo Control
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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);
RTC - Simple RTC
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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
RTC - Simple RTC Alarm
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
SPI – Print Image And Text On LCD Screen
If you are not familiar with SPI, please read Introduction to SPI first.
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
AMB21/ AMB22 and QVGA TFT LCD Wiring Diagram:
AMB23 and QVGA TFT LCD Wiring Diagram:
BW16 and QVGA TFT LCD Wiring Diagram:
AMB21 / AMB22 and Adafruit 2.8’’ TFT LCD touch shield Wiring Diagram:
AMB23 and Adafruit 2.8’’ TFT LCD touch shield Wiring Diagram:
BW16 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 [AMB21 / AMB22 / AMB23 / BW16] 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.
TensorFlow Lite - Hello World
Materials
AmebaD [AMB21 / AMB22 / AMB23] 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 [AMB21 / AMB22 / AMB23] 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 [AMB21 / AMB22 / AMB23] 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 [AMB21 / AMB22 / AMB23] 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
UART - Communicate with PC over USB to Serial Module
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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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.
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
AMB23 Wiring Diagram:
Open the example in “Files” -> “Examples” ->
“AmebaSoftwareSerial” -> “Adafruit_GPS_parsing”
.
UART – Set Callback Function For UART Communications
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
USB to TTL Adapter x 1
Example
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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.
UART - PM2.5 Concentration in The Air
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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.
Watchdog - Simple WDG Timer
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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”
:Community Examples
小技巧
Welcome to share your examples under the Community Examples section if you have completed a project using the Ameba boards
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
Support
FAQ
Where to buy Ameba RTL8722DM Board?
Refer to Purchase link.
Which Bluetooth standards are supported by RTL8722CSM/RTL8722DM?
Both boards support BLE 5.0. Classic Bluetooth (BR/EDR) is not supported.
Which BLE roles are supported?
RTL8722CSM/RTL8722DM can operate as either a BLE Central or BLE Peripheral device.
Are all pins on RTL8722CSM/RTL8722DM usable?
No, those marked
NC
are not connected to any pin and thus unusable.
Is XIP (execute in place) supported on RTL8722CSM/RTL8722DM?
Yes, it is supported.
Does RTL8722CSM support 5G WiFi?
No. Only RTL8722DM supports dual band 2.4G + 5G WiFi. RTL8722CSM only supports single band 2.4G WiFi.
How to enter the download mode?
Press and hold the UART DOWNLOAD button. Then Press the RESET button and release both UART DOWNLOAD and RESET buttons.
Trouble shooting
RTL8722CSM/RTL8722DM cannot be found as a Bluetooth device.
Please make sure the antenna is connected properly. Check your code for the correct Bluetooth configurations.
My code is not behaving as I expected.
Try to debug your program using
printf()
andSerial.print()
statements. If the issue persists, you can ask for help at Forums
Why is there no output on my serial terminal after connecting to RTL8722CSM/RTL8722DM UART?
RTL8722CSM/RTL8722DM is by default configured at 115200 baudrate, please check if your serial terminal is configured to 115200.
My program is not being downloaded into RTL8722CSM/RTL8722DM?
- Please follow the procedure for the correct downloading:
Enter the download mode. The on-board Green LED will blink when entered download mode.
When downloading the image into board the on-board Red LED will blink
After a successful download, you will see log like this “All images sent successfully”.
Sometimes WiFi signal is weak?
The default antenna for RTL8722CSM/RTL8722DM uses the I-Pex Connector. Please change/connect the I-Pex Connector antenna.
Why is my board not powering up?
Please make sure the connector J38 beside resistor R43 is connected. The connector is used to link the power to IC.
If you have driver issue to connect board to your computer?
Please go to https://ftdichip.com/drivers/ for USB driver.
AMB23 (RTL8722DM MINI)
Welcome to AMB23 Arduino online documentation.
Getting Started
Ameba ARDUINO: Getting Started with AMB23
Required Environment
AMB23 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[AMB23]
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.
AMB23 has smaller size than Arduino Uno, as shown in the above figure.
# |
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 |
Setting up Development Environment
Step 1. Installing the Driver
First, connect AMB23 to the computer via Micro USB (same as power):
Step 2. Set up Arduino IDE
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-M33 @200MHz)” in the list, click “Install”, then the Arduino IDE starts to download required files for AmebaD.
“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-M33 @200MHz)”` in the list, click “Install”, then the Arduino IDE starts to download required files for AmebaD.
Finally, we select AmebaD as current connected board in “Tools” -> “Board” -> “Ameba ARM (32-bits) Boards” ->” RTL8722DM MINI”:
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 onboard green LED and blue LED all turned off.
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
(End)
备注
If you face any issue, please refer to the FAQ and Trouble shooting sections on Support page.
Peripherals & Examples
Basic Examples
AMB23 (RTL8722DM_MINI) Supported ARDUINO built-in example table
There are many built-in examples in Arduino. In the table below, we list all examples that are compatible with Ameba.
Category |
Name |
Comment |
Remarks |
---|---|---|---|
01. Basics |
AnalogRead Serial |
Connect potentiometer to 3.3V. |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
Bare Minimum |
|||
Blink |
Pin LED_BUILTIN sets to LED_B |
Onboard LEDs options LED_B and LED_G. (blue and green) |
|
DigitalRead Serial |
Onboard button PUSH_BTN. |
||
Fade |
Replace “led = 9;” by a PWM pin (D4, D5, D7, D12, D13, D14, D17, D20, or D21). e.g. “led = 4;” |
||
ReadAnalog Voltage |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
02. Digital |
BlinkWitout Delay |
The onboard blue LED (LED_B) has been used. |
Onboard LEDs options LED_G. |
Button |
Onboard LEDs options LED_B and LED_G. Onboard button PUSH_BTN. |
||
Debounce |
Onboard LEDs options LED_B and LED_G. Onboard button PUSH_BTN. |
||
DigitalInput Pullup |
Onboard LEDs options LED_B and LED_G. |
||
StateChange Detection |
Onboard LEDs options LED_B and LED_G. Onboard button PUSH_BTN. |
||
toneKeyboard |
Replace “tone(8, notes[thisSensor], 20);” by a PWM pin (D4, D5, D7, D12, D13, D14, D17, D20, or D21). e.g. “tone(21, notes[thisSensor], 20);” |
||
toneMelody |
|||
tone Multiple |
|||
tonePitch Follower |
|||
03. Analog |
AnalogIn OutSerial |
Replace “analogOutPin = 9;” by a PWM pin (D4, D5, D7, D12, D13, D14, D17, D20, or D21). e.g. “analogOutPin = 4;” |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
AnalogInput |
Onboard LEDs options LED_B and LED_G. ADC pin reading voltage range 0 to 3.3V. |
||
Analog Write Mega |
Use PWM pins D4, D5, D7, D12, D13, D14, D17, D20, or D21. |
||
Calibration |
Onboard LEDs options LED_B and LED_G. Onboard button PUSH_BTN. ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
Fading |
Replace “ledPin = 9;” by a PWM pin (D4, D5, D7, D12, D13, D14, D17, D20, or D21). e.g. “ledPin = 4;” |
||
Smoothing |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
04. Communication |
ASCIITable |
||
Dimmer |
Onboard LEDs options LED_B and LED_G. |
||
Graph |
Connect potentiometer to 3.3V. |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
|
Midi |
Use Serial1 and pin D18, or use Serial2 and pin D1. |
||
MultiSerial |
|||
Physical Pixel |
Onboard LEDs options LED_B and LED_G. |
||
ReadASCII String |
Use PWM pin for LED (D4, D5, D7, D12, D13, D14, D17, D20, or D21). |
||
SerialCall Response |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
Serial CallResponse ASCII |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
SerialEvent |
|||
SerialPa ssthrough |
Serial options, Serial1 or Serial2. |
||
VirtualColor Mixer |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
05. Control |
Arrays |
Use pins D1, D2, D3, D4, D5, D6. |
|
ForLoop Iteration |
Use pins D1, D2, D3, D4, D5, D6. |
||
IfStatement Conditional |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. Onboard LEDs options LED_B and LED_G. |
||
switchCase |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
switchCase2 |
Use pins D1, D2, D3, D4, D5, D6. |
||
WhileStatement Conditional |
Replace “ledPin = 9;” by a PWM pin (D4, D5, D7, D12, D13, D14, D17, D20, or D21). e.g. “ledPin = 4;” |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
|
06. Display |
barGraph |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
|
RowColumn Scanning |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
07. Strings |
Character Analysis |
||
String Addition Operator |
|||
String Append Operator |
|||
StringCase Changes |
|||
String Characters |
|||
String Comparison Operators |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. ADC pin reading voltage range 0 to 3.3V. |
||
String IndexOf |
|||
String Length |
|||
StringLength Trim |
|||
String Replace |
|||
String StartsWith EndsWith |
|||
String Substring |
|||
String ToInt |
Network Examples
BLE - BLE Battery Service
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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.
AMB21 / AMB22:
AMB23:
BW16:
“Files” -> “Examples” -> “AmebaBLE” ->
“DHT_over_BLEUart”
.BLE – PWM over BLE UART
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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).
AMB21 /AMB22:
AMB23:
BW16:
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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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.
HTTP - Retrieve HTTP websites from the Internet
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
HTTP - Set up Server to Control LED
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Breadboard x 1
LED x 1
1KΩ Resistor x 1
Procedure
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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.HTTP - Set up Server to Get the Ameba Status
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.HTTP - Use IFTTT for Web Service
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 [AMB21 / AMB22 / AMB23 / BW16] 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.
IPv6 – Ameba as IPv6 Server/Client over TCP
Materials
AmebaD [AMB21 / AMB22 / AMB23 / 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 [AMB21 / AMB22 / AMB23 / 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,
MDNS - Set up mDNS Client on Arduino IDE
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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);
MQTT - Set up MQTT Client to Communicate with Broker
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 [AMB21 / AMB22 / AMB23 / BW16] 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.
MQTT - Set up MQTT Client over TLS
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Example
“File” -> “Examples” ->
“AmebaMQTTClient” -> “MQTT_TLS”
MQTT - Use Amazon AWS IoT Shadow Service
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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);
MQTT - Use Google Cloud IoT
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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);
MQTT - Upload PM2.5 Data to LASS System
Intro to LASS
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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
.NTP - Retrieve Universal Time (UTC) by NTPClient library
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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();
WiFi - Approximate UDP Receive Delay
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
WiFi - Approximate UDP Sending Delay
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
WiFi - Approximate UDP Receive Timeout
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
WiFi - Connect to WiFi networks
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.WiFi - Retrieve Universal Time (UTC) by UDP
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Example
“File” -> “Examples” -> “AmebaWiFi” -> “WiFiUdpNtpClient”
WiFi - Scan the surrounding WiFi networks
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Antenna x 1
AmebaD [:raw-html:`<p style=”color:#1A76B4;”>AMB21(RTL8722DM/CSM)</p>` / AMB23(RTL8722DM_MINI) / BW16(RTL8729DN)] 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.WiFi - Set up Server to communicate
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.WiFi - Set up Client to Retrieve Google Search Information
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.WiFi - Set up UDP Server to Communicate
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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()
.WiFi - Set up WiFi 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 [AMB21 / AMB22 / AMB23 / BW16] 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:
WiFi - Set up SSL Client for HTTPS Communication
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
Components Used
Humidity & temperature sensor
|
Distance measurement function
|
TFT LCD display with SPI interface
|
|
QVGA TFT LCD display module
|
High-quality GPS positioning module
|
Servo with high output power
|
Peripheral Examples
Audio Codec – Basic Input Output
Materials
AmebaD [AMB21 / AMB22 / AMB23] 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 [AMB21 / AMB22 / AMB23] x 1
Example
"Files" -> "Examples" -> “AmebaAudioCodec” -> “FFT”
.Audio Codec - Input FFT
Materials
AmebaD [AMB21 / AMB22 / AMB23] 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 [AMB21 / AMB22 / AMB23] 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 [AMB23] x 1
MicroSD card
Example
Procedure
As AMB23 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”
.
E-Paper - Display Images
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
Front view of the e-Paper Module:
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
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 [AMB21 / AMB22 / AMB23 / BW16] x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
Front view of the e-Paper Module:
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
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 [AMB21 / AMB22 / AMB23 / BW16] x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
Front view of the e-Paper Module:
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
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
FatfsSDIO – File system in SD card
Materials
AmebaD [AMB23] 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 [AMB23] 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.
Flash Memory - Store data in FlashEEProm
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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);
GPIO - Measure Distance By Ultrasound Module
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
HC-SR04 Ultrasonic x 1
Dropping resistor or Level converter
Example
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 Wiring Diagram:
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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 - Measure Temperature and Humidity
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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 [AMB21 / AMB22 / AMB23 / BW16] 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”
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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.
GTimer - Using The Periodic GTimer
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / 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);
GTimer - Using the One-Time Gtimer
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / 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.
I2C - Send Data to Arduino UNO
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 [AMB21 / AMB22 / AMB23 / BW16] 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
AMB21/ AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 Wiring Diagram:
Code Reference
I2C - Display Data On LCD Screen
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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 - Receive Data from Arduino UNO
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.IR - Transmit IR NEC Raw Data And Decode
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16 ] 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.
Figure 11 and Figure 12 shows the pin configuration of IR Emitter and Receiver with Ameba RTL8720DN (BW16).
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
Power Save - Deep Sleep Mode
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Example
Introduction
Ameba-D supports 2 low power modes which are deepsleep mode and sleep mode. Deep Sleep mode turns off more power domain than sleep mode. The power consumption of Deep Sleep mode is around 7μA to 8μA as compared to normal state which is around 22mA. This example describes how to enter Deep Sleep mode and configure the wakeup source
AON Timer(SET_DS_AON_TIMER_WAKEUP);
AON GPIO pins(SET_AONWAKEPIN_WAKEUP);
RTC Timer(SET_DS_RTC_WAKEUP);
AON_TIMER_SLEEP_DURATION
SET_AON_GPIO_WAKEUP_GPIOA25
or the pin that you want to use as shown in the picture belowDS_RTC_ALARM_DAY
,
DS_RTC_ALARM_HOUR
, DS_RTC_ALARM_MIN
, and DS_RTC_ALARM_SEC
AON Timer
AON GPIO Pin
RTC Timer
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
Power Save - Deep Sleep for DHT and E-paper
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON_TIMER_SLEEP_DURATION
SET_AON_GPIO_WAKEUP_GPIOA25
or the pin that you want to use as shown in the picture below.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 for DHT and LCD
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON_TIMER_SLEEP_DURATION
SET_AON_GPIO_WAKEUP_GPIOA25
or the pin that you want to use as shown in the picture below.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 [AMB21 / AMB22 / AMB23 / BW16] 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.
LOGUART(SET_TL_UART_WAKEUP);
RTC Timer(SET_TL_RTC_WAKEUP);
AON pins(SET_AON_WAKEPIN_WAKEUP);
LOGUART
RTC Timer
AON GPIO Pins
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
PWM - Play Music by Buzzer
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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:
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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 - Servo Control
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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);
RTC - Simple RTC
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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
RTC - Simple RTC Alarm
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
SPI – Print Image And Text On LCD Screen
If you are not familiar with SPI, please read Introduction to SPI first.
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
AMB21/ AMB22 and QVGA TFT LCD Wiring Diagram:
AMB23 and QVGA TFT LCD Wiring Diagram:
BW16 and QVGA TFT LCD Wiring Diagram:
AMB21 / AMB22 and Adafruit 2.8’’ TFT LCD touch shield Wiring Diagram:
AMB23 and Adafruit 2.8’’ TFT LCD touch shield Wiring Diagram:
BW16 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 [AMB21 / AMB22 / AMB23 / BW16] 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.
TensorFlow Lite - Hello World
Materials
AmebaD [AMB21 / AMB22 / AMB23] 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 [AMB21 / AMB22 / AMB23] 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 [AMB21 / AMB22 / AMB23] 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 [AMB21 / AMB22 / AMB23] 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
UART - Communicate with PC over USB to Serial Module
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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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.
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
AMB23 Wiring Diagram:
Open the example in “Files” -> “Examples” ->
“AmebaSoftwareSerial” -> “Adafruit_GPS_parsing”
.
UART – Set Callback Function For UART Communications
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
USB to TTL Adapter x 1
Example
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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.
UART - PM2.5 Concentration in The Air
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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.
Watchdog - Simple WDG Timer
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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”
:Community Examples
OpenMV Bluetooth TripWire
CONTRIBUTED BY: SIMON XI (https://github.com/xidameng )
Hi if you haven’t watched the demo video, feel free to play this short clip below to see what it’s capable of.

This project took the inspiration from the another open-source project daytripper (link 1) which uses 2 seperate devices to detect movement and control your PC to switch Apps. However, I think if we go with the Computer Vision solution instead, we might reduce the number of hardware to just 1, and we can even push it a little further by adding some more cool features like face recognition, speed detection and even more.
That’s how I came up with this idea – using OpenMV, which is littler and easier to deploy, and a IoT Microcontroller, in this case Ameba RTL8722DM_MINI, together we can achieve the same function as daytripper and more.
AMB23 (RTL8722DM MINI) dev board x1
OpenMV( any model) dev board x1
Connection is simple, just connect P0 pin on OpenMV to pin 9 on Ameba Board.
This is how it works,
# Advanced Frame Differencing Example
#
# This example demonstrates using frame differencing with your OpenMV Cam. This
# example is advanced because it preforms a background update to deal with the
# backgound image changing overtime.
import sensor, image, pyb, os, time
from pyb import Pin
p_out = Pin('P0', Pin.OUT_PP)
p_out.low()
TRIGGER_THRESHOLD = 5
BG_UPDATE_FRAMES = 50 # How many frames before blending.
BG_UPDATE_BLEND = 128 # How much to blend by... ([0-256]==[0.0-1.0]).
sensor.reset() # Initialize the camera sensor.
sensor.set_pixformat(sensor.RGB565) # or sensor.RGB565
sensor.set_framesize(sensor.QVGA) # or sensor.QQVGA (or others)
sensor.skip_frames(time = 2000) # Let new settings take affect.
sensor.set_auto_whitebal(False) # Turn off white balance.
clock = time.clock() # Tracks FPS.
# Take from the main frame buffer's RAM to allocate a second frame buffer.
# There's a lot more RAM in the frame buffer than in the MicroPython heap.
# However, after doing this you have a lot less RAM for some algorithms...
# So, be aware that it's a lot easier to get out of RAM issues now. However,
# frame differencing doesn't use a lot of the extra space in the frame buffer.
# But, things like AprilTags do and won't work if you do this...
extra_fb = sensor.alloc_extra_fb(sensor.width(), sensor.height(), sensor.RGB565)
print("About to save background image...")
sensor.skip_frames(time = 2000) # Give the user time to get ready.
extra_fb.replace(sensor.snapshot())
print("Saved background image - Now frame differencing!")
triggered = False
frame_count = 0
while(True):
clock.tick() # Track elapsed milliseconds between snapshots().
img = sensor.snapshot() # Take a picture and return the image.
frame_count += 1
if (frame_count > BG_UPDATE_FRAMES):
frame_count = 0
# Blend in new frame. We're doing 256-alpha here because we want to
# blend the new frame into the backgound. Not the background into the
# new frame which would be just alpha. Blend replaces each pixel by
# ((NEW*(alpha))+(OLD*(256-alpha)))/256. So, a low alpha results in
# low blending of the new image while a high alpha results in high
# blending of the new image. We need to reverse that for this update.
img.blend(extra_fb, alpha=(256-BG_UPDATE_BLEND))
extra_fb.replace(img)
# Replace the image with the "abs(NEW-OLD)" frame difference.
img.difference(extra_fb)
hist = img.get_histogram()
# This code below works by comparing the 99th percentile value (e.g. the
# non-outlier max value against the 90th percentile value (e.g. a non-max
# value. The difference between the two values will grow as the difference
# image seems more pixels change.
diff = hist.get_percentile(0.99).l_value() - hist.get_percentile(0.98).l_value()
triggered = diff > TRIGGER_THRESHOLD
if triggered == True:
p_out.high()
else:
p_out.low()
print(clock.fps(), triggered) # Note: Your OpenMV Cam runs about half as fast while
# connected to your computer. The FPS should increase once disconnected.
#include "BLEHIDDevice.h"
#include "BLEHIDKeyboard.h"
#include "BLEDevice.h"
BLEHIDKeyboard keyboardDev;
BLEAdvertData advdata;
#define ENABLE_PIN 9
void setup() {
Serial.begin(115200);
advdata.addFlags();
advdata.addCompleteName("AMEBA_BLE_HID");
advdata.addAppearance(GAP_GATT_APPEARANCE_HUMAN_INTERFACE_DEVICE);
advdata.addCompleteServices(BLEUUID(HID_SERVICE_UUID));
BLEHIDDev.init();
BLE.init();
BLE.configAdvert()->setAdvData(advdata);
BLE.setDeviceName("AMEBA_BLE_HID");
BLE.setDeviceAppearance(GAP_GATT_APPEARANCE_HUMAN_INTERFACE_DEVICE);
BLE.configSecurity()->setPairable(true);
BLE.configSecurity()->setAuthFlags(GAP_AUTHEN_BIT_BONDING_FLAG);
BLE.configServer(3);
BLE.addService(BLEHIDDev.hidService());
BLE.addService(BLEHIDDev.battService());
BLE.addService(BLEHIDDev.devInfoService());
pinMode(ENABLE_PIN, INPUT);
BLE.beginPeripheral();
}
int flag = 0;
void loop() {
if (BLE.connected() && digitalRead(ENABLE_PIN) && flag == 0) {
Serial.println("Sending keystrokes");
keyboardDev.keyReleaseAll();
delay(100);
keyboardDev.keyPress(HID_KEY_ALT_LEFT);
delay(100);
keyboardDev.keyPress(HID_KEY_TAB);
keyboardDev.keyReleaseAll();
delay(100);
flag = 1;
} else {
flag = 0;
delay(100);
}
}
This project is not perfect as it’s done in a rush, so if anyone wants to perfect it you may go ahead and change my code however you like, or leave a comment below if you have a question or want to discuss something with me~
Until next time, happy coding.
小技巧
Welcome to share your examples under the Community Examples section if you have completed a project using the Ameba boards
Release History
Version 3.1.2 - 2021/12/28
Feature:
Update SimpleWebServerWiFi example
Support BW16
API Updates:
Update Wlan related naming from “AmebaWiFi” become “WiFi”
Update RTC library for minor bug fix
Misc:
Update all Fritzing files for new name updates
AMB21, AMB22, AMB23, and BW16
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
Support
FAQ
Where to buy Ameba RTL8722DM Board?
Refer to Purchase link.
Which Bluetooth standards are supported by RTL8722CSM/RTL8722DM?
Both boards support BLE 5.0. Classic Bluetooth (BR/EDR) is not supported.
Which BLE roles are supported?
RTL8722CSM/RTL8722DM can operate as either a BLE Central or BLE Peripheral device.
Are all pins on RTL8722CSM/RTL8722DM usable?
No, those marked
NC
are not connected to any pin and thus unusable.
Is XIP (execute in place) supported on RTL8722CSM/RTL8722DM?
Yes, it is supported.
Does RTL8722CSM support 5G WiFi?
No. Only RTL8722DM supports dual band 2.4G + 5G WiFi. RTL8722CSM only supports single band 2.4G WiFi.
How to enter the download mode?
Press and hold the UART DOWNLOAD button. Then Press the RESET button and release both UART DOWNLOAD and RESET buttons.
Trouble shooting
RTL8722CSM/RTL8722DM cannot be found as a Bluetooth device.
Please make sure the antenna is connected properly. Check your code for the correct Bluetooth configurations.
My code is not behaving as I expected.
Try to debug your program using
printf()
andSerial.print()
statements. If the issue persists, you can ask for help at Forums
Why is there no output on my serial terminal after connecting to RTL8722CSM/RTL8722DM UART?
RTL8722CSM/RTL8722DM is by default configured at 115200 baudrate, please check if your serial terminal is configured to 115200.
My program is not being downloaded into RTL8722CSM/RTL8722DM?
- Please follow the procedure for the correct downloading:
Enter the download mode. The on-board Green LED will blink when entered download mode.
When downloading the image into board the on-board Red LED will blink
After a successful download, you will see log like this “All images sent successfully”.
Sometimes WiFi signal is weak?
The default antenna for RTL8722CSM/RTL8722DM uses the I-Pex Connector. Please change/connect the I-Pex Connector antenna.
Why is my board not powering up?
Please make sure the connector J38 beside resistor R43 is connected. The connector is used to link the power to IC.
If you have driver issue to connect board to your computer?
Please go to https://ftdichip.com/drivers/ for USB driver.
BW16 (RTL8720DN) by Ai-Thinker
Welcome to BW16 (RTL8720DN) online documentation.
Getting Started
Ameba ARDUINO: Getting Started with BW16
Required Environment
BW16 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.
BW16 has a smaller size than AMB21 and AMB23 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 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 BW16, and the basic examples of Arduino can run on 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 BW16 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
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-M33 @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-M33 @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 BW16 on Instructable: https://www.instructables.com/RTL8720DN/
Load Arduino image into BW16: How to load BW16 program with Arduino – #13
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 Support page.
Peripherals & Examples
Basic Examples
BW16 (RTL8720DN) Supported ARDUINO built-in example table
There are many built-in examples in Arduino. In the table below, we list all examples that are compatible with Ameba.
Category |
Name |
Comment |
Remarks |
---|---|---|---|
01. Basics |
Analog ReadSerial |
Connect potentiometer to 3.3V. Use ADC pin A2(PB3). |
ADC pin reading voltage range 0 to 3.3V. |
BareMinimum |
|||
Blink |
Pin LED_BUILTIN sets to LED_G |
Onboard LEDs options LED_R, LED_B, and LED_G. (red, blue, and green) |
|
Digital ReadSerial |
|||
Fade |
Use PWM pins D7(PA25), D8(PA26), D11(PA13), D12(PA12) |
||
Read Analog Voltage |
Use ADC pin A2(PB3). |
ADC pin reading voltage range 0 to 3.3V. |
|
02. Digital |
BlinkWithout Delay |
Pin LED_BUILTIN sets to LED_G |
Onboard LEDs options LED_R, LED_B, and LED_G. |
Button |
Replace “ledPin = 13;” by available digital pins. e.g. “ledPin = LED_BUILTIN;” |
Onboard LEDs options LED_R, LED_B, and LED_G. |
|
Debounce |
Replace “ledPin = 13;” by available digital pins. e.g. “ledPin = LED_BUILTIN;” |
Onboard LEDs options LED_R, LED_B, and LED_G. |
|
Digital InputPullup |
Replace “ledPin = 13;” by available digital pins. e.g. “ledPin = LED_BUILTIN;” |
Onboard LEDs options LED_R, LED_B, and LED_G. |
|
StateChange Detection |
Replace “ledPin = 13;” by available digital pins. e.g. “ledPin = LED_BUILTIN;” |
Onboard LEDs options LED_R, LED_B, and LED_G. |
|
toneKeyboard |
Replace “tone(8, notes[thisSensor], 20);” by a PWM pin D7(PA25), D8(PA26), D11(PA13) or D12(PA12)). e.g. “tone(PA25, notes[thisSensor - 4], 20);”, “tone(7, notes[thisSensor - 4], 20);” |
||
toneMelody |
|||
tone Multiple |
|||
tonePitch Follower |
|||
03. Analog |
Analog InOutSerial |
Replace “analogOutPin = 9;” by a PWM pin (D7(PA25), D8(PA26), D11(PA13) or D12(PA12))). e.g. “analogOutPin = 7;”. Use ADC pin A2(PB3). |
ADC pin reading voltage range 0 to 3.3V. |
AnalogInput |
Replace “ledPin = 13;” by available digital pins. e.g. “ledPin = LED_BUILTIN;”. Use ADC pin A2(PB3). |
Onboard LEDs options LED_R, LED_B, and LED_G. ADC pin reading voltage range 0 to 3.3V. |
|
Analog Write Mega |
Use PWM pins D7(PA25), D8(PA26), D11(PA13), D12(PA12) |
Onboard LEDs with PWM. LED_B(D11), and LED_G(D12). |
|
Calibration |
Connect another LED to pin D13. Use ADC pin A2(PB3). |
ADC pin reading voltage range 0 to 3.3V. |
|
Fading |
Use PWM pins D7(PA25), D8(PA26), D11(PA13), D12(PA12). |
Onboard LEDs with PWM. LED_B(D11), and LED_G(D12). |
|
Smoothing |
Use ADC pin A2(PB3). |
ADC pin reading voltage range 0 to 3.3V. |
|
04. Communication |
ASCIITable |
||
Dimmer |
Onboard LEDs options LED_R, LED_B, and LED_G. |
||
Graph |
Connect potentiometer to 3.3V. Use ADC pin A2(PB3). |
ADC pin reading voltage range 0 to 3.3V. |
|
Midi |
Use Serial1 and pin D4(PB1). |
||
MultiSerial |
Required external USB-to-UART module. |
||
Physical Pixel |
Replace “ledPin = 13;” by available digital pins. e.g. “ledPin = LED_BUILTIN;”. |
Onboard LEDs options LED_R, LED_B, and LED_G. |
|
Read ASCIIString |
Use PWM pins for LED, D7(PA25), D8(PA26), D11(PA13), D12(PA12). |
Onboard LEDs with PWM. LED_B(D11), and LED_G(D12). |
|
SerialEvent |
|||
Serial Passthrough |
Required external USB-to-UART module. |
||
05. Control |
Arrays |
Use pins D9, D2, D8, D1, D11, D10. |
|
ForLoop Iteration |
Use pins D9, D2, D8, D1, D11, D10. |
||
IfStatement Conditional |
Replace “ledPin = 13;” by available digital pins. e.g. “ledPin = LED_BUILTIN;”. Use ADC pin A2(PB3). |
Onboard LEDs options LED_R, LED_B, and LED_G. ADC pin reading voltage range 0 to 3.3V. |
|
switchCase |
Use ADC pin A2(PB3). |
ADC pin reading voltage range 0 to 3.3V. |
|
switchCase2 |
Use pins D9, D2, D8, D1, D11, D10. |
||
While Statement Conditional |
Use ADC pin A2(PB3). Replace “indicatorLedPin = 13;” by available digital pins. e.g. “indicatorLedPin = LED_BUILTIN;”. Replace “ledPin = 9;” by a PWM pin D7(PA25), D8(PA26), D11(PA13) or D12(PA12)). e.g. “ledPin = 7;” |
ADC pin reading voltage range 0 to 3.3V. Onboard LEDs options LED_R, LED_B, and LED_G. Onboard LEDs with PWM. LED_B(D11), and LED_G(D12). |
|
06. Display |
barGraph |
Use ADC pin A2(PB3). |
ADC pin reading voltage range 0 to 3.3V. |
07. Strings |
Character Analysis |
||
StringAddition Operator |
|||
StringAppend Operator |
|||
String CaseChanges |
|||
String Characters |
|||
String Comparision Operators |
Use ADC pin A2(PB3). |
ADC pin reading voltage range 0 to 3.3V. |
|
StringIndexOf |
|||
StringLength |
|||
String LengthTrim |
|||
String Replace |
|||
String Starts WithEndsWith |
|||
String Substring |
|||
StringToInt |
Network Examples
BLE - BLE Battery Service
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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.
AMB21 / AMB22:
AMB23:
BW16:
“Files” -> “Examples” -> “AmebaBLE” ->
“DHT_over_BLEUart”
.BLE – PWM over BLE UART
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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).
AMB21 /AMB22:
AMB23:
BW16:
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.
HTTP - Retrieve HTTP websites from the Internet
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
HTTP - Set up Server to Control LED
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Breadboard x 1
LED x 1
1KΩ Resistor x 1
Procedure
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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.HTTP - Set up Server to Get the Ameba Status
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.HTTP - Use IFTTT for Web Service
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 [AMB21 / AMB22 / AMB23 / BW16] 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.
IPv6 – Ameba as IPv6 Server/Client over TCP
Materials
AmebaD [AMB21 / AMB22 / AMB23 / 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 [AMB21 / AMB22 / AMB23 / 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,
MDNS - Set up mDNS Client on Arduino IDE
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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);
MQTT - Set up MQTT Client to Communicate with Broker
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 [AMB21 / AMB22 / AMB23 / BW16] 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.
MQTT - Set up MQTT Client over TLS
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Example
“File” -> “Examples” ->
“AmebaMQTTClient” -> “MQTT_TLS”
MQTT - Use Amazon AWS IoT Shadow Service
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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);
MQTT - Use Google Cloud IoT
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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);
MQTT - Upload PM2.5 Data to LASS System
Intro to LASS
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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
.NTP - Retrieve Universal Time (UTC) by NTPClient library
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();
WiFi - Approximate UDP Receive Delay
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
WiFi - Approximate UDP Sending Delay
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
WiFi - Approximate UDP Receive Timeout
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
WiFi - Connect to WiFi networks
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.WiFi - Retrieve Universal Time (UTC) by UDP
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Example
“File” -> “Examples” -> “AmebaWiFi” -> “WiFiUdpNtpClient”
WiFi - Scan the surrounding WiFi networks
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Antenna x 1
AmebaD [:raw-html:`<p style=”color:#1A76B4;”>AMB21(RTL8722DM/CSM)</p>` / AMB23(RTL8722DM_MINI) / BW16(RTL8729DN)] 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.WiFi - Set up Server to communicate
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.WiFi - Set up Client to Retrieve Google Search Information
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.WiFi - Set up UDP Server to Communicate
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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()
.WiFi - Set up WiFi 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 [AMB21 / AMB22 / AMB23 / BW16] 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:
WiFi - Set up SSL Client for HTTPS Communication
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
Components Used
Humidity & temperature sensor
|
Distance measurement function
|
TFT LCD display with SPI interface
|
|
QVGA TFT LCD display module
|
High-quality GPS positioning module
|
Servo with high output power
|
Peripheral Examples
E-Paper - Display Images
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
Front view of the e-Paper Module:
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
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 [AMB21 / AMB22 / AMB23 / BW16] x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
Front view of the e-Paper Module:
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
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 [AMB21 / AMB22 / AMB23 / BW16] x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
Front view of the e-Paper Module:
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
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
Flash Memory - Store data in FlashEEProm
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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);
GPIO - Measure Distance By Ultrasound Module
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
HC-SR04 Ultrasonic x 1
Dropping resistor or Level converter
Example
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 Wiring Diagram:
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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 - Measure Temperature and Humidity
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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 [AMB21 / AMB22 / AMB23 / BW16] 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”
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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.
GTimer - Using The Periodic GTimer
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / 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);
GTimer - Using the One-Time Gtimer
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / 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.
I2C - Send Data to Arduino UNO
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 [AMB21 / AMB22 / AMB23 / BW16] 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
AMB21/ AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 Wiring Diagram:
Code Reference
I2C - Display Data On LCD Screen
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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 - Receive Data from Arduino UNO
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.IR - Transmit IR NEC Raw Data And Decode
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16 ] 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.
Figure 11 and Figure 12 shows the pin configuration of IR Emitter and Receiver with Ameba RTL8720DN (BW16).
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
Power Save - Deep Sleep Mode
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
Example
Introduction
Ameba-D supports 2 low power modes which are deepsleep mode and sleep mode. Deep Sleep mode turns off more power domain than sleep mode. The power consumption of Deep Sleep mode is around 7μA to 8μA as compared to normal state which is around 22mA. This example describes how to enter Deep Sleep mode and configure the wakeup source
AON Timer(SET_DS_AON_TIMER_WAKEUP);
AON GPIO pins(SET_AONWAKEPIN_WAKEUP);
RTC Timer(SET_DS_RTC_WAKEUP);
AON_TIMER_SLEEP_DURATION
SET_AON_GPIO_WAKEUP_GPIOA25
or the pin that you want to use as shown in the picture belowDS_RTC_ALARM_DAY
,
DS_RTC_ALARM_HOUR
, DS_RTC_ALARM_MIN
, and DS_RTC_ALARM_SEC
AON Timer
AON GPIO Pin
RTC Timer
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
Power Save - Deep Sleep for DHT and E-paper
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON_TIMER_SLEEP_DURATION
SET_AON_GPIO_WAKEUP_GPIOA25
or the pin that you want to use as shown in the picture below.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 for DHT and LCD
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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_AON_WAKEPIN_WAKEUP);
RTC timer (SET_DS_RTC_WAKEUP);
AON_TIMER_SLEEP_DURATION
SET_AON_GPIO_WAKEUP_GPIOA25
or the pin that you want to use as shown in the picture below.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 [AMB21 / AMB22 / AMB23 / BW16] 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.
LOGUART(SET_TL_UART_WAKEUP);
RTC Timer(SET_TL_RTC_WAKEUP);
AON pins(SET_AON_WAKEPIN_WAKEUP);
LOGUART
RTC Timer
AON GPIO Pins
Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
PWM - Play Music by Buzzer
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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:
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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 - Servo Control
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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);
RTC - Simple RTC
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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
RTC - Simple RTC Alarm
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
SPI – Print Image And Text On LCD Screen
If you are not familiar with SPI, please read Introduction to SPI first.
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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.
AMB21/ AMB22 and QVGA TFT LCD Wiring Diagram:
AMB23 and QVGA TFT LCD Wiring Diagram:
BW16 and QVGA TFT LCD Wiring Diagram:
AMB21 / AMB22 and Adafruit 2.8’’ TFT LCD touch shield Wiring Diagram:
AMB23 and Adafruit 2.8’’ TFT LCD touch shield Wiring Diagram:
BW16 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 [AMB21 / AMB22 / AMB23 / BW16] 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.
UART - Communicate with PC over USB to Serial Module
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 [AMB21 / AMB22 / AMB23 / BW16] 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 [AMB21 / AMB22 / AMB23 / BW16] 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.
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
AMB23 Wiring Diagram:
Open the example in “Files” -> “Examples” ->
“AmebaSoftwareSerial” -> “Adafruit_GPS_parsing”
.
UART – Set Callback Function For UART Communications
Materials
AmebaD [AMB21 / AMB22 / AMB23 / BW16] x 1
USB to TTL Adapter x 1
Example
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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.
UART - PM2.5 Concentration in The Air
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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
AMB21 / AMB22 Wiring Diagram:
AMB23 Wiring Diagram:
BW16 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.
Watchdog - Simple WDG Timer
Preparation
AmebaD [AMB21 / AMB22 / AMB23 / BW16] 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”
:Community Examples
小技巧
Welcome to share your examples under the Community Examples section if you have completed a project using the Ameba boards
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
Support
FAQ
Where to buy Ameba RTL8722DM Board?
Refer to Purchase link.
Which Bluetooth standards are supported by RTL8722CSM/RTL8722DM?
Both boards support BLE 5.0. Classic Bluetooth (BR/EDR) is not supported.
Which BLE roles are supported?
RTL8722CSM/RTL8722DM can operate as either a BLE Central or BLE Peripheral device.
Are all pins on RTL8722CSM/RTL8722DM usable?
No, those marked
NC
are not connected to any pin and thus unusable.
Is XIP (execute in place) supported on RTL8722CSM/RTL8722DM?
Yes, it is supported.
Does RTL8722CSM support 5G WiFi?
No. Only RTL8722DM supports dual band 2.4G + 5G WiFi. RTL8722CSM only supports single band 2.4G WiFi.
How to enter the download mode?
Press and hold the UART DOWNLOAD button. Then Press the RESET button and release both UART DOWNLOAD and RESET buttons.
Trouble shooting
RTL8722CSM/RTL8722DM cannot be found as a Bluetooth device.
Please make sure the antenna is connected properly. Check your code for the correct Bluetooth configurations.
My code is not behaving as I expected.
Try to debug your program using
printf()
andSerial.print()
statements. If the issue persists, you can ask for help at Forums
Why is there no output on my serial terminal after connecting to RTL8722CSM/RTL8722DM UART?
RTL8722CSM/RTL8722DM is by default configured at 115200 baudrate, please check if your serial terminal is configured to 115200.
My program is not being downloaded into RTL8722CSM/RTL8722DM?
- Please follow the procedure for the correct downloading:
Enter the download mode. The on-board Green LED will blink when entered download mode.
When downloading the image into board the on-board Red LED will blink
After a successful download, you will see log like this “All images sent successfully”.
Sometimes WiFi signal is weak?
The default antenna for RTL8722CSM/RTL8722DM uses the I-Pex Connector. Please change/connect the I-Pex Connector antenna.
Why is my board not powering up?
Please make sure the connector J38 beside resistor R43 is connected. The connector is used to link the power to IC.
If you have driver issue to connect board to your computer?
Please go to https://ftdichip.com/drivers/ for USB driver.
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()
您应该能够看到返回周围无线网络的结果
(完结)
Release History
Version 1.0.2 release - 2021/10/14
Feature:
Add MacOS toolchain to support building on MacOS
Pre-test passed for RTL8722DM MINI
API Updates:
Update PWM module with new API
Re-structure SDFS module and remove warning when no SD card
Misc
Update WLAN and other libraries
Update readme documentation
Version 1.0.1 release - 2021/06/07
Feature:
Added MacOS Support for firmware uploading (not compilation)
Fixed PWM API issue with loop
Implemented SDFS (SD FileSystem) module [Currently only support RTL8722DM_mini]
Update welcome message and help message
Update Ameba SDK and libraries
Fixed network and WLAN security issues
Fix bugs related to WiFi
Update Readme
Provide examples for new module
Version 1.0.0 release - 2020/11/11
Feature:
OS Support Windows and Linux
WiFi
Socket
ADC
builtin help
Example and online API
Version 0.0.1 alpha release - 2020/09/29
Feature:
Ported basic MicroPython functions
Implemented REPL and basic terminal functions
Added Pin Mapping for RTL8722
Added peripheral helper modules:
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的阴极引脚:
Then, copy the following code and press Ctrl + e
in REPL
to enter the paste mode (for more information about REPL
and paste mode, check “Getting Started” page). If you are using Tera Term
, simply right click on any blank space of the terminal and paste the code into REPL
, then press Ctrl + d
to execute the code. If everything is order, you should be able to see the LED blink for 3 times in 3 seconds.
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默认固件地址,您可以直接使用它。
点选下载按钮 进度条将显示每个固件的传输进度并且可以从日志窗口获取操作成功消息或错误消息。
Release History
Version 1.0.0 – 2021/10/12
Hardware information:
CPU. 32-bit KM4 (Arm Cortex-M33 compatible) and 32-bit KM0 (Arm Cortex-M23 compatible)
MEMORY. 512KB SRAM + 4MB PSRAM
Feature:
Integrated 802.11a/n Wi-Fi SoC
USB Host/Device
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?
Refer to Purchase link.
故障排除
遇到开发板连接到计算机的驱动程序问题?
请参考下列USB驱动程序 https://ftdichip.com/drivers/。
小技巧