You are on page 1of 5

Covenant University

College of Engineering
GEC225 Exercises on Storage Classes and Scope 4

4.1 Extern in C

/* Listing */

#define MAXVAL 1000

void setup()
{
int x = 5;
Serial.begin(9600);
if (x < MAXVAL) {
int temp;

temp = x * 100;
Serial.print("The lvalue for temp is: ");
Serial.println((long) &temp);
Serial.print("The rvalue for temp is: ");
Serial.println((long) temp);
}
int temp;

Serial.print("The lvalue for 2nd temp is: ");


Serial.println((long) &temp);
Serial.print("The rvalue for temp is: ");
Serial.println((long) temp);
}

void loop() {}

GEC225-Applied Computer Programming - II | Hands-On Exercise No 4 1


4.2 Extern in C

/* Listing Using the static Storage Class. */


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

void loop() {
while (true) {
Serial.println(MyCounter());
}
}

int MyCounter()
{
static int counter = 0;
// do some stuff...
return ++counter;
}

GEC225-Applied Computer Programming - II | Hands-On Exercise No 4 2


4.3 Extern in C

extern int number;

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {
number *= number;
Serial.println(number);
}

4.4 Extern in C

_______________
/* Listing. Short Program with Error */

extern int number;

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {
number *= number;
Serial.println(number);
}

GEC225-Applied Computer Programming - II | Hands-On Exercise No 4 3


4.5 Extern in C

/* Extract variables from string */

void setup() {
char message[] = "70.0,95,15:00";

int index;
int holdIndex = 0;
int temperature;
int humidity;

Serial.begin(9600);

index = FindCharacter(message, ',');


if (index > 0) { // Found a comma
message[index] = '\0'; // Make it a string
temperature = atoi(message);
holdIndex += index + 1; // Look past the null for next pass
}
index = FindCharacter(message + holdIndex, ','); // Really passing message[5]
if (index > 0) { // Found a comma
message[index] = '\0'; // Make it a string
humidity = atoi(&message[holdIndex]);
holdIndex += index + 1;
}
Serial.print("The temperature is = ");
Serial.print(temperature);
Serial.print(" with humidity = ");
Serial.print(humidity);
Serial.print(" at ");
Serial.print(&message[holdIndex]);
}
void loop(){}

/*****
This method looks for a specific character in a string

GEC225-Applied Computer Programming - II | Hands-On Exercise No 4 4


Parameter list:
char msg[] an array of characters, null terminated
char c the char to find

return value:
int the position in the string where found or
0 if no match
*****/
int FindCharacter(char msg[], char c)
{
int i = 0;

while (msg) {
if (msg[i] == c) {
return i;
} else {
i++;
}
}
return 0;
}

GEC225-Applied Computer Programming - II | Hands-On Exercise No 4 5

You might also like