Homework Code

This is just a list of possible programs to solve the coding homework problems. There area usually other correct ways to solve the assignments but these are simple ones that work.

NOTE that I am not showing the includes and header comments. Those must always be present but I trust that you know that part by now.

H3 Prob. 12.

Write a computer program that sits reading characters from the serial port and echoing them back in the opposite case. That is, if the user types 'a' then the program should send back 'A', if the user types 'Q', the program should send back 'q', etc.

Solution

void main(void) {
	//
	//	Declare any variables that you use here.
	//
	char theChar;
	//
	//	Do any one-time setup here
	//
	Serial_begin(9600);
	printf("Enter the text to convert\r\n");
	//
	//	Code runs in an endless loop
	//
	for (;;) {
		theChar = getchar();
		if (('A' <= theChar) && ('Z' >= theChar)) {
			//
			// Found an upper case letter. Print as lower case.
			//
			putchar(theChar + 0x20);
		} else if (('a' <= theChar) && ('z' >= theChar)) {
			//
			// Found a lower case letter. Print as upper case.
			//
			putchar(theChar - 0x20);
		} else {
			//
			// Otherwise should print what they typed.
			//
			putchar(theChar);
		}
	} // end for
} // end main

H4 Prob. 12.

Write a program that sits reading +ve integers from the serial port. It should stop when a zero is entered and then it should print the largest and smallest values that were entered (excluding the zero). Obviously it will then go back and ask for more input numbers and start over again.

Thus the interaction should look something like this

Enter numbers (-ve to end)
23
46
103
27
5
0
The largest value was 103 and the smallest was 5.
Enter numbers....

Solution

void main(void) {
//
// Declare variables here
//
	unsigned int cVal;		// The current value
	unsigned int minVal;  	// The lowest value found.
	unsigned int maxVal;  	// The highest value found
	//
	// Put any setup code here.
	//
	Serial_begin(9600);
	//
	// Main code runs in an infinite loop
	//
	for (;;) {
		printf(“Enter numbers (-ve to end)\r\n\”);
		minVal = 65535; // init with largest number so any value is smaller
		maxVal = 0; 	// and this is started from the smallest
		for (;;) {
			cVal = GetWord();
			if (cVal == 0) {
				break;
			}
			if (cVal < minVal) { // See if we need to update the minimum
				minVal = cVal;
			}
			if (cVal > maxVal) { // See if we need to update the maximum
				maxVal = cVal;
			}
		}
		//
		// Get here only when they entered a negative. Print results.
		//
		printf(“The largest values was %d and the smallest %d.\r\n”, maxVal, minVal);
	} // Never exit this for loop
}

Physics 245