]> git.piffa.net Git - sketchbook_andrea/blob - programming/leap_year_functions/leap_year_functions.ino
Common esempi
[sketchbook_andrea] / programming / leap_year_functions / leap_year_functions.ino
1 /**
2  * Program: find out is the user typed in a leap year. The code assumes
3  * the user is not an idiot and only types in numbers that are a valid
4  * year.
5  * Author: Dr. Purdum, Aug. 7, 2012
6  **/
7 void setup()
8 {
9   Serial.begin(9600);
10 }
11 void loop()
12 {
13   if (Serial.available() > 0) {
14     int bufferCount;
15     int year;
16     char myData[20];
17     bufferCount = ReadLine(myData);
18     year = atoi(myData);
19     Serial.print("Year: ");
20     Serial.print(year);
21     if (IsLeapYear(year)) {
22       Serial.print(" is ");
23     } 
24     else {
25       Serial.print(" is not ");
26     }
27     Serial.println("a leap year");
28   }
29 }
30 // Convert to int
31 /*****
32  * Purpose: Determine if a given year is a leap year
33  * Parameters:
34  * int yr               
35  * The year to test
36  * Return value:
37  * int          
38  * 1 if the year is a leap year, 0 otherwise
39  *****/
40 int IsLeapYear(int yr)
41 {
42   if (yr % 4 == 0 && yr % 100 != 0 || yr % 400 == 0) {
43     return 1;    // It is a leap year
44   } 
45   else {
46     return 0;   
47     // not a leap year
48   }
49 }
50 /*****
51  * Purpose: Read data from serial port until a newline character is read ('\n')
52  * Parameters:
53  * char str[]
54  * character array that will be treated as a nul-terminated string
55  * Return value:
56  * int
57  * the number of characters read for the string
58  * CAUTION: This method will sit here forever if no input is read from the serial
59  * port and no newline character is entered.
60  ****/
61 int ReadLine(char str[])
62 {
63   char c;
64   int index = 0;
65   while (true) {
66     if (Serial.available() > 0) {
67       c = Serial.read();
68       if (c != '\n') {
69         str[index++] = c;
70       } 
71       else {
72         str[index] = '\0'; // null termination character
73         break;
74       }
75     }
76   }
77   return index;
78 }
79
80