Serial.print()
往串口发数据,无换行
- 描述
以人类可读的ASCII码形式向串口发送数据,该函数有多种格式。整数的每一数位将以ASCII码形式发送。浮点数同样以ASCII码形式发送,默认保留小数点后两位。字节型数据将以单个字符形式发送。字符和字符串会以其相应的形式发送。例如:
Serial.print(78) 发送 "78" Serial.print(1.23456) 发送 "1.23" Serial.print('N') 发送 "N" Serial.print("Hello world.") 发送 "Hello world."
可选的第二个参数用于指定数据的格式。允许的值为:BIN (binary二进制), OCT (octal八进制), DEC (decimal十进制), HEX (hexadecimal十六进制)。对于浮点数,该参数指定小数点的位数。例如:
Serial.print(78, BIN) gives "1001110" Serial.print(78, OCT) gives "116" Serial.print(78, DEC) gives "78" Serial.print(78, HEX) gives "4E" Serial.println(1.23456, 0) gives "1" Serial.println(1.23456, 2) gives "1.23" Serial.println(1.23456, 4) gives "1.2346"
你可以用F()把待发送的字符串包装到flash存储器。例如:
Serial.print(F(“Hello World”))
要发送单个字节数据,请使用Serial.write()。
- 语法:
Serial.print(val) Serial.print(val, format)
- 参数:
val: 要发送的数据(任何数据类型)
format: 指定数字的基数(用于整型数)或者小数的位数(用于浮点数)。
- 返回值:<>
size_t (long): print()返回发送的字节数(可丢弃该返回值)。
- 示例:
/* Uses a FOR loop for data and prints a number in various formats. */ int x = 0; // variable void setup() { Serial.begin(9600); // open the serial port at 9600 bps: } void loop() { // print labels Serial.print("NO FORMAT"); // prints a label Serial.print("\t"); // prints a tab Serial.print("DEC"); Serial.print("\t"); Serial.print("HEX"); Serial.print("\t"); Serial.print("OCT"); Serial.print("\t"); Serial.print("BIN"); Serial.print("\t"); for(x=0; x< 64; x++){ // only part of the ASCII chart, change to suit // print it out in many formats: Serial.print(x); // print as an ASCII-encoded decimal - same as "DEC" Serial.print("\t"); // prints a tab Serial.print(x, DEC); // print as an ASCII-encoded decimal Serial.print("\t"); // prints a tab Serial.print(x, HEX); // print as an ASCII-encoded hexadecimal Serial.print("\t"); // prints a tab Serial.print(x, OCT); // print as an ASCII-encoded octal Serial.print("\t"); // prints a tab Serial.println(x, BIN); // print as an ASCII-encoded binary // then adds the carriage return with "println" delay(200); // delay 200 milliseconds } Serial.println(""); // prints another carriage return }