Check if a character is printable in Arduino

ArduinoArduino BoardsArduino IDEArduino Programming Language

Through various operations, you may come across characters which are not printable. After all, a char is an 8-bit number, and if you look at the ASCII table (https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html), only the values from 32 to 127, or a total of 96 values out of 127 are printable (see http://facweb.cs.depaul.edu/sjost/it212/documents/ascii-pr.htm).  ASCII uses only 7 digits, instead of 8.

Thus, if you get a char output from a function, and wish to check if it is printable, then you can use the isPrintable() function of Arduino.

Syntax

isPrintable(myChar)

where myChar is the character being checked. This function returns a true if the character is printable.

Example

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
   Serial.println();
   char c1 = 'a';
   char c2 = 6;
   char c3 = 56;

   if (isPrintable(c1)) {
      Serial.println("c1 is printable!");
   } else {
      Serial.println("c1 is not printable!");
   }

   if (isPrintable(c2)) {
      Serial.println("c2 is printable!");
   } else {
      Serial.println("c2 is not printable!");
   }

   if (isPrintable(c3)) {
      Serial.println("c3 is printable!");
   } else {
      Serial.println("c3 is not printable!");
   }
}

void loop() {
   // put your main code here, to run repeatedly:
}

Output

The Serial Monitor output is shown below −

As you can see, the character c2, which corresponds to the ASCII equivalent of number 6, is not printable. You can check from the ASCII table that it corresponds to ACK. Similarly, 56 corresponds to the character representation of number 8. Thus, it is printable.

raja
Published on 31-May-2021 14:26:39
Advertisements