歡迎來到 Ameba D (RTL8722) 編程指南!
我們支持3個獨特的開發平台:Realtek Standard SDK、Arduino SDK 和 MicroPython SDK。
所有的 入門指南、例子、教程、API參考 和 數據手冊 都可以在下面的相關鏈接中找到。

Arduino 開發平台
RTL8722DM
歡迎來到 Ameba Arduino RTL8722DM 在綫文檔
RTL8722DM 快速入門
環境配置
AmebaD RTL8722CSM/RTL8722DM目前支持Windows XP/7/8/10 32位元/64位元,Linux以及Mac作業系統。 在本文檔中,請使用1.8.12或更高版本的Arduino IDE。
AmebaD RTL8722CSM/RTL8722DM 簡介
Ameba是一個易於編程的微控制器平台,可用於開發各種物聯網應用程序。
AmebaD有各種外圍接口,包括WiFi, GPIO INT, I2C, UART, SPI, PWM, ADC。通過這些接口, AmebaD可以連接LED、開關、壓力計、濕度計、PM2.5粉塵傳感器等電子元件。
Ameba所收集的數據可以通過WiFi無線上傳,並被智能設備上的應用程序使用,實現物聯網的應用。
AmebaD和Arduino Uno的尺寸類似,如上圖所示,並且AmebaD上的引腳與Arduino Uno兼容。
AmebaD使用Micro USB來供電,這在許多智能設備中很常見。 AmebaD的引腳圖和功能請參考下圖和表格。
# |
PIN name |
GPIO |
ADC |
PWM |
UART |
SPI |
I2C |
---|---|---|---|---|---|---|---|
D00 |
GPIOB_2 |
✓ |
ADC5 |
UART3_RX(b) |
|||
D01 |
GPIOB_1 |
✓ |
ADC4 |
UART3_TX(b) |
|||
D02 |
GPIOB_3 |
✓ |
ADC6 |
||||
D03 |
GPIOB_31 |
✓ |
|||||
D04 |
GPIOB_30 |
✓ |
|||||
D05 |
GPIOB_28 |
✓ |
|||||
D06 |
GPIOB_29 |
✓ |
|||||
D07 |
NC |
||||||
D08 |
GPIOB_22 |
✓ |
PWM14 |
||||
D09 |
GPIOB_23 |
✓ |
PWM15 |
||||
D10 |
GPIOB_21 |
✓ |
PWM13 |
UART0_RTS(b) |
SPI0_CS |
||
D11 |
GPIOB_18 |
✓ |
PWM10 |
UART0_RX(b) |
SPI0_MOSI |
||
D12 |
GPIOB_19 |
✓ |
PWM11 |
UART0_TX(b) |
SPI0_MISO |
||
D13 |
GPIOB_20 |
✓ |
PWM12 |
UART0_CTS(b) |
SPI0_CLK |
||
D14 |
GPIOA_7 |
✓ |
UART2_TX(log) |
||||
D15 |
GPIOA_8 |
✓ |
UART2_RX(log) |
||||
D16 |
GPIOA_25 |
✓ |
PWM4 |
UART3_RX(a) |
I2C0_SCL |
||
D17 |
GPIOA_26 |
✓ |
PWM5 |
UART3_TX(a) |
I2C0_SDA |
||
D18 |
GPIOB_7 |
✓ |
ADC3 |
PWM17 |
SPI1_CS |
||
D19 |
GPIOB_6 |
✓ |
ADC2 |
SPI1_CLK |
|||
D20 |
GPIOB_5 |
✓ |
ADC1 |
PWM9 |
SPI1_MISO |
||
D21 |
GPIOB_4 |
✓ |
ADC0 |
PWM8 |
SPI1_MOSI |
||
D22 |
GPIOA_28 |
✓ |
|||||
D23 |
GPIOA_24 |
✓ |
PWM3 |
UART0_CTS(a) |
I2C1_SDA |
||
D24 |
GPIOA_23 |
✓ |
PWM2 |
UART0_RTS(a) |
I2C1_SCL |
||
D25 |
GPIOA_22 |
✓ |
UART0_RX(a) |
||||
D26 |
GPIOA_21 |
✓ |
UART0_TX(a) |
||||
D27 |
GPIOA_20 |
✓ |
|||||
D28 |
GPIOA_19 |
✓ |
設置開發環境
步驟1. 安裝驅動程序
下文為未翻譯部分:
(End)
If you face any issue, please refer to the FAQ and troubleshooting page.
相關資源下載
發佈歷史
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
外圍設備 & 示例
基本範例
There are many built-in examples in Arduino. In the table below, we list all examples that are compatible with Ameba.
Category |
Name |
Comment |
---|---|---|
|
AnalogReadSerial |
Connect potentiometer to 3.3V |
BareMinimum |
||
Blink |
Connect LED to pin 8 |
|
DigitalReadSerial |
||
Fade |
||
ReadAnalogVoltage |
ADC can read a maximum of 3.3V. |
|
|
BlinkWithoutDelay |
Connect LED to pin 8 |
Button |
Connect LED to pin 13 |
|
Debounce |
Connect LED to pin 13 |
|
DigitalInputPullup |
Connect LED to pin 13 |
|
StateChangeDetection |
Connect LED to pin 13 |
|
toneKeyboard |
||
toneMelody |
||
toneMultiple |
||
tonePitchFollower |
||
|
AnalogInOutSerial |
|
AnalogInput |
Connect LED to pin 13 |
|
Analog Write Mega |
||
Calibration |
Connect another LED to pin 13 |
|
Fading |
||
Smoothing |
||
|
ASCIITable |
|
Dimmer |
Use serial baud rate 115200 |
|
Graph |
Use serial baud rate 115200, Connect potentiometer to 3.3V |
|
Midi |
Please use Serial1 and pin 26, or use Serial2 and pin 17 |
|
MultiSerial |
||
PhysicalPixel |
Use serial baud rate 115200 |
|
ReadASCIIString |
||
SerialCallResponse |
Use serial baud rate 115200 |
|
Se rialCallResponseASCII |
Use serial baud rate 115200 |
|
SerialEvent |
||
SerialPassthrough |
||
VirtualColorMixer |
Use serial baud rate 115200 |
|
|
Arrays |
Use pins 1, 2, 3, 4, 5, 6 |
ForLoopIteration |
Use pins 1, 2, 3, 4, 5, 6 |
|
I fStatementConditional |
||
switchCase |
||
switchCase2 |
||
Whil eStatementConditional |
Connect another LED to pin 13 |
|
|
barGraph |
Use another pin to replace pin 7 |
RowColumnScanning |
||
|
CharacterAnalysis |
|
S tringAdditionOperator |
||
StringAppendOperator |
||
StringCaseChanges |
||
StringCharacters |
||
Stri ngComparisonOperators |
||
StringIndexOf |
||
StringLength |
||
StringLengthTrim |
||
StringReplace |
||
Str ingStartsWithEndsWith |
||
StringSubstring |
||
StringToInt |
網路相關範例
[RTL8722CSM] [RTL8722DM] Scan available WiFi hotspots in the surroundings
Materials
Ameba x 1
Antenna x 1
Example
In this example, we use Ameba to scan available WiFi hotspots in the surroundings, and prints the SSID, encryption type, signal strength information of each detected hotspot.
First, make sure the correct Ameba development board is selected in Arduino IDE: “Tools” -> “Board” ->
Open the “ScanNetworks” example in “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
Comparison with Arduino
In the Arduino platform, we need to add an extra WiFi shield to be the WiFi module to realize the WiFi connection. And we must #include to use SPI to communicate with WiFi module.
However, Ameba is already equipped with WiFi module. Therefore, #include is not needed.
[RTL8722CSM] [RTL8722DM] Connect to WiFi
Materials
Ameba 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
Comparison with Arduino
[RTL8722CSM] [RTL8722DM] Use Ameba as Server to communicate with Client
Materials
Ameba 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.

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
[RTL8722CSM] [RTL8722DM] Use Ameba to retrieve HTTP websites from the internet
Materials
Ameba x 1
Example
Then open “File” -> “Examples” -> “AmebaHttp” -> “SimpleHttpExample”

In the sample code, modify the highlighted section to enter the information required (ssid, password, key index) to connect to your WiFi network.

Code Reference
Use http.get() to send a GET request to the website.
[RTL8722CSM] [RTL8722DM] Use Ameba to retrieve information from the Internet
Materials
Ameba x 1
Example
Then open “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
[RTL8722CSM] [RTL8722DM] Use Ameba as Server to control LED
Materials
Ameba x 1
Breadboard x 1
LED x 1
1KΩ Resistor x 1
Procedure
In this example, we connect Ameba to WiFi and use Ameba as server, the user can control the LED on/off through a webpage.
First, connect Ameba with the LED.
In a LED, the longer pin is the positive pole, and the shorter pin is the negative pole. So, we connect the shorter pin to GND and connect the longer pin to D13. Additionally, to avoid the electric current exceeds the tolerance of the LED and causes damage, we connect a resistance on the positive pole.

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.
Code Reference
[RTL8722CSM] [RTL8722DM] Use Ameba as server to send Ameba status
Materials
Ameba x 1
Example

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. After connecting to WiFi, Ameba starts to run as server. The IP of the server is shown in the serial monitor, and port is 80.

[RTL8722CSM] [RTL8722DM] Use Ameba as UDP server
Preparation
Ameba x 1
Example
In this example, we connect Ameba to WiFi and use Ameba to be an UDP server. When Ameba receives a message from UDP client, it replies “acknowledged” message to client.
Modify the highlighted code section (ssid, password, keyindex) to connect to your WiFi network.

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.
Choose client mode and fill in the IP of UDP server (which is the IP of Ameba) and port 2390, then click “UDP Connect”.
After the connection is established, fill in “Hello World” in the Buf 0 field in sokit and click “Send”. Then you can see the Ameba UDP server replies “acknowledged”.

Code Reference
[RTL8722CSM] [RTL8722DM] Retrieve Universal Time (UTC) By Ameba
Preparation
Ameba x 1
Example
In this example, we connect Ameba to WiFi. Then send NTP (Network Time
Protocol, RFC 1305) request to NTP server using UDP. After receiving the
NTP request, the NTP server replies current UTC (Coordinated Universal
Time) packet. We will parse the UTC packet to show current UTC time in
the serial monitor. Open the example. “File” -> “Examples” ->
“AmebaWiFi” -> “WiFiUdpNtpClient”Modify the highlighted code
section (ssid, password, keyindex) to connect to your WiFi
network.
Compile the code and upload it to Ameba. After pressing
the Reset button, Ameba connects to WiFi and sends NTP request packet to
NTP server “129.6.15.28”. We parse the replied packet and show UTC time
in serial monitor:
[RTL8722CSM] [RTL8722DM] Use MQTT To Upload And Listen To Data
Intro to MQTT
MQTT (Message Queuing Telemetry Transport) is a protocol proposed by IBM and Eurotech. The introduction in MQTT Official Website: MQTT is a machine-to-machine (M2M)/”Internet of Things” connectivity protocol. It was designed as an extremely lightweight publish/subscribe messaging transport. We can say MQTT is a protocol designed for IoT. MQTT is based on TCP/IP and transmits/receives data via publish/subscribe. Please refer to the figure below:

In the operation of MQTT, there are several roles:
- Publisher: Usually publishers are the devices equipped with sensors
(ex. Ameba). Publishers uploads the data of the sensors to MQTT-Broker, which serves as a database with MQTT service.
- Subscriber: Subscribers are referred to the devices which receive and
observe messages, such as a laptop or a mobile phone.
- Topic: Topic is used to categorized the messages, for example the
topic of a message can be “PM2.5” or “Temperature”. Subscribers can choose messages of which topics they want to receive.
Preparation
Ameba x 1
Example
In this example, we connect Ameba to MQTT-Broker. Then send messages as
publisher and receive messages from MQTT-Broker as subscriber. Open the
MQTT example “File” -> “Examples” -> “AmebaMQTTClient” ->
“MQTT_Basic”Please modify some WiFi-related parameters. And
some information related to MQTT:
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. Next, compile the code and upload it to Ameba. Press
the reset button, then open the serial monitor
After Ameba is
connected to MQTT server, it sends the message “hello world” to
“outTopic”. To see the message, we need another MQTT client. Here we use
a chrome plugin “MQTTLens” to be the MQTT client. You can find it in
google webstore.
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.
Then click “CREATE CONNECTION”.Since we have not registered the
topic we want to listen to, we would not receive any messages now. Fill
in “outTopic” in the “Topic” field and click “Subscribe”. Wait for Ameba
to send next message (or you can press the reset button). Then you can
see the “hello world” message show up.
[RTL8722CSM] [RTL8722DM] Use Amazon AWS IoT Shadow Service
Preparation
Ameba x 1
Example
Introduction
Amazon AWS IoT is a cloud IoT service platform:

AWS Management Console



Ameba setting
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);
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);
[RTL8722CSM] [RTL8722DM] Use MQTT over TLS
Preparation
Ameba x 1
Example
In this example, we connect Ameba to a MQTT broker using TLS
authentication. Then send messages as a publisher and receive messages
from as a subscriber. Open the MQTT example “File” -> “Examples” ->
“AmebaMQTTClient” -> “MQTT_TLS”Please modify the WiFi-related
parameters to connect to your WiFi network. Modify the MQTT parameters
to fit your application:
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. Next, compile the code and upload it to Ameba. Press
the reset button, then open the serial monitor
After Ameba is
connected to MQTT server, it sends the message “hello world” to
“outTopic”. To see the message, use another MQTT client. Refer to the
MQTT_Basic example guide on how to setup a PC-based MQTT client. If you
wish to use TLS client authentication in addition to server
authentication, you will need to generate an OpenSSL private key and
obtain a signed certificate from the server. For testing purposes,
signed certificates can be obtained from test.mosquitto.org by following
the guide at https://test.mosquitto.org/ssl/. Replace the character
strings “certificateBuff” and “privateKeyBuff” with your signed
certificate and OpenSSL private key, ensuring that they are formatted
the same way as the shown in the example code. Also uncomment the
highlighted code to enable client authentication, and to change the MQTT
port number.
[RTL8722CSM] [RTL8722DM] Upload PM2
Intro to LASS
The LASS stands for “Location Aware Sensor System”. It is an open project and was started only for the interest of public welfare. Find detailed introduction here.
Practically, LASS is based on MQTT protocol to collect all kinds of uploaded data, and for those who need these data can subscribe top as well. Find more LASS information at their official hackpad.
Preparation
Ameba x 1
PlanTower PMS3003 (or PMS5003) x 1
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
Open the example. “File” -> “Examples” -> “AmebaMQTTClient” ->
“lass_basic”This example requires internet connection, so make
sure you fill in SSID and PASS into AP information that you wish to
connect. Also, LASS requires GPS information. There is no GPS sensor
included in this example, so you must manually provide GPS information.
Use Google Map to find the coordinates you plan to place your Ameba. You
can see in this example that the latitude is 24.7814033, and the
longitude is 120.9933676
Fill in GPS info at gps_lat and
gps_lon.
Then connect sensors according to UART-PlanTower
PMS3003 wiring example. RTL8722 wiring diagram:
Compile the code
and upload it to Ameba. After pressing the Reset button, Ameba will
attempt to read PM2.5 data every minute and upload it to LASS
MQTT-Broker. Open Serial Monitor to see the uploaded data, including
client id, topic, and current PM2.5 status.
We can also use
MQTTlens to verify if the data is properly uploaded. Enter
“gpssensor.ddns.net” as the MQTT-Broker server and “LASS/Test/PM25/live”
as the subscribe topic to receive data. The time uses UTC format, and
the PM2.5 data stores in s-d0. In the figure, s_d0 = 9 represents that
the PM2.5 is 9, meaning that the entire publish/ subscribe process is
working successfully.

[RTL8722CSM] [RTL8722DM] Ameba AP Mode
In AP mode, Ameba can accept at most 3 station connections, and can be set to open mode or WPA2 mode.
Preparation
Ameba x 1
Example
In this example, we turn on the AP mode of Ameba and connect station to Ameba.
Open the WiFi AP 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:

[RTL8722CSM] [RTL8722DM] Use MDNS To Let Arduino IDE Find Ameba
Preparation
Ameba 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
For example, Arduino IDE adopts the naming for the mDNS service which is
used in OTA as following: MyAmeba._arduino._tcp.local Among the
naming example, “MyAmeba” can identify the Ameba device name and the
name “MyAmeba” is changeable. “_arduino._tcp” is the protocol that
Arduino IDE adopts, and the Domain is set as local in common. Open the
example, “File” -> “Examples” -> “AmebaMDNS” -> “mdns_on_arduino_ide”
You need to input ssid and password of the AP because the example will
use WiFi connection. And you can find out the naming of the service at
the place where it declares MDNS Service. The example uses the default
name “MyAmeba” and the name is changeable.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.)
If you cannot find the Network ports on your Arduino
IDE, please check:
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);
[RTL8722CSM] [RTL8722DM] Use Firebase To Push Messaging Services
Preparation
Ameba x 1
Android Studio
Smart phone with Google Play Service x 1
Example
In the era of the popularity of smart phones, people often receive reminders from specific apps. In this example, we will teach how to use Google Firebase to send messages from the Ameba Client to mobile phones.
First, we use Firebase Cloud Messaging (FCM) as a cross-platform messaging solution that lets you deliver messages for free and reliably.
With FCM, you can notify your client application (App) to sync emails or other data. You can send a message to drive user engagement. For instant messaging content, a message can transfer up to 4KB of payload to the client application.

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

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

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

Click Connect to Firebase

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

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

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


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

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

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

Click in the upper right corner to go to the console

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

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

Select Set up


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

Connect to FCM Server after connecting to AP

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

Code Reference
https://firebase.google.com/docs/cloud-messaging/send-message
The main payload format in the program is as follows. The user can freely change the Title and Body of the message. Body represents the content of the message.
char const* payload = 「{」 \
「"to": \」」 ACCESS_TOKEN 「",」 \
「"notification": {」 \
「"body": \」Hello World!",」 \
「"title" : \」From Realtek Ameba" 」 \
「} }」 ;
setup()
if (client.connect(server, 80)) {
Serial.println(「connected to server」);
// Make a HTTP request:
sprintf(message,」%s%s%s%s%s%d%s%s%s」,」POST /fcm/send HTTP/1.1nContent-Type: application/jsonnAuthorization: key=」,SERVER_KEY,」nHost: 「,HOST_NAME,」nContent-Length: 「,strlen(payload),」nn」,payload,」n」);
printf(」nRequest:n%s \n」,message);
client.println(message);
client.println();
}
The sprintf part puts the payload into the HTTP POST content and sends the message out after connecting to the FCM Server.
loop()
while (client.available()) {
char c = client.read();
Serial.write(c);
}
Waiting for the response from Server and printing out the response
[RTL8722CSM] [RTL8722DM] Access IFTTT Via Ameba
Introduction to IFTTT
IFTTT, known as If This Then That, is a website and mobile app and free web-based service to create the applets, or the chains of simple conditional statements. The applet is triggered by changes that occur within other web services such as Gmail, Facebook, Telegram, Instagram, Pinterest etc.
Preparation
Ameba x 1
- An account from https://ifttt.com/ , in order to access IFTTT
service*

*Note: Upon log in, there are several cloud and online services that are integrated with IFTTT platforms.
Example
Generate Applet from IFTTT
In next, 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 My Applets from Top

Click “New Applet” on the Applet page.

Click +this as indicated below to add the trigger

Choose “Webhooks” service as shown below. Alternatively, search the service under Choose a Service

Then, the available triggers will appear under service. So far, only one Trigger, Receive a web request, is under Webhooks.

Once Receive a web request is selected, an event name is required to identify the trigger successfully. In this example, set Event name as “test_event”
Next, select That field to create the action service taken in response to the last trigger. In this example, choose Email as the action service



A list of Actions can be available under Action Service. In this example, only Send me an Email is found. Click on Send me an Email

Under the template of Send me an Email, the contents os the email, such as subject and body, is editable. Click Create Action to complete action. Note that Email service is offered to the email ID registered under IFTTT account.

After Review Click on Finish **to complete and create the Applet. The applet is then found under **My Applet in own IFTTT oage

Post the Trigger via Ameba
Once the Applet is ready in the IFTTT dashboard, the example program can be flashed onto Ameba board to post HTTP request.
1. The example program is under the folder “HTTP_IFTTT_POST”. Follow the steps below:
1) Open the example code in “File” -> “Examples” -> “AmebaWiFi” -> “HTTP_IFTTT_Post”
2) Once the example is opened, edit the following 3 items inside the code to make the program work.
Edit the wi-fi credentials to connect to the wi-fi hotspot or access point of desirable choice.
Edit the wi-fi credentials to connect to the wi-fi access point of choice.
Under the host name field, enter the hostname of the IFTTT service “maker.ifttt.com”
under the Path field, enter the EventName and key field “trigger//with/key/”
− Event name: The event name should be same as the one specified in the IFTTT applet. In this example, the event name is “test_event”
− Key: available under Webhook service in individual IFTTT account. See next step to obtain.
How To obtain a key from documentation tab of the Webhooks?
find the Webhooks service in the Services tab.


On Webhooks service page, click on the Documentation tab on the top right corner.
The key can found in the documentation page. Also, how HTTP request can be used as shown


Once the example is ready, connect to Ameba board via USB Cable.


Thereafter an email is sent to recipient email account registered at IFTTT Applet and email notification will be received.
[RTL8722CSM] [RTL8722DM] BLE – BLE Battery Service
Materials
Ameba D [RTL8722 CSM/DM] 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:
iOS :https://apps.apple.com/us/app/nrf-connect/id1054362403
LightBlue is an alternative application that can also be used, but has less features:
iOS :https://apps.apple.com/us/app/lightblue/id557428110
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.
[RTL8722CSM] [RTL8722DM] BLE – BLE Beacon
Materials
Ameba D 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.
[RTL8722CSM] [RTL8722DM] BLE – BLE Scan
Materials
Ameba D 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.
[RTL8722CSM] [RTL8722DM] BLE – Battery Client
Materials
AmebaD [RTL8722 CSM/DM] x 2
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.
[RTL8722CSM] [RTL8722DM] BLE – WiFi Configuration Service
Materials
AmebaD [RTL8722 CSM/DM] 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.
[RTL8722CSM] [RTL8722DM] BLE – BLE UART Client
Materials
Ameba D [RTL8722 CSM/DM] x 1
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.
[RTL8722CSM] [RTL8722DM] BLE – BLE UART Service
Materials
Ameba D [RTL8722 CSM/DM] x 1
Android / iOS smartphone
Example
Introduction
Procedure
Open the example, “Files” -> “Examples” -> “AmebaBLE” -> “BLEUartService”.





Code Reference
[RTL8722CSM] [RTL8722DM] BLE – DHT over BLE UART
Materials
Ameba D [RTL8722 CSM/DM] 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.

Open the example, “Files” -> “Examples” -> “AmebaBLE” -> “DHT_over_BLEUart”.



After starting the UART function, notifications should be received every 5 seconds containing the measured temperature and humidity.

[RTL8722CSM] [RTL8722DM] BLE – PWM over BLE UART
Materials
Ameba D [RTL8722 CSM/DM] 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).

Open the example, “Files” -> “Examples” -> “AmebaBLE” -> “PWM_over_BLEUart”.
Upload the code and press the reset button on Ameba once the upload is finished.

Open the app on your smartphone, scan and connect to the board shown as “AMEBA_BLE_DEV” and choose the controller -> color picker function in the app.



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.
[RTL8722CSM] [RTL8722DM] Approximate UDP Receive Delay
Materials
Ameba 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.
[RTL8722CSM] [RTL8722DM] Approximate UDP Receive Timeout
Materials
Ameba 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.
[RTL8722CSM] [RTL8722DM] Approximate UDP Sending Delay
Materials
Ameba 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.

[RTL8722CSM] [RTL8722DM] Google Cloud IoT
Preparation
Ameba 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
Open the example in “File” -> “Examples” -> “AmebaMQTTClient” ->
“Google_Cloud_IoT”.Enter the required information in the
highlighted sections below.
In the yellow section, enter the
SSID and password required to connect to your WiFi network. In the green
section, enter the Project ID, server Region, Registry ID and Device ID
previously configured in Google Cloud console. In the blue section,
enter the hexadecimal string previously extracted from the private key.
Upload the code and press the reset button on Ameba once the upload is
finished. Open the serial monitor and observe as Ameba connects and
sends messages to Google Cloud IoT.
In Google Cloud console,
go to Pub/Sub subscriptions, select the previously created subscription,
and click view messages. Here you can view the messages sent by
Ameba.
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);
[RTL8722CSM] [RTL8722DM] Use Ameba To Securely Retrieve Information From The Internet
Materials
Ameba 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.

週邊硬體相關範例
[RTL8722CSM] [RTL8722DM] GPIO – Measure The Distance By Ultrasound Module
Preparation
Ameba x 1
HC-SR04 Ultrasonic x 1
Dropping resistor or Level converter
Example
HC-SR04 is a module that uses ultrasound to measure the distance. It
looks like a pair of eyes in its appearance, therefore it’s often
installed onto robot-vehicle or mechanical bugs to be their eyes. The
way it works is that first we “toggle high” the TRIG pin (that is to
pull high then pull low). The HC-SR04 would send eight 40kHz sound wave
signal and pull high the ECHO pin. When the sound wave returns back, it
pull low the ECHO pin.Assume the velocity of sound is 340 m/s,
the time it takes for the sound to advance 1 cm in the air is
340*100*10^-6 = 29 us。 The sound wave actually travels twice the
distance between HC-SR04 and the object, therefore the distance can be
calculated by (time/29) / 2 = time / 58。 The working voltage of HC-SR04
is 5V. When we pull high the ECHO pin to 5V, the voltage might cause
damage to the GPIO pin of Ameba. To avoid this situation, we need to
drop the voltage as follows:
We pick the resistors with resistance
1:2, in the example we use 10kΩ and 20kΩ. If you do not have resistors
in hand, you can use level converter instead.The TXB0108 8 channel level
converter is a suitable example:
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;
[RTL8722CSM] [RTL8722DM] GPIO - Measuring The Temperature And Humidity
Preparation
Ameba 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.

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.
[RTL8722CSM] [RTL8722DM] GPIO - Use GPIO Interrupt To Control LED
Preparation
Ameba 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”
RTL8722 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.
[RTL8722CSM] [RTL8722DM] PWM – Play Music
Preparation
Ameba 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:


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.
[RTL8722CSM] [RTL8722DM] PWM – Using A Servo
Preparation
Ameba 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.
RTL8722 wiring diagram:

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);
[RTL8722CSM] [RTL8722DM] I2C - Communicate with Arduino UNO via I2C
Introduction of I2C
- There are two roles in the operation of I2C, one is “master”, the
other is “slave”. Only one master is allowed and can be connected to many slaves. Each slave has its unique address, which is used in the communication between master and the slave. I2C uses two pins, one is for data transmission (SDA), the other is for the clock (SCL). Master uses the SCL to inform slave of the upcoming data transmission, and the data is transmitted through SDA. The I2C example was named “Wire” in the Arduino example.
Materials
Ameba x 1
Arduino UNOx 1
Example
Setting up Arduino Uno to be I2C Slave

Then click “Sketch” -> “Upload” to compile and upload the example to Arduino Uno.
Setting up Ameba to be I2C Master

Wiring
RTL8722 wiring diagram:


Code Reference
[RTL8722CSM] [RTL8722DM] I2C - Use I2C to receive data from Arduino UNO
Materials
Ameba x 1
Arduino UNO x 1
Example
In the previous example “I2C – Communicate with Arduino UNO via I2C” , Ameba, the I2C master, transmits data to the Arduino UNO, the I2C slave. As to this example, Ameba is the I2C master, and receives data from the Arduino UNO, which is the I2C slave.
Setting up Arduino Uno to be I2C Slave

Then click “Sketch” -> “Upload” to compile and upload the example to Arduino Uno.
Setting up Ameba to be I2C Master

Click “Sketch” -> “Upload” to compile and upload the example to Ameba.
Wiring



Code Reference
[RTL8722CSM] [RTL8722DM] I2C - Display Data On LCD Screen
Preparation
Ameba x 1
I2C 2×16 LCD
Example


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.
[RTL8722DM] [RTL8722DM] UART - Communicate with the computer via UART
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.
材料準備
Ameba x 1
USB to TTL Adapter x 1
示例
Install USB to TTL Adapter

Executing the Example
Open the “SoftwareSerialExample” example in “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
Use write() to send data, and use SoftwareSerial:available() to get the number of bytes available for reading from a software serial port:
[RTL8722CSM] [RTL8722DM] UART - Retrieve GPS Position
Preparation
Ameba 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.
In this example
we are only interested in the “$GPRMC (Global Positioning Recommended
Minimum
Coordinates)”: $GPRMC,032122.000,A,2446.8181,N,12059.7251,E,0.39,78.89,270116,,,A*53 Each
field is separated by a comma.
- 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.
RTL8722 wiring diagram:Open the example in “Files” -> “Examples” ->
“AmebaSoftwareSerial” -> “Adafruit_GPS_parsing”. Compile and upload to
Ameba, then press the reset button. The result will be output to Serial
Monitor:
[RTL8722CSM] [RTL8722DM] UART – Set Callback Function For UART Communications
Materials
Ameba x 1
USB to TTL Adapter x 1
Example
This example shows how to set a callback function for UART communication to process the UART data.
A USB to TTL adapter is required for this example. Ensure that you have the driver installed and connect it to the Ameba board as shown.

Open the example in “File” -> “Examples” -> “AmebaSoftwareSerial” -> “SoftwareSerial_Irq_Callback”

Speed: 38400
Data: 8 bit
Parity: none
Stop bits: 1 bit
Flow control: none

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.
[RTL8722CSM] [RTL8722DM] Detect PM2.5 Concentration In The Air
Preparation
Ameba 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
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.
[RTL8722CSM] [RTL8722DM] Flash Memory - Store data in FlashEEProm
Preparation
Ameba 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.
[RTL8722CSM] [RTL8722DM] Flash Memory - Use Flash Memory Larger Than 4K
Preparation
Ameba x 1
Example
Flash Memory API uses memory of 4K bytes, which is normally sufficient for most application. However, larger memory can be provided by specifying a specific memory address and required size.
First, open the sample code in “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);
[RTL8722CSM] [RTL8722DM] SPI – Print Image And Text On LCD Screen
If you are not familiar with SPI, please read Introduction to SPI first.
Preparation
Ameba 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.
Wiring example of QVGA TFT LCD:


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
- 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.
[RTL8722CSM] [RTL8722DM] SPI – Show PM2
If you are not familiar with SPI, please read Introduction to SPI first.
Preparation
Ameba x 1
ILI9341 TFT LCD with SPI interface x 1
Plantower PMS3003 or PMS5003 x 1
Example
This example extends previous PM2.5 example to show the PM2.5 concentration on the LCD.

Adafruit 2.8” TFT LCD wiring diagram:

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.
[RTL8722CSM] [RTL8722DM] Timer - Using The Periodic GTimer
Preparation
Ameba x 1
Example
Ameba provides 5 hardware GTimer for users to use. The timers’ resolution are at microseconds scale. Note that the timers may have overlapped pin with other peripherals. For example, the timer with ID 0 overlaps with PWM_3. Therefore, when we use Time 0, we cannot use the PWM_3 on D12.
Time ID |
Note |
---|---|
0 |
Share with PWM_3 |
1 |
Share with PWM_0 |
2 |
Share with PWM_1 |
3 |
Share with PWM_2 |
4 |
Share with software RTC |
The timer can be set to be periodic or for single use. The periodic timers reset periodically, and the single-use timers do not. Open the example, “File” -> “Examples” -> “AmebaGTimer” -> “TimerPeriodical”. Compile and upload to Ameba, and press reset. In the Serial Monitor, you can see the counter value is increased periodically.
Code Reference
The first argument of begin() is the timer id (0~5). 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. In the example, we call the “myhandler” function to increase the counter value by 1 and print the counter value to serial monitor.
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);
[RTL8722CSM] [RTL8722DM] Timer - Using The Single-Use GTimer
Preparation
Ameba x 1
Example
In this example, we use five single-use GTimer, and carry user data in eac timer. Open the example “File” -> “Examples” -> “AmebaGTimer” -> “TimerOneshot”. Compile and upload to Ameba, and press reset. Then you can see the 5 timers print out log to the serial monitor in series.
Code Reference
The first argument of begin() is the Timer ID (0~4). 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 five timers are separately set to count for 1, 2, 3, 4, 5 seconds, from 1 second to 5 second, the user data of each timer are printed on the serial monitor in order. After 5 second, no log will be printed.
[RTL8722CSM] [RTL8722DM] Power Save Deep Sleep Mode
Materials
RTL8722DM x 1
Example
Introduction
Ameba-D supports two low power modes which are deepsleep mode and sleep mode. Deepsleep mode turns off more power domain than sleep mode. The power consumptions of DeepSleep Mode is around 7uA to 8uA compare to normal state around 22mA. This example describes how to enter deepsleep mode and configure wakeup source.

AON timer can be set from 0 to 32760000 range (unit ms) by AON_TIMER_SLEEP_DURATION
There are 4 pins can be set as AON pins and active high for wake-up, D16, D17, D26 and D27. The AON pin can be set by SET_DS_AON_WAKEPIN_WAKEUPPIN
RTC timer wake-up system by set alarm. The alarm has 4 values, day, hour, min and sec. All 4 values can be set by DS_RTC_ALARM_DAY, DS_RTC_ALARM_HOUR, DS_RTC_ALARM_MIN, and DS_RTC_ALARM_SEC

When finished the condition values setting, system will run and switch between normal and deepsleep mode controlled by wakeup source. Serial Monitor displays the switching log.



Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
[RTL8722CSM] [RTL8722DM] Power Save Deep Sleep DHT Eink
Materials
RTL8722DM 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 Eink 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).

AON timer can be set from 0 to 32760000 range (unit ms) by AON_TIMER_SLEEP_DURATION
There are 4 pins can be set as AON pins and active high for wake-up, D16, D17, D26 and D27. The AON pin can be set by SET_DS_AON_WAKEPIN_WAKEUPPIN
RTC timer wake-up system by set alarm. The alarm has 4 values, day, hour, min and sec. All 4 values can be set by DS_RTC_ALARM_DAY, DS_RTC_ALARM_HOUR, DS_RTC_ALARM_MIN, and DS_RTC_ALARM_SEC

When finished the condition values setting, system will run and switch between normal 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.
[RTL8722CSM] [RTL8722DM] Power Save Deep Sleep DHT LCD
Materials
RTL8722DM 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).

AON timer can be set from 0 to 32760000 range (unit ms) by AON_TIMER_SLEEP_DURATION
There are 4 pins can be set as AON pins and active high for wake-up, D16, D17, D26 and D27. The AON pin can be set by SET_DS_AON_WAKEPIN_WAKEUPPIN
RTC timer wake-up system by set alarm. The alarm has 4 values, day, hour, min and sec. All 4 values can be set by DS_RTC_ALARM_DAY, DS_RTC_ALARM_HOUR, DS_RTC_ALARM_MIN, and DS_RTC_ALARM_SEC

When finished the condition values setting, system will run and switch between normal 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.
[RTL8722CSM] [RTL8722DM] Power Save Tickless Mode
Materials
RTL8722DM 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.

When apply the LOGUART wakeup, KM4 “TL_Suspend_function” then enter sleep mode. KM0 keep alive 13s then enter sleep mode.
RTC timer wake-up system by set alarm. The alarm has 4 values, day, hour, min and sec. All 4 values can be set by TL_RTC_ALARM_DAY, TL_RTC_ALARM_HOUR, TL_RTC_ALARM_MIN, and TL_RTC_ALARM_SEC
There are 4 pins can be set as AON pins and active high for wake-up, D16, D17, D26 and D27. The AON pin can be set by SET_TL_AON_WAKEPIN_WAKEUP
TL_SYSACTIVE_TIME is for setting time duration of the system to keep alive. (unit ms)




Code Reference
Please refer to the API Documents PowerSave section for detail description of all API.
[RTL8722CSM] [RTL8722DM] Use NTPClient Library To Obtain Local Time
Preparation
Ameba 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”Modify the highlighted code section
(ssid, password) to connect to your WiFi network.
Compile the
code and upload it to Ameba. After pressing the Reset button, Ameba
connects to WiFi, gets the UTC time from the NTP server, and prints out
the current time with time zone offset to the serial monitor.
Code Reference
Configure NTP client: The NTPClient needs to use a UDP client for communications. A WiFiUDP client is declared and passed to the NTPClient constructor, along with an NTP server address, time zone offset in seconds, and update interval in milliseconds. If detailed configuration is not needed, just passing in the UDP client is also sufficient, refer to the “NTPClient” -> “Basic” example.
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, “europe.pool.ntp.org”, 3600, 60000);
Start NTP client: After connecting to WiFi, the NTPClient is started using the begin() function, which causes the client to sync with the NTP server and get the UTC time.
WiFiUDP ntpUDP;
timeClient.begin();
Get local time: 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();
[RTL8722CSM] [RTL8722DM] Transmit IR NEC Raw Data And Decode
Materials
Ameba x2 (one for IR transmitting, the other one for IR receiving)
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.

Figure 1: Grove – Infrared Receiver

Figure 2: Grove – Infrared Emitter

Figure 3: A typical IR transmission and reception setup implementation
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.

Figure 4: Modulation of NEC
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 5: Sample of a Full NEC Data (in logic1 or 0)

Figure 6: Sample of a Full NEC RAW Data (in us)
Figure 7 and 8 shows the pin configuration of IR Emitter and Receiver with Ameba RTL8722 board.

Figure 7: Pin configuration of IR Emitter and Ameba RTL8722

Figure 8: Pin configuration of the IR Receiver and Ameba RTL8722
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” -> “RTL8722CSM/RTL8722DM”.
Open the “IRSendRAW” example in “File” -> “Examples” -> “AmebaIRDevice” -> “IRSendRAW” (Figure 9) and upload to 1st board connected with IR Emitter:

Figure 9: Example Location of IRSendRaw and IRRecvNEC
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.

Figure 10: Pulse View results from sending and receiving pin
Code Reference
[RTL8722CSM] [RTL8722DM] Display Images On E-Paper
Materials
Ameba x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
In this example, we use the Ameba RTL8722 module connects to a Waveshare
2.9inch e-Paper module to display a few QR codes. The display uses the
flexible substrate as a base plate, with an interface and a reference
system design. The 2.9” active area contains 296×128 pixels and has
1-bit white/black full display capabilities. An integrated circuit
contains gate buffer, source buffer, interface, timing control logic,
oscillator, etc… are supplied with each panel. You may refer to the
official 2.9inch e-Paper HAT (D)
datasheet to
know more information about this module. Front view of the e-Paper
Module:RTL8722 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. Then we move to the coding part for this
example. First, make sure the correct Ameba development board is
selected in Arduino IDE: “Tools” -> “Board” -> “RTL8722CSM/RTL8722DM”.
Then open the “DisplayQR” example in “File” -> “Examples” -> “AmebaEink”
-> “EinkDisplayImage “:
Upon successfully upload the sample
code and press the reset button, you need to wait for around 1~2 seconds
for the e-Paper module to fresh its screen. Then the screen will start
to display an image for 5 seconds first, then 3 different QR codes will
be displayed every 5 seconds (showing in the screenshot below, y may
scan the QR codes and find out more information if you wish to). Lastly,
a gif in which forms of 3 frames will be displayed for a few
seconds.
Code Reference
[RTL8722CSM] [RTL8722DM] Display Text On E-Paper
Materials
Ameba x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
In this example, we use the Ameba RTL8722 module connects to a Waveshare
2.9inch e-Paper module to display a texts in alphanumeric. The display
uses the flexible substrate as the base plate, with interface and a
reference system design. The 2.9” active area contains 296×128 pixels
and has 1-bit white/black full display capabilities. An integrated
circuit contains gate buffer, source buffer, interface, timing control
logic, oscillator, etc… are supplied with each panel. You may refer to
the official 2.9inch e-Paper HAT (D)
datasheet to
know more about this module. Front view of the e-Paper
Module:RTL8722 wiring diagram:
Firstly, you need
to open the “DisplayText” example in “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
[RTL8722CSM] [RTL8722DM] Display User-Generated QR Code on E-Paper
Materials
Ameba x 1
Waveshare 2.9inch e-Paper HAT (D) x 1
Example
In this example, we use the Ameba RTL8722 module connects to a Waveshare
2.9inch e-Paper module to display a few QR codes. The display uses the
flexible substrate as the base plate, with interface and a reference
system design.The 2.9” active area contains 296×128 pixels and has 1-bit
white/black full display capabilities. An integrated circuit contains
gate buffer, source buffer, interface, timing control logic, oscillator,
etc… are supplied with each panel. You may refer to the
official 2.9inch e-Paper HAT (D)
datasheet to
know more about this module. Front view of the e-Paper
Module:RTL8722 wiring diagram:
Firstly, you need
to open the “DisplayQR” example in “File” -> “Examples” -> “AmebaEink”
-> “EinkDisplayQR”:
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
[RTL8722CSM] [RTL8722DM] A Simple RTC Example
Materials
Ameba D [RTL8722 CSM/DM] 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.

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
[RTL8722CSM] [RTL8722DM] Simple RTC Alarm
Materials
Ameba D [RTL8722 CSM/DM] 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” -> “RTL8722CSM/RTL8722DM”. 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.

[RTL8722CSM] [RTL8722DM] Watchdog Timer Simple Example
Materials
Ameba D [RTL8722 CSM/DM] 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
If you have a dog in your home. You need to feed that dog at a regular interval. if you can’t feed one day, it will bite you! And likewise, this is the working logic behind the watchdog timer.
Then we move to the coding part for this example, for this example, you will only need the Ameba RTL8722 board itself.

Firstly, make sure the correct Ameba development board is selected in Arduino IDE: “Tools” -> “Board” -> “RTL8722CSM/RTL8722DM”. Then open the “Watchdog Timer” example in “File” -> “Examples” -> “AmebaWatchdog” -> “Watchdog Timer”:

Upon successfully upload the sample code, open the serial monitor, and press the reset button. You will find that the successful task (small task) can refresh the watchdog within the 5 seconds (initialized in the watchdog timer). However, the failed task (big task) will not be able to refresh the watchdog within 5 seconds, which leads to the microcontroller reset.

[RTL8722CSM/RTL8722DM] Audio Codec – Basic Input Output
Materials
Ameba D [RTL8722 CSM/DM] 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
Procedure
Connect the potentiometer, microphone and 3.5mm connector to the RTL8722 board following the diagram.

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.
[RTL8722CSM/RTL8722DM] Audio Codec – FFT
Materials
Ameba D [RTL8722 CSM/DM] x 1
Example
Introduction
This example shows how to use the FFT class to calculate the fast Fourier transform of a signal to extract the frequencies present in the signal.
Procedure
Open the example, 「Files」 -> 「Examples」 -> “AmebaAudioCodec” -> “FFT”.

Upload the code and press the reset button on Ameba once the upload is finished.
Open the serial monitor, and the output results of the FFT calculation will be displayed.

[RTL8722CSM/RTL8722DM] Audio Codec – Input FFT
Materials
Ameba D [RTL8722 CSM/DM] x 1
Analog microphone x 1 (e.g., Adafruit 1063 / 1064)
Example
Introduction
This example shows how to use the FFT class to calculate the fast Fourier transform of the audio signal recorded by the microphone.
Procedure
Connect the microphone to the RTL8722 board following the diagram.

Open the example, 「Files」 -> 「Examples」 -> “AmebaAudioCodec” -> “InputFFT”.

Upload the code and press the reset button on Ameba once the upload is finished.
Open the serial monitor and change the baud rate to 2000000. A stream of FFT results of audio samples will be displayed. Try playing music or use a smartphone app to generate a sine wave into the microphone, and you should be able to see the FFT output change.

[RTL8722CSM/RTL8722DM] Audio Codec – Output Sine Wave
Materials
Ameba D [RTL8722 CSM/DM] x 1
3.5mm TRS/TRRS breakout x 1 (e.g., Adafruit 2791 / Sparkfun 11570)
Example
Procedure
Connect the 3.5mm connector to the RTL8722 board following the diagram.

Open the example, 「Files」 -> 「Examples」 -> “AmebaAudioCodec” -> “OutputSineWave”.

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 and you should hear the generate single sinusoidal tone.
[RTL8722DM_mini] FatfsSDIO – File system in SD card
Materials
Ameba D [RTL8722DM_mini] x 1
MicroSD card
Example
Procedure
Insert a MicroSD card into the onboard SD card reader of RTL8722DM_mini board.
Example 01 create_folder
Open the example, 「Files」 -> 「Examples」 -> “AmebaFatfsSDIO” -> “create_folder”.

Upload the code and press the reset button on Ameba once the upload is finished.
In the sample code, we first create a folder “testdir”, then text file
“test.txt” with content “hello world!”. Read the file and print content
to serial monitor.
Next, insert SD card into card reader, and check whether the operations succeeded.

Example 02 file_read_write
Open the example, 「Files」 -> 「Examples」 -> “AmebaFatfsSDIO” -> “file_read_write”.
Upload the code and press the reset button on Ameba once the upload is finished.
In the sample code, we create text file “test.txt” with content “hello world!”. Read the file and print content to serial monitor.

Next, insert SD card into card reader, and check whether the operations succeeded.

Example 03 get_file_attribute
Open the example, 「Files」 -> 「Examples」 -> “AmebaFatfsSDIO” -> “get_file_attribute”.
Upload the code and press the reset button on Ameba once the upload is finished.
In the sample code, system will print put all file attribute to serial monitor.

Next, insert SD card into card reader, and check whether the operations succeeded. In this case, we already know the attribute should be folder “testdir” and text file “test.txt”by refer the above pictures.
Example 04 last_modified_time
Open the example, 「Files」 -> 「Examples」 -> “AmebaFatfsSDIO” -> “last_modified_time”.
Upload the code and press the reset button on Ameba once the upload is finished.
In the sample code, system will print put the target file last modified time to serial monitor.

Next, insert SD card into card reader, and check whether the operations succeeded.

Example 05 list_root_files
Open the example, 「Files」 -> 「Examples」 -> “AmebaFatfsSDIO” -> “list_root_files”.
Upload the code and press the reset button on Ameba once the upload is finished.
In the sample code, system will print put all root file to serial monitor.

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.
[RTL8722CSM/RTL8722DM] TensorFlow Lite - Hello World
Materials
Ameba D [RTL8722 CSM/DM] 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”.

Upload the code and press the reset button on Ameba once the upload is finished.
Connect the LED to digital pin 10 and ground, ensuring that the polarity is correct. You should see the LED fade in and out rapidly.
In the Arduino serial plotter, you can see the output value of the Tensorflow model plotted as a graph, it should resemble a sine wave.

Code Reference
More information on TensorFlow Lite for Microcontrollers can be found at: https://www.tensorflow.org/lite/microcontrollers
[RTL8722CSM/RTL8722DM] TensorFlow Lite - Magic Wand
Materials
Ameba D [RTL8722 CSM/DM] x 1
Adafruit LSM9DS1 accelerometer
LED x 2
Example
Procedure
Connect the accelerometer and LEDs to the RTL8722 board following the diagram.

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.
In the Arduino IDE library manager, install the Arduino_LSM9DS1 library. This example has been tested with version 1.1.0 of the LSM9DS1 library.
Open the example, 「Files」 -> 「Examples」 -> “TensorFlowLite_Ameba” -> “magic_wand”.

Upload the code and press the reset button on Ameba once the upload is finished.
Holding the accelerometer steady, with the positive x-axis pointing to the right and the positive z-axis pointing upwards, move it following the shapes as shown, moving it in a smooth motion over 1 to 2 seconds, avoiding any sharp movements.

If the movement is recognised by the Tensorflow Lite model, you should see the same shape output to the Arduino serial monitor. Different LEDs will light up corresponding to different recognized gestures.
Note that the wing shape is easy to achieve, while the slope and ring shapes tend to be harder to get right.

Code Reference
More information on TensorFlow Lite for Microcontrollers can be found at: https://www.tensorflow.org/lite/microcontrollers
[RTL8722CSM/RTL8722DM] TensorFlow Lite - Micro Speech
Materials
Ameba D [RTL8722 CSM/DM] x 1
Adafruit PDM MEMS microphone
LED x 4
Example
Procedure
Connect the microphone and LEDs to the RTL8722 board following the diagram.

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” -> “micro_speech”.

Upload the code and press the reset button on Ameba once the upload is finished.
Once it is running, you should see one of the LEDs flashing, indicating that it is processing audio. Saying the word 「yes」 will cause the green LED to light up. Saying the word “no” will cause the red LED to light up. If the word is not recognized, the blue LED will to light up.
The inference results are also output to the Arduino serial monitor, which appear as follows:

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
[RTL8722CSM/RTL8722DM] TensorFlow Lite - Person Detection
Materials
Ameba D [RTL8722 CSM/DM] x 1
Arducam Mini 2MP Plus OV2640 SPI Camera Module x 1
LED x 3
Example
Procedure
Connect the camera and LEDs to the RTL8722 board following the diagram.

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.
You will also need to install the Ameba_ArduCAM library, found together with the TensorFlow Lite library.
In the Arduino IDE library manager, install the JPEGDecoder library. This example has been tested with version 1.8.0 of the JPEGDecoder library.
Once the library has installed, you will need to configure it to disable some optional components that are not compatible with the RTL8722DM. Open the following file:
Arduino/libraries/JPEGDecoder/src/User_Config.h
Make sure that both #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”.

Upload the code and press the reset button on Ameba once the upload is finished.
Once it is running, you should see the blue LED flashing once every few seconds, indicating that it has finished processing an image. The red LED will light up if it determines that there is no person in the previous image captured, and the green LED will light up if it determines that there is a person.
The inference results are also output to the Arduino serial monitor, which appear as follows:

Code Reference
More information on TensorFlow Lite for Microcontrollers can be found at: https://www.tensorflow.org/lite/microcontrollers
相關元件介紹
|
|
|
|
|
|
|
(End)
HDK 硬件參考
API Documents
Class AmebaServo
AmebaServo Class
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. |
AmebaServo::attach
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.
AmebaServo::detach
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.
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 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
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
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
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 |
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
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
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
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
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
MQTTClient_Readme
The Ameba MQTT related APIs and examples are works based on the PubSubClient libraries written by Nicholas O’Leary (http://pubsubclient.knolleary.net).
These include,
These libraries are under MIT License.
NTPClient_Readme
The NTPClient library is based on the NTPClient library written by Fabrice Weinberg, which can be found at https://github.com/arduino-libraries/NTPClient. These include, NTPClient.cpp NTPClient.h These libraries are licensed under MIT License.
Class PMUClass
PMUClass Class
Members
Public Constructors |
|
---|---|
PMUClass::PMUClass |
Constructs a PMUClass object |
Public Methods |
|
PMUCLASS::begin |
Initialize the PMUCLASS select sleep mode |
PMUCLASS::AONTimerDuration |
Set time duration of AON timer |
PMUCLASS::AONTimerCmd |
Disable the AON timer for power save usage |
PMUCLASS::RTCWakeSetup |
Setup RTC timer for power save usage |
PMUCLASS::enable |
Enable power save deep sleep mode |
PMUCLASS::AONWakeReason |
Check the AON wakeup source |
PMUCLASS::WakePinCheck |
Check AON pin as wake up source |
PMUCLASS::AONWakeClear |
Clear all AON wake up source |
PMUCLASS::DsleepWakeStatusGet |
Check if set deepsleep mode |
PMUCLASS::TL_sysactive_time |
Tickless mode system active time |
PMUCLASS::TL_wakelock |
Tickless mode wake lock, select acquire or release |
PMUCLASS::PMUCLASS
PMUCLASS::begin
PMUCLASS::AONTimerDuration
PMUCLASS::AONTimerCmd
PMUCLASS::RTCWakeSetup
PMUCLASS::enable
PMUCLASS::AONWakeReason
PMUCLASS::WakePinCheck
PMUCLASS::AONWakeClear
PMUCLASS::DsleepWakeStatusGet
PMUCLASS::TL_sysactive_time
PMUCLASS::TL_wakelock
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
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
SoftwareSerial_Readme
The Ameba Software Serial related APIs and examples are works based on libraries formerly known as NewSoftSerial.h by Mikal Hart (http://arduiniana.org/libraries/newsoftserial).
These include,
These libraries are under GNU Lesser General Public License.
The Ameba GPS related APIs and examples are works based on Adafruit GPS library written by Limor Fried/Ladyada for Adafruit Industries (http://www.adafruit.com/products/746).
These libraries are under BSD License.
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
SPI_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.
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
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
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
WiFi_Readme
The Ameba WiFi related APIs and examples are works based on Arduino WiFI shield libraries (https://www.arduino.cc/en/Reference/WiFi).
These include,
These libraries are under GNU Lesser General Public License, either version 2.1 of the License, or (at your option) any later version.
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.
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 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 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
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
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);
}
其他資源
網頁鏈接
技術支援
常見問題
-
請參考 購買鏈接.
- RTL8722CSM/RTL8722DM 支持哪些藍牙標準?
兩者皆支援 BLE 5.0。 Classic Bluetooth (BR/EDR) 則不支援。
- 支持哪些BLE設備?
RTL8722CSM/RTL8722DM 可當作 BLE Central 或 BLE Peripheral 設備。
- RTL8722CSM /RTL8722DM上的所有接腳都可用嗎?
不,標有“NC”的未連接到任何接腳,因此無法使用。
- RTL8722CSM 支援 5G WiFi 嗎?
不,只有 RTL8722DM 支援雙頻 2.4G + 5G WiFi。 RTL8722CSM 只有支援單頻 2.4G WiFi。
- 如何進入下載模式??
按住UART DOWNLOAD按鈕,然後按下RESET按鈕,并同時放開UART DOWNLOAD和RESET按鈕。
故障排除
-
請確保天線連接正確。 檢查您的程式碼有確認正確的藍牙配置。
-
嘗試使用printf和Serial.print語法除錯。 如果問題仍然存在,您可以在 論壇 尋求幫助
連接到RTL8722CSM / RTL8722DM UART後,為什麼串行終端上沒有輸出?
RTL8722CSM / RTL8722DM 默認配置為115200波特率,請檢查串行終端是否配置為115200。
程序無法下載到RTL8722CSM / RTL8722DM中
- 請按照以下步驟正確下載:
請進入下載模式。 進入下載模式時,開發版綠色LED指示燈將閃爍。
下載過程中,開發版紅色LED指示燈將閃爍。
下載成功後,Arduino IDE會出現通知。
-
RTL8722CSM / RTL8722DM 的預設天線使用I-Pex連接器。 請更換/連接I-Pex連接器天線。
-
請確認已連接電阻R43旁的連接器J38。 該連接器用於將電源鏈接到IC。
RTL8722DM-MINI
歡迎來到 Ameba Arduino RTL8722DM-MINI 在綫文檔
RTL8722DM_mini 快速入門
環境配置
AmebaD RTL8722DM_MINI 目前支持32位和64位 Windows XP/7/8/10,Linux 和 Mac 操作系統。 在本文檔中,請使用使用 1.8.12 或更高版本的 Arduino IDE。
AmebaD RTL8722DM_MINI 簡介
Ameba 是一個用於開發所有類型的物聯網應用,易於編程的平台。 AmebaD 配備了包括 WiFi、GPIO INT、 I2C、UART、SPI、PWM、ADC 各種外圍接口。通過這些接口,AmebaD可以與如 LED、開關、壓力計、濕度計 PM2.5粉塵傳感器等電子元件連接。採集的數據可以通過 WiFi上傳,並被智能設備上的應用程序利用, 以實現物聯網的實施。

RTL8722DM_MINI的尺寸比Arduino Uno小,如上圖所示。

相關資源下載
發佈歷史
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
外圍設備 & 示例
基本示例
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 |
---|---|---|---|
|
An alogReadSerial |
Connect potentiometer. Reading voltage range 0 to 3.3V. |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. |
BareMinimum |
|||
Blink |
Onboard LEDs options LED_B and LED_G. (blue and green) |
||
Dig italReadSerial |
Onboard button PUSH_BTN. |
||
Fade |
Replace 「led = 9;」 by a PWM pin (D4, D5, D7, D9, D10, D14, D17, D20, or D21). e.g. 「led = 4;」 |
* * |
|
Rea dAnalogVoltage |
ADC can read a maximum of 3.3V. |
* * |
|
|
Bli nkWithoutDelay |
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. |
||
Digi talInputPullup |
Onboard LEDs options LED_B and LED_G. |
||
StateC hangeDetection |
Onboard LEDs options LED_B and LED_G. Onboard button PUSH_BTN. |
||
toneKeyboard |
Replace 「tone(8, note s[thisSensor], 20);」 by a PWM pin (D4, D5, D7, D9, D10, D14, D17, D20, or D21). e.g. 「tone(21, note s[thisSensor], 20);」 |
||
toneMelody |
|||
toneMultiple |
|||
ton ePitchFollower |
|||
|
Ana logInOutSerial |
Replace 「const int analogOutPin = 9;」 by a PWM pin (D4, D5, D7, D9, D10, D14, D17, D20, or D21). e.g. 「const int analogOutPin = 4;」 |
|
AnalogInput |
Onboard LEDs options LED_B and LED_G. |
||
Analog Write Mega |
|||
Calibration |
Replace 「ledPin = 9;」 by a PWM pin (D4, D5, D7, D9, D10, D14, D17, D20, or D21). e.g. 「ledPin = 4;」 |
Onboard LEDs options LED_B and LED_G. Onboard button PUSH_BTN. |
|
Fading |
|||
Smoothing |
|||
04. Communication |
ASCIITable |
||
Dimmer |
Replace 「ledPin = 9;」 by a PWM pin (D4, D5, D7, D9, D10, D14, D17, D20, or D21). e.g. 「ledPin = 4;」 |
||
Graph |
Connect potentiometer. Reading voltage range 0 to 3.3V. |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. |
|
Midi |
Please use Serial1 with D18 or Serial2 with D1. |
||
MultiSerial |
|||
PhysicalPixel |
Onboard LEDs options LED_B and LED_G. |
||
R eadASCIIString |
Use PWM pin for LED (D4, D5, D7, D9, D10, D14, D17, D20, or D21). |
||
Seri alCallResponse |
|||
SerialCal lResponseASCII |
|||
SerialEvent |
|||
Ser ialPassthrough |
For “Serial1”, please use D18 and D19. |
||
Vir tualColorMixer |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. |
||
|
Arrays |
||
Fo rLoopIteration |
|||
IfStatem entConditional |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. Onboard LEDs options LED_B and LED_G. |
||
switchCase |
|||
switchCase2 |
|||
WhileStatem entConditional |
Replace 「ledPin = 9;」 by a PWM pin (D4, D5, D7, D9, D10, D14, D17, D20, or D21). e.g. 「ledPin = 4;」 |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. |
|
|
barGraph |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. Onboard LEDs options LED_B and LED_G. |
|
Row ColumnScanning |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. |
||
|
Cha racterAnalysis |
||
StringAd ditionOperator |
|||
String AppendOperator |
|||
Str ingCaseChanges |
|||
St ringCharacters |
|||
StringCompa risonOperators |
ADC pin options A0, A1, A2, A3, A4, A5 and A6. |
||
StringIndexOf |
|||
StringLength |
|||
St ringLengthTrim |
|||
StringReplace |
|||
StringStar tsWithEndsWith |
|||
S tringSubstring |
|||
StringToInt |
開發板HDK文件
API 手冊
Resources
Links
Support
FAQ
如何購買 Ameba RTL8722DM Board?
請參考 購買連結.
RTL8722CSM/RTL8722DM 支持哪些藍牙標準?
兩者皆支援 BLE 5.0。 Classic Bluetooth (BR/EDR) 則不支援。
RTL8722CSM /RTL8722DM上的所有接腳都可用嗎?
不,標有“NC”的未連接到任何接腳,因此無法使用。
RTL8722CSM/RTL8722DM 有支援 XIP (execute in place)嗎?
有支援。
RTL8722CSM 有支援 5G WiFi 嗎?
不,只有 RTL8722DM 支援雙頻 2.4G + 5G WiFi。 RTL8722CSM 只有支援單頻 2.4G WiFi。
如何進入下載模式?
按住UART DOWNLOAD按鈕,然後按下RESET按鈕並放開UART DOWNLOAD和RESET按鈕。
Trouble shooting
無法找到藍牙裝置RTL8722CSM/RTL8722DM
請確保天線連接正確。 檢查您的程式碼有確認正確的藍牙配置。
程式碼操作不如預期
嘗試使用printf和Serial.print語法除錯。如果問題仍然存在,您可以在 論壇 尋求幫助。
連接到RTL8722CSM / RTL8722DM UART後,為什麼串行終端上沒有輸出?
RTL8722CSM / RTL8722DM 默認配置為115200波特率,請檢查串行終端是否配置為115200。
程序無法下載到RTL8722CSM / RTL8722DM中
請按照以下步驟正確下載。 1. 請進入下載模式。 進入下載模式時,開發版綠色LED指示燈將閃爍。 2. 1. 下載過程中,開發版紅色LED指示燈將閃爍。 3. 下載成功後,Arduino IDE會出現通知。
WiFi有時信號較弱
RTL8722CSM / RTL8722DM 的預設天線使用I-Pex連接器。 請更換/連接I-Pex連接器天線。
Micropython 開發平台
歡迎來到 Ameba MicroPython 的綫上文檔
快速入門
環境配置
AmebaD RTL8722CSM/RTL8722DM MicroPython SDK 目前支持 Windows 10 和 Linux 操作系統。
Introduction to AmebaD RTL8722CSM/RTL8722DM
Ameba 是一個用於開發所有類型的物聯網應用,易於編程的平台。 AmebaD 配備了包括 WiFi、GPIO INT、 I2C、UART、SPI、PWM、ADC 各種外圍接口。通過這些接口,AmebaD可以與如 LED、開關、壓力計、濕度計 PM2.5粉塵傳感器等電子元件連接。採集的數據可以通過 WiFi上傳,並被智能設備上的應用程序利用, 以實現物聯網的實施。
D00 |
PB_2 |
✓ |
ADC5 |
UART3_RX(b) |
|||
D01 |
PB_1 |
✓ |
ADC4 |
UART3_TX(b) |
|||
D02 |
PB_3 |
✓ |
ADC6 |
||||
D03 |
PB_31 |
✓ |
|||||
D04 |
PB_30 |
✓ |
|||||
D05 |
PB_28 |
✓ |
|||||
D06 |
PB_29 |
✓ |
|||||
D07 |
NC |
||||||
D08 |
PB_22 |
✓ |
PWM14 |
||||
D09 |
PB_23 |
✓ |
PWM15 |
||||
D10 |
PB_21 |
✓ |
PWM13 |
UART0_RTS(b) |
SPI0_CS |
||
D11 |
PB_18 |
✓ |
PWM10 |
UART0_RX(b) |
SPI0_MOSI |
||
D12 |
PB_19 |
✓ |
PWM11 |
UART0_TX(b) |
SPI0_MISO |
||
D13 |
PB_20 |
✓ |
PWM12 |
UART0_CTS(b) |
SPI0_CLK |
||
D14 |
PA_7 |
✓ |
UART2_TX(log) |
||||
D15 |
PA_8 |
✓ |
UART2_RX(log) |
||||
D16 |
PA_25 |
✓ |
PWM4 |
UART3_RX(a) |
I2C0_SCL |
||
D17 |
PA_26 |
✓ |
PWM5 |
UART3_TX(a) |
I2C0_SDA |
||
D18 |
PB_7 |
✓ |
ADC3 |
PWM17 |
SPI1_CS |
||
D19 |
PB_6 |
✓ |
ADC2 |
SPI1_CLK |
|||
D20 |
PB_5 |
✓ |
ADC1 |
PWM9 |
SPI1_MISO |
||
D21 |
PB_4 |
✓ |
ADC0 |
PWM8 |
SPI1_MOSI |
||
D22 |
PA_28 |
✓ |
|||||
D23 |
PA_24 |
✓ |
PWM3 |
UART0_CTS(a) |
I2C1_SDA |
||
D24 |
PA_23 |
✓ |
PWM2 |
UART0_RTS(a) |
I2C1_SCL |
||
D25 |
PA_22 |
✓ |
UART0_RX(a) |
||||
D26 |
PA_21 |
✓ |
UART0_TX(a) |
||||
D27 |
PA_20 |
✓ |
|||||
D28 |
PA_19 |
✓ |
Note: Not all sets of peripherals shown on the picture/table above are available on MicroPython, please refer to “Peripheral Example and API” section for more information.
Introduction to RTL8722 MicroPython port
Background Information
MicroPython, by definition, is a lean and efficient Python3 compiler and runtime specially designed for microcontrollers.
MicroPython distinguishes itself from other compilation-based platforms (Arduino etc.) with its powerful method of real-time interaction to Microcontroller through a built-in feature – REPL.
REPL stands for Read-Evaluation-Print-Loop, it is an interactive prompt that you can use to access and control your microcontroller.
REPL has been equipped with other powerful features such as tab completion, line editing, auto-indentation, input history and more. It basically functions like the classic Python IDLE but running on microcontroller.
To use REPL, simply open any serial terminal software (most common ones are teraterm, putty etc.) on your PC and connect to your microcontroller’s serial port, then set baudrate to 115200 before manually reset the board, then you will see >>> MicroPython prompt appear on the terminal. Now you may type in any Python script on REPL as long as it’s support by MicroPython and your microcontroller’s MicroPython port.
Most importantly, try to abuse 「help()」 function as much as possible to gain more information. For example, upon microcontroller power up and REPL shown, just type
>>> help()
You will see a help page giving you more details about this port; also if you type
>>> help(modules)
it will list out all available builtin modules that are at your disposal
Furthermore, if you want to learn more about a module, such as its API and CONSTANT available, simply type the following code and details of that module will be returned to you,
>>> help(the module of your interest)
Let’s take Pin module (GPIO) as an example:
>>> 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 Hotkeys
Ctrl + d :
Soft reboot MicroPython will perform software reboot, this is useful when your microcontroller is behaving abnormally. This will also run scripts in 『boot.py』 once again. Note that this will only reset the MicroPython interpreter not the hardware, all your previously configured hardware will stay the way it is until you manually hard-reset the board.
Ctrl + e :
Paste mode Paste mode allow you to perform pasting a large trunk of code into REPL at once without executing code line by line. This is useful when you have found a MicroPython library and wish to test it out immediately by copy and paste
Ctrl + b :
Normal mode This hotkey will set REPL back to normal mode. This is useful if you are stuck in certain mode and can not get out.
Ctrl + c :
Quick cancel This hotkey help you to cancel any input and return a new line
Setting up Development Environment
Step 1. Installing the Driver
First, connect AmebaD to the computer via Micro USB:
Step 2. Installing the necessary tools
On Windows
For windows users, please install a serial terminal software to interact with MicroPython. The most common serial terminals are Tera Term and Putty, here we recommend using Tera Term, which can be downloaded from internet.
For advanced developer who wish to compile MicroPython firmware from scratch, then please be sure to install Cygwin, which is a Linux-like environment running on Windows system. When selecting the Cygwin installer, we recommend using the Cygwin 32-bit version. During Cygwin installation, installer will prompt user if wish to install other software, please make sure to select the GNU version of make from the Devel category (see picture below) and pick the latest edition.
Also, Python3 is required during firmware compilation, so be sure to download the latest Python3 from its official website and have it added as environment variable when asked during installation.
On Linux
For Linux user, please install a serial terminal software of your choice using apt-get install command. Here we recommend using picocom for its lightweight.
For advanced developer interested in developing MicroPython module in C, please make sure the GNU make of at least version 3.82 or newer and Python3 are installed and can be found using terminal.
Upload Firmware into Ameba
Step 2. Enter UART Download mode
To do this, first press and hold the UART_DOWNLOAD button, then press the RESET button. If success, you should see a green LED flashing on your ameba.
Step 3. Run “Double-Click-Me-to-Upload”
As the name suggested, double click on the file to run it, follow instructions printed on the screen to update the ameba’s serial COM port (this is known to us during the driver installation step mentioned above) so the uploading can be carried out successfully. Once the uploading is successful, you will see a line of log printed on the screen – “All images are sent successfully”
Try the First Example
Step 1. Open REPL
REPL stands for Read, Evaluate, Print and Loop, it is the MicroPython’s terminal for user to control the microcontroller. REPL is running on LOG UART, thus we need to open our serial terminal software, in this case, Tera Term to see REPL,
Once Tera Term is opened, select “Serial” like in the picture above and choose your ameba’s serial port using the dropdown list, after that, hit “OK”. If your serial terminal is not configured to 115200 baud rate, now is the time to change it to 115200 and leave the rest of settings as default.
Now that the serial port is connected, press the RESET button once on your ameba and you should see the MicroPython’s welcome page as shown below,
What happened here was that your Ameba first check its calibration data and then boot into MicroPython’s firmware, MicroPython then run the “boot.py” python script and imported builtin libraries.
Now, you can simply type
>>> help()
to see more information, and type
>>> help(modules)
to check all readily available libraries
Step 2. Run WiFi Scan example
As most of peripherals’ examples requires additional hardware to show the example is working, we will just use WiFi Scan example as our first example and to see how easy it is to control WiFi using MicroPython.
Now, please follow along by copy+paste the following code or manually typing them out into Tera Term and hit “Enter”
>>> from wireless import WLAN
>>> wifi = WLAN(mode = WLAN.STA)
>>> wifi.scan()
You should be able to see the returned result with all discovered wireless network in your surrounding
(End)
If you face any issue, please refer to the FAQ and troubleshooting page.
相關資源下載
Release History
Version 1.0.0 release – 2020/11/11
Feature:
– OS Support Windows and Linux
– WiFi
– Socket
– ADC
– built-in 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
Examples
Network/Peripheral Examples
[RTL8722CSM] [RTL8722DM] ADC - Read potentiometer
Materials
Ameba x 1, Potentiometerx 1
Steps
Here we connect ameba to a potentiometer to measure its analogue value, the connection is as follows.
Copy and paste the following code into REPL.
1import socket
2a = ADC(0)
3a.read()
[RTL8722CSM] [RTL8722DM] GPIO - Blink
Materials
Ameba x 1, LED x 1, Resistor(220ohm) x 1
Steps
Blink is one of the best examples to get started with MicroPython.
Let us connect pin PB_22 to the anode leg of an LED which in series with a current limiting resistor and GND to cathode of the LED as shown below,
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.
1from machine import Pin
2a = Pin("PB_22", Pin.OUT)
3a.value(1)
4time.sleep_ms(500)
5a.value(0)
6time.sleep_ms(500)
7a.on()
8time.sleep_ms(500)
9a.off()
10time.sleep_ms(500)
11a.toggle()
12time.sleep_ms(500)
13a.toggle()
[RTL8722CSM] [RTL8722DM] I2C - Send and Receive
Materials
Ameba x 1, Arduino UNO x 1
Steps
I2C is a very common module on microcontrollers, it only takes 2 wire and able to achieve data rate at up to 3.4Mbps. It works in master-slave model and a master can simultaneously connect to up to 128 slaves, making it a very versatile communication protocol between microcontroller and sensor. Here we are going to use Ameba as an I2C master and Arduino UNO as a slave to achieve I2C send and recv. Before connection, make sure to upload the “Examples -> Wire -> Slave_receiver” example code to Arduino UNO. Connection is shown as follows, here we are using PA_26 as SDA pin and PA_25 as SCL. Note: There is currently 1 set of I2C available to MicroPython user, they are
Then copy and paste the following code line by line into REPL to see their effects.
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 fade
Materials
Ameba x 1, LED x 1, Resistor(220ohm) x 1
Steps
PWM use pulse width modulation to control output duty cycle and is widely used to control LED brightness and motor. Here we are using an LED to demonstrate how PWM works.
Let us connect pin PA_26 to the anode leg of an LED which in series with a current limiting resistor and GND to cathode of the LED as shown below,
Then, copy and paste the following code line by line into REPL and hit Enter. If everything is in order, you should be able to see the LED slowly become brighter as you paste another line of code.
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 -Get time
Materials
Ameba x 1
Steps
RTC module help microcontroller to keep track of time and is essential to our time module. Here we an example to demonstrate how to get local time and update the time.
Copy and paste the following code line by line into REPL to see its effect.
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 Server and Client
Materials
Ameba x 2
Steps
After WiFi is set up, the best way to access the internet is to use socket. Socket is like an imaginary ethernet socket by which you use to connect your PC to some server on the internet like Google or Github.
Application layer protocol like HTTP are also built on top of socket. Once you are given an IP address and a port number, you can start to connect to the remote device and talk to it.
Here is an example of letting a server socket and a client socket to echo each other’s message, to use this example, you need 2 ameba RTL8722 running MicroPython, copy and paste the following code to 2 ameba respectively under REPL paste mode.
This is the server code,
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")
This is the client code,
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 - Get information from HTTP website
Materials
Ameba x 1
Steps
With socket created, we can visit an HTTP website and get information from it. Copy and paste the following code into REPL under paste mode.
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 - Slave Receive
Materials
Ameba x 1, Arduino UNO x 1
Steps
SPI is a fast and robust communication protocol that are commonly found on many microcontrollers and is often used to retrieve sensor data or output image signal to a display. Ameba support SPI in both master and slave mode. Here we are going to see an example demonstrating how ameba receive data in slave mode on MicroPython.
Before connection, make sure to upload the following code to your Arduino UNO.
1rtc = RTC()
2///////////////////////
3// SPI Master Write //
4///////////////////////
5#include
6void setup (void) {
7 Serial.begin(115200); //set baud rate to 115200 for usart
8 digitalWrite(SS, HIGH); // disable Slave Select
9 SPI.begin ();
10}
11void loop (void) {
12 char c;
13 digitalWrite(SS, LOW); // enable Slave Select
14 // send test string
15 for (const char * p = "Hello, world!\r" ; c = *p; p++) {
16 SPI.transfer(c);
17 Serial.print(c);
18 }
19 Serial.println();
20 digitalWrite(SS, HIGH); // disable Slave Select
21 delay(2000);
22}
Connection is shown as follows, here we are using unit 0 as SPI slave, and Arduino UNO as SPI master,
Then copy and paste the following code into REPL under paste mode to see their effects.
1from machine import SPI
2s1= SPI(0 , mode = SPI.SLAVE)
3for i in range(14):
4chr(s1.read())
[RTL8722CSM] [RTL8722DM] Time - Delay and Timing
Materials
Ameba x 1
Steps
MicroPython has provided rich functions to deal with time and delay, here are some examples.
Copy and paste the following code line by line into REPL to see its effect.
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 -Periodical timer
Materials
Ameba x 1
Steps
There are 3 sets of general timers available to user, each at 32KHz, they are timer 1/2/3. Here we use timer 1 as example to demonstrate how a periodical timer works.
Copy and paste the first 3 lines of code into REPL to see its effect.
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()
A text of “–timer triggered. to stop: type t.stop()–” will be printed on the terminal every 2 seconds.To stop the timer, simply type t.stop().
[RTL8722CSM] [RTL8722DM] UART - Send and Receive
Materials
Ameba x 1, TTL USB to Serial module x 1
Steps
UART is a very versatile communication protocol and almost an essential part of a microcontroller. A TTL USB to Serial module is an IC that helps to translate UART signal to USB signal so that we can see uart log printed on our PC. This module is often found on many development boards, including ameba. However, the module on Ameba is reserved for LOG UART and Firmware uploading, that is why we need a separate module to communicate between ameba and PC.
There are currently 2 sets of UART available to MicroPython users and they are,
Then, copy and paste the following code line by line into REPL to see its effect.
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
[RTL8722CSM] [RTL8722DM] WiFi - WiFi Connect
Materials
Ameba x 1
Steps
Ameba can connect to WiFi access point with open security or WPA2 security type, which is the most common security type used in household wireless routers. Here we are going to connect to a WiFi access point using code below, copy and paste the following code line by line into REPL to see their effects.
1from wireless import WLAN
2wifi = WLAN(mode = WLAN.STA)
3wifi.connect(ssid = "YourWiFiName", pswd = "YourWiFiPassword")
[RTL8722CSM] [RTL8722DM] WiFi - WiFi Scan
Materials
Ameba x 1
Steps
WiFi Scan function can help us quickly discover what WiFi networks are available in our surrounding. This example does not require any additional hardware, thus simply copy, and paste the following code into REPL to see its effect.
1from wireless import WLAN
2wifi = WLAN(mode = WLAN.STA)
3wifi.scan()
Peripheral_SDFS_file_manipulation
Examples
SDFS File Manipulation
Materials:
Ameba x 1
MicroSD Card x 1
Steps:
SD File System is supported on MicroPython RTL8722 port through importing the ```sdfs``` module. This module is a simplified file system with the aim to highlight SD card manipulation, thus it does not support virtual file system as well as virtual file object.
Copy and paste the following code line by line into REPL to see its effect.
Note: No file open or close is needed, the API does that automatically for you.
Board HDK
API Documents
Online API Documents
ADC
Constructors
ADC(unit[required])
Create an ADC object associated with the given unit ID. This allows you to then read analog values on the pin assigned to the unit ID.
unit: unit number is tied to a specific pin. Refer to table below for more information,
Unit |
Pin |
---|---|
0 |
PB_4 |
1 |
PB_5 |
2 |
PB_6 |
3 |
PB_7 |
4 |
PB_1 |
5 |
PB_2 |
6 |
PB_3 |
Methods
ADC.read()
Read the value on the analog pin and return it.
I2C
Constructors
I2C(unit_id[optional], “sda_pin”[required], “scl_pin”[required], frequency[optional])
Create a I2C object associated with the given pin name and configure it using other parameters. This allows you to then read/write data on the I2C bus.
unit_id: The unit ID of the hardware I2C, assume default value if left blank
“sda_pin”: The pin name of SDA
“scl_pin”: The pin name of SCL
frequency: The frequency at which I2C operates at, assume default value if left blank.
Note: All optional parameters have default values as follows,
Parameter |
Default |
---|---|
Unit_id |
0 |
Frequency |
100000 (Hz) |
Methods
I2C.reset()
This method de-initializes the I2C device.
I2C.scan()
This method scans and return the available I2C addresses.
I2C.readinto( buf[required], flag[optional])
This method reads the data received at I2C buffer into a user-declared buffer
buf: a buffer of string / array /byte array type
flag: a Boolean flag, if True then send a NACK at the end, vice versa
I2C.write(buf[required])
This method sends data stored in the buffer.
buf: a buffer of string / array /byte array type
I2C.readfrom(addr[required], len[required], stop[optional])
This method reads len bytes of data from given address, if stop is True, then send a STOP bit at the end of the transmission.
addr: the address to read from
len: the number of bytes to expect
stop: a Boolean flag whether or not to send a STOP bit at the end of transmission
I2C.readfrom_into(addr[required], buf[required], stop[optional])
This method reads data from given address into the user-declared buffer provided, if stop is True, then send a STOP bit at the end of the transmission.
addr: the address to read from
buf: a data buffer of string / array/ byte array type
stop: a Boolean flag, if True then send a STOP bit at the end of transmission, vice versa
I2C.writeto(addr[required], value[required], stop[optional])
This method sends an integer value to the given address, if stop is True, then send a STOP bit at the end of the transmission.
addr: the address to write to
value: an integer value to be sent over
stop: a Boolean flag, if True then send a STOP bit at the end of transmission, vice versa
Pin
Constructors
Pin(「pin_name」[required], direction[required], pull_mode[optional], value[optional])
Create a Pin object associated with the given gpio pin name and configure it using other parameters. This allows you to then read/write digital values on the pin.
「pin_name」: The name of the pin, must be in string format, use help(Pin.board) to check all pin names
direction:
Pin.IN – for input
Pin.OUT - for output
pull_mode:
Pin.PULL_NONE – no pull-up or down resistor
Pin.PULL_UP – enable pull-up resistor
Pin.PULL_DOWN – enable pull-down resistor
default value – Pin.PULL_NONE
value: Initial value, only applicable to OUTPUT, for example value = 1. Default value 0.
Methods
Pin.id()
This method will return the associated GPIO pin name after declaring a Pin object.
Pin.init(「pin_name」[required], direction[required], pull_mode[optional], value[optional])
Identical function as the Constructor, it creates and initializes a Pin object using parameter typed in.
Pin.value(number[optional])
This method can be used in 2 ways,
Output number keyed in
number can only be either 0 or 1 , indicating logic 0 or logic 1
Check the status of the pin
When left blank, this method will check the status (logic 0 /1) of the Pin, regardless of which direction this Pin is configured as.
Pin.on()
This method sends a logic 1 signal to the associated pin
Pin.off()
This method sends a logic 0 signal to the associated pin
Pin.toggle()
This method toggles the logic signal of the associated pin
PWM
Constructors
PWM(unit[optional], “pin_name”[required])
Create a PWM object associated with the given pin name. This allows you to then write PWM signal on the pin.
unit: unit ID of the hardware PWM, will use default unit 0 if leave blank
「pin_name」: The name of the pin, must be in string format. See below for PWM supported pins.
Note:
PWM is currently only supported on the following pins,
PA_23, PA_24, PA_25, PA_26
Methods
PWM.write(dutycycle_float[required])
This method will output a PWM signal with given duty cycle on the associated GPIO pin.
dutycycle_float: a floating point duty cycle value, can be from 0.0 (0%) to 1.0 (100%)
RTC
Constructors
RTC()
Create a RTC object.
Methods
RTC.datetime(array_8[optional])
This method works in 2 ways
Return the local date and time if NOT passing any argument into it. The returned format is as follows,
(year, month, date, hour, minute, second, weekday[0-6 for Mon to Sun], yearday[1-366])
Update the local date and time if passing an eight-elements array into it, the array format is same as above
SPI
Constructors
SPI(unit_id[required], baudrate[optional], polarity[optional], phase[optional], databits[optional], firstbit[optional], miso[optional], mosi[optional], sck[optional], mode[optional])
Create a SPI object and configure it using other parameters. This allows you to then read/write data on the SPI bus.
unit_id: The unit ID of the hardware SPI, assume default value if left blank
baudrate: The speed of SPI
polarity: one of factor determining SPI mode. (deprecated)
phase: one of factor determining SPI mode. (deprecated)
databits: number of data bits
Firstbit: this determine whether first bit is MSB or LSB
miso: miso pin. (deprecated)
mosi: mosi pin. (deprecated)
sck: clock pin. (deprecated)
mode: either MASTER mode or SLAVE mode
Note: All optional parameters have default values as follows,
Parameter |
Default |
---|---|
Baudrate |
2000000 Hz |
Polarity |
Inactive_low |
Phase |
Toggle_middle |
Databits |
8 |
Firstbit |
MSB |
Miso |
N.A. |
Mosi |
N.A. |
Sck |
N.A. |
Mode |
MASTER |
There is currently 2 set of SPI, they are,
unit |
MOSI |
MISO |
SCK |
CS |
---|---|---|---|---|
0 |
PB_18 |
PB_19 |
PB_20 |
PB_21 |
1 |
PB_4 |
PB_5 |
PB_6 |
PB_7 |
Note: both unit support master mode, but only unit 0 supports slave mode.
Methods
SPI.read()
This method waits and read data received in SPI buffer, then return the data received. Works in both master and slave mode.
SPI.write( value[required])
This method writes an integer value to SPI bus. Works in both master and slave mode.
value: an integer value to be sent on SPI bus
time
Constructors
N.A.
Methods
time.sleep(seconds[required])
This method will stop the microcontroller from what it is doing and delay for the given time.
seconds: number of seconds, must be an integer
time.sleep_ms(milliseconds[required])
This method will stop the microcontroller from what it is doing and delay for the given time.
milliseconds: number of milliseconds, must be an integer
time.sleep_us(microseconds[required])
This method will stop the microcontroller from what it is doing and delay for the given time.
microseconds: number of microseconds, must be an integer
time.time()
This method will return the total number of seconds elapsed since Epoch (1970-01-01).
time.localtime()
This method will return RTC’s local time in the following format,
(year, month, date, hour, minute, second, weekday[0-6 for Mon to Sun], yearday[1-366])
time.mktime(tuple[required])
This is inverse function of localtime. Its argument is a full 8-tuple which expresses a time as per localtime. It returns an integer which is the number of seconds since Jan 1, 2000.
tuple: an 8-element tuple
time.ticks_ms()
This method returns an increasing millisecond counter with an arbitrary reference point. Normally used together with ticks_add() and ticks_diff()
time.ticks_add(starting_ticks[required], ticks_added[required])
This method add given number of ticks to the starting_ticks.
starting_ticks: millisecond counter obtained from ticks_ms()
ticks_added: number of ticks to add
time.ticks_diff(end_ticks[required], starting_ticks[required])
This method perform subtraction on parameters given and return the difference of end_ticks minus starting_ticks.
end_ticks: millisecond counter obtained from ticks_ms()
starting_ticks: millisecond counter obtained from ticks_ms()
Timer
Constructors
Timer(unit[optional])
Create a timer object with given unit ID.
unit: can be 1 / 2 / 3 for timer 1 / 2 / 3
Methods
Timer.start(microseconds[required], type[required])
This method will start a given type of timer, either one-shot or periodical, at duration of given microseconds.
microseconds: number of microseconds interval, must be an integer
type: either Timer. PERIODICAL or Timer.ONESHOT
Timer.deinit()
This method will de-initialize the Timer object created and stop the timer.
Timer.stop()
This method will stop the timer and its timer interrupt handler.
Timer.us ()
This method will return the current timer tick in microsecond.
Timer.tick ()
This method will return the current timer tick in Gtimer clock(0~32768).
Timer.reload (duration_us[required])
This method will reload the timer with given duration in microsecond.
duration_us: duration in microsecond
UART
Constructors
UART(unit[optional], baudrate[optional], databits[optional], stopbit[optional], paritybit[optional], timeout[optional], tx_pin[required], rx_pin[required])
Create a UART object associated with the given tx and rx pins and configure it using other parameters. This allows you to then read/write uart signal on the pins.
unit: The unit ID, either 0 or 3
baudrate: 115200 is the recommended baudrate on ameba
databits: the number of bits for data bits, usually 7 or 8 bits
stopbits: the number of stop bits, usually 1 or 1.5 or 2 bits
paritybit: for parity check, usually none, odd or even
timeout: how long uart wait before its timeout (in milliseconds)
tx_pin: the transmitter pin, connect the rx pin of the receiver
rx_pin: the receiver pin, connect to tx pin of the transmitter
Note: Not all parameters are required, thus MicroPython will assume its default value once left blank, here are the default values for each optional parameter,
Parameter |
Default Value |
---|---|
Unit |
0 |
Baudrate |
115200 |
Databits |
8 |
Stopbits |
1 |
Paritybit |
0 |
Timeout |
10 (ms) |
Methods
UART.init()
This method initializes and configures the UART.
UART.read(length[optional])
This method reads the data received in UART buffer.
length: the length of the data to receive
UART.readline()
This method is similar to read(), but read a line ending with a newline character.
UART.write(buffer[require])
This method sends the buffer of bytes to the bus and returns the number of bytes written.
buffer: data buffer that can be a string, an integer or other data types
UART.irq_enable(bool[optional])
This method works in 2 way:
Check the status of uart irq when NOT passing any argument, and it will return True if irq is enabled, False if disabled
Enable/disable uart irq handler by passing True or False as bool
UART.irq_handler(function[required])
Passing the python handler to uart irq so that it will be triggered when an UART event occurs.
function: a function defined in python or a lambda function
WiFi
Constructors
WLAN(mode[required])
Create a WLAN object and configure it to the given mode. This then allows you to control WiFi and check its status.
mode: use WLAN.STA for station mode
Methods
WLAN.scan()
This method scan and list out all available WiFi network in the surroundings.
WLAN.connect(ssid[required], pswd[optional], security[optional])
This method attempts to establish a connection to a WiFi access point.
ssid: The name of your WiFi network
pswd: The password of your WiFi network
security: The security type of your WiFi network
Leaving optional parameters blank will assume taking default values which are
Parameter |
Default value |
---|---|
pswd |
NULL |
security |
WPA2_AES_PSK |
Note: Connecting to an OPEN network is also supported, just omit 『pswd』 parameter and type in 「security = WLAN.OPEN」 followed by ssid.
WLAN.get_ip()
This method returns the IP address of the current WLAN interface. Only works after successful connection to an AP.
WLAN.disconnect()
This method disconnect ameba from current WiFi AP, but still keep WiFi module on.
WLAN.on()
This method turns on the WiFi device.
WLAN.off()
This method shut down WiFi device and suspend all connections.
WLAN.wifi_is_running()
This method returns the WiFi status. True when WiFi is on, and False when off.
WLAN.is_connect_to_ap()
This method returns the connection status. True if ameba is connected to an AP, False if ameba is not connected to anything.
Socket
Constructors
socket.SOCK(domain[optional], type[optional])
Create a SOCK object and configure it with the given parameters. SOCK class is under socket class and is the main class we use for all socket level communications.
domain: domain address family type. Default is AF_INET
AF_INET: IPv4, classic IP address with dot-notation that is slowly being replaced by IPv6 due to shortage.
AF_INET6: IPv6, IP address with colon-notation
type: socket type, default is SOCK_STREAM
SOCK_STREAM: TCP type
SOCK_DGRAM: UDP type
Methods
socket.SOCK.connect(host[required], port[required])
This method connects to a remote server as client.
host: a website address in string
port: port number in integer
socket.SOCK.bind(port[required])
This method creates a server socket and binds it to the given port number.
port: port number in integer
socket.SOCK.listen()
This method set the server to listening state, waiting for client connection at the given port.
socket.SOCK.accept()
This method accepts a client connection and return a new socket object for subsequent communication and client’s address.
socket.SOCK.recv(length[required])
This method receive data with given length
length: the length of data expected to receive
socket.SOCK.send(buffer[required])
This method sends data stored in the buffer
buffer: a data buffer in format of array/bytearray/string
socket.SOCK.settimeout(seconds[required])
This method set socket’s timeout to the given value
seconds: new timeout in seconds
socket.SOCK.close()
This method close the socket.
class sdfs – SD File System
Constructors
sdfs
Create a 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.
Methods
sdfs.listdir()
This method listing the files and folders under current path.
sdfs.mkdir(「folder name[required]」)
This method attempts to create a folder under current path.
sdfs.chdir(「folder name[required]」)
This method change directory to a folder.
sdfs.pwd()
This method is to print out present working directory (current path).
sdfs.chdir(「/」)
This method is to change directory path to root directory.
sdfs.rm(「folder name[required]」)
This method is to delete a folder.
sdfs.create(「file name[required]」)
This method is to create a file.
sdfs.write(「file name[required]」)
This method is to write a string to a file.
sdfs.read(「file name[required]」)
This method is to read the content from a file.
sdfs.rm(「file name[required]」)
This method is to delete the file.
Resources
Links
Support
FAQ
What is MicroPython and how to use it?
Please refer to MicroPython official website for more information.
Can I use all Python libraries available online?
No, MicroPython only support a small section of the classic Python standard library. However, this can be done by porting the classic python library to MicroPython.
Are all pins on RTL8722CSM/RTL8722DM usable?
No, those marked “NC” are not connected to any pin and thus unusable.
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
Compilation of MicroPython firmware failed
During the building process, some user may encounter error that suspend the process, this is due to missing system environment setup and can be fixed as follows,
1. Error related to python By default, MicroPython use python3 to run building scripts for the MicroPython kernals, if you encounter error related to python, it may be because the path of the Python3 executable is not added to system environment variable.
However, if environment variable is already added but the build could not be completed, you may try,
Re-start your PC
2) type “python” on your terminal, if the python shown is python3, then please add PYTHON = python to the second line of the “Makefile” under “port/rtl8722” folder
2. Error related to MPY-CROSS If building process stop when mpy-cross shown as error, there is a step to be done as follows,
navigate to “MicroPython_RTL8722/mpy-cross” folder
2) Open your Cygwin/Linux terminal and just type make Wait for make finish building the MicroPython Cross Compiler, then this should fix the error
My code is not behaving as I expected
Try to debug your program using print( ) function and learn more about each API used through the API page.
Why am I constantly getting “syntax error” from REPL?
Please note that MicroPython only support Python 3 syntax.
How to upload my python script into Ameba?
There are 3 ways of uploading your python code into Ameba,
1. via REPL normal mode In the normal REPL mode, you can paste your into REPL code line by line and have them executed sequentially, but note that syntax will be automatically indented when using condition checking or loop, like “if” or “while”, incorrect indenting will crash your input script
2. via REPL paste mode When in normal REPL mode, press “Ctrl”+ “e” will enter paste mode, paste mode only allow pasting a large chunk of a complete code, incomplete code or editing after pasting will mess up your syntax and cause error
3. via mp_frozenmodules By placing your python script into the “mp_frozenmodules” folder under “rtl8722” folder, your code will be embedded into the MicroPython firmware and uploaded to Ameba, after that you can use it by simply importing the name of your python script. If you get syntax error using this method, you better check your python code syntax again.
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.
Standard SDK
This is the Ameba Standard SDK online documentation
Ameba RTL8722DM (AMB 21)
入門指南
GCC 開發環境的設置
在 Windows 上,可以將 Cygwin 用作 GCC 開發環境。 Cygwin 是 GNU 和開源工具的集合,類似於提供 Linux 相關的功能在 Windows 平台上使用。 點選 http://cygwin.com/ 且依照自己的 Windows 平台來下載 Cygwin package setup-x86.exe 。 1. 32位元 Windows 和64位元 Windows 均支持32位元 Cygwin。 2. 安裝 Cygwin package 過程中, 如下圖所示在 Select Packages 頁面中選擇 ‘Devel -> make’ 與 ‘Math -> bc’ 功能。
對於 Linux,請參考 AN0400 Ameba-D Application Note v12.pdf 來建立GCC開發環境。
Ameba-D 開發板的相關介紹
對於 Ameba-D,有許多類型的芯片組可用,例如 RTL8720CS,RTL8721CSM,RTL8722CSM,RTL8720DN,RTL8720DM,RTL8721DM 和 RTL8722DM。 此外,芯片組可以嵌入在 Ameba-D DEV 開發板上且擴展各種 I/O 接口。我們提供了相應的 HDK(硬件開發套件)文檔,請聯繫 RTK 了解更多詳細信息。 Ameba-D 開發板的硬件圖如下所示。 USB TO UART: 供電和日誌打印。 baud rate 為 115200bps。 SWD: SWD 介面,用於下載圖像和使用 IAR 進行調試。 Reset button: IAR 完成下載後,重置 Ameba-D 以運行固件。
連接串口
在 Ameba-D 板上,FTDI 芯片和 FT232 可用於串口和除錯器。 可以使用SecureCRT、Teraterm與Putty等終端工具查看串口訊息。 1) 選擇相對應的uart參數且打開連接端口。 2) 然後按 Ameba 上的重置按鈕,在終端中可以找到一些訊息。
在 Ameba-D 上建立第一個 GCC 項目
以下步驟供首次開發人員在現有 RTK SDK 下構建GCC項目。
Building Code 本節說明如何構建SDK。 首先,您需要切換到 GCC目錄。 對於Windows,打開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)上相應目錄下使用$ make all命令。 KM0 project 對於 KM0,如果終端輸出訊息包含 “km0_image2_all.bin” 和 “Image manipulating end”,則表示固件已成功構建,如下所示。
如果構建失敗,請輸入$ make clean 然後重新執行 make。 成功構建後,固件檔案位於project / realtek_amebaD_va0_example / GCC-RELEASE / project_lp / asdk / image 下,如下圖所示。
KM4 project 對於 KM4,如果終端輸出訊息包含 “km0_image2_all.bin” 和 “Image manipulating end”,則表示固件已成功構建,如下所示。
如果構建失敗,請輸入$ make clean 然後重新執行 make。 成功構建後,固件檔案位於project / realtek_amebaD_va0_example / GCC-RELEASE / project_hp / asdk / image 下,如下圖所示。
下載固件至 Ameba-D Realtek 提供了 image tool 在 windows 中可以方便下載固件 * 環境需求: WinXP, Win 7 以上, Microsoft .NET Framework 3.5 * ImageTool.exe 位置: SDKtoolsAmebaDImage_ToolImageTool.exe
假設 PC 上的 ImageTool 是服務器,它將通過 UART 將固件檔案發送到 Ameba(客戶端)。 要將檔案從服務器下載到客戶端,客戶端必須首先進入 uart download 模式。
進入 UART_DOWNLOAD 模式
按下 UART DOWNLOAD 按鈕並保持按下狀態。
重新打開電源,或按重置按鈕。
放開 UART DOWNLOAD 按鈕。
現在Ameba 板 進入 UART_DOWNLOAD 模式並準備接收數據。
點選 UI上 的 Chip Select(紅色),然後選擇芯片(AmebaD 或 AmebaZ)。
選擇相應的串行端口和傳輸 baudrate。 默認 baudrate 是 1.5Mbps(推薦)。
點選瀏覽按鈕以選擇要編程的固件(km0_boot_all.bin / km4_boot_all.bin / km0_km4_image2.bin)與其位址。
固件位址為 {path}projectrealtek_amebaD_va0_exampleGCC-RELEASEproject_hpasdkimage 與 {path}projectrealtek_amebaD_va0_exampleGCC-RELEASEproject_hpasdkimage。 {path} 為自己電腦上項目的位址。
默認目標地址是SDK默認固件地址,您可以直接使用它。
點選下載按鈕 進度條將顯示每個固件的傳輸進度並且可以從日誌窗口獲取操作成功消息或錯誤消息。
Download
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
Board HDK
Support
FAQ
如何購買 Ameba RTL8722DM Board?
請參考 購買連結。
Trouble shooting
遇到開發板連接到電腦的驅動程式問題?
請參考下列USB驅動程式 https://ftdichip.com/drivers/。