Rotate the letters received through the serial port

Zápisník experimentátora

Rotating letters by a specified number of letters is an undemanding task that is also suitable for the beginner. The original idea comes from Caesar's cipher where it rotates by 3 letters. Another modification is the ROT13 algorithm, where it rotates by 13 letters. In our example, we will rotate by one letter. We send the letters to the Arduino using the Serial Port Monitor.

The sketch

The algorithm is simple. We must only be careful about the end-of-line characters that we can not rotate. We'll send it back to the computer as we received them. We can rotate the other characters.

The algorithm can also be written simpler, because we know that the displayable characters begin with a space. Therefore, it would be enough to compare all the received characters with the space character and to rotate only those characters. For the sake of clarity, I chose an algorithm where the end-of-line characters are uniquely named to make it clear at first glance what we are trying to do.

int received;

void setup() {
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    received = Serial.read();
    switch (received) {
      case '\r':
      case '\n':
        Serial.write(received); // new line is not rotated, we want to see new line in Serial Monitor
        break;
      default:
        Serial.write(received + 1); // char rotate
        break;
    }
  }
}

Source code

The source code is located on the GitHub server.


06.03.2018


Menu