char toUpper(char c) { if (c >= ‘a’ && c <= ‘z’) return c – 0x20; else return c; } char input; void loop() { if (Serial.available() > 0) { input = Serial.read(); if (input != -1) Serial.print(toUpper(input)); else Serial.println(); } } Rewrite the toUpper() function to take a pointer to a character as a parameter and make whatever other changes are required in the rest of the program. (4)
The Correct Answer and Explanation is:
Here is the modified version of your program with the toUpper function rewritten to take a pointer to a character as a parameter. The changes reflect this new approach, and I’ll explain how the code works afterward.
Modified Code:
tvoid toUpper(char* c) {
if (*c >= 'a' && *c <= 'z') {
*c = *c - 0x20; // Convert to uppercase
}
}
char input;
void loop() {
if (Serial.available() > 0) {
input = Serial.read();
if (input != -1) {
toUpper(&input); // Pass the address of input to the function
Serial.print(input);
} else {
Serial.println();
}
}
}
Explanation:
- Function Signature Change:
In the originaltoUpperfunction, acharwas passed by value, meaning any modifications made to the variable inside the function wouldn’t affect the original character inloop(). By changing the function to accept achar*(pointer tochar), we now modify the original character passed to the function. - Dereferencing the Pointer:
Inside thetoUpperfunction, we use*cto dereference the pointer and access the actual character that the pointer refers to. This allows us to modify the original character directly. The conditionif (*c >= 'a' && *c <= 'z')checks if the character is a lowercase letter. If it is, we convert it to uppercase by subtracting0x20(which is the difference between the ASCII values of lowercase and uppercase letters). - Calling
toUpperinloop():
In theloop()function, we pass the address of theinputvariable using&input. This allows thetoUpperfunction to work directly with the memory location ofinput, changing it in place. After the function call, the updated value ofinput(now potentially in uppercase) is printed. - Other Adjustments:
No other major changes were needed in the rest of the code. The logic to check if data is available on the serial port and to print the result remains the same. We just updated the function call to handle a pointer rather than a direct value.
Key Takeaways:
- Pointers allow you to modify data directly by accessing its memory location.
- By passing a pointer to a character, we are now able to change the character inside the
toUpperfunction, and the change is reflected in the calling function (loop()).
