在Arduino中獲取ASCII表
在本文中,我們將逐步講解Arduino中的示例程式碼,該程式碼有助於在序列埠監視器輸出中生成ASCII表。供您參考,這就是ASCII表的樣子:http://www.asciitable.com/
它包含字元,後跟其十進位制、十六進位制的ASCII碼,有時甚至還有八進位制和二進位制表示。在這個例子中,我們將打印出所有可列印ASCII字元的這些表示。請記住,第一個可列印的ASCII字元從數字33開始,可列印字元一直到數字126。由於我們將在序列埠監視器上列印ASCII表,因此我們只關注可列印字元。
要訪問此示例,請轉到**檔案 → 示例 → 04 通訊 → ASCII 表**。

讓我們開始逐步講解這段程式碼。如您所見,我們首先在setup中初始化Serial,然後等待Serial埠連線。之後,我們只需列印草圖的標題。
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
}
// prints title with ending line break
Serial.println("ASCII Table ~ Character Map");
}接下來,定義全域性變數thisByte。它被初始化為33。記住33等於第一個可列印的ASCII字元。
int thisByte = 33;
在迴圈中,我們首先以字元的形式列印thisByte的值(使用Serial.write()),然後列印其十進位制值(使用Serial.print()),然後使用Serial.print()中的格式說明符列印其十六進位制、八進位制和二進位制表示。
之後,我們將thisByte的值遞增,直到達到126的值,之後進入無限迴圈,基本上什麼也不做。
示例
void loop() {
// prints value unaltered, i.e. the raw binary version of the byte.
// The Serial Monitor interprets all bytes as ASCII, so 33, the first number will show up as '!'
Serial.write(thisByte);
Serial.print(", dec: ");
// prints value as string as an ASCII-encoded decimal (base 10).
// Decimal is the default format for Serial.print() and Serial.println(),
// so no modifier is needed:
Serial.print(thisByte);
// But you can declare the modifier for decimal if you want to.
// this also works if you uncomment it:
// Serial.print(thisByte, DEC);
Serial.print(", hex: ");
// prints value as string in hexadecimal (base 16):
Serial.print(thisByte, HEX);
Serial.print(", oct: ");
// prints value as string in octal (base 8);
Serial.print(thisByte, OCT);
Serial.print(", bin: ");
// prints value as string in binary (base 2) also prints ending line break:
Serial.println(thisByte, BIN);
// if printed last visible character '~' or 126, stop:
if (thisByte == 126) { // you could also use if (thisByte == '~')
{
// This loop loops forever and does nothing
while (true) {
continue;
}
}
// go on to the next character
thisByte++;
}輸出
序列埠監視器輸出如下所示:

廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP