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