Hardware Reference
In-Depth Information
45 // Print data to the serial port, and to the file
46 Serial.println(dataString);
47 dataFile.println(dataString);
48
49 // Close the file
50 dataFile.close();
51 }
52
53 // Increase the iteration number
54 iteration++;
55
56 // Sleep for one minute
57 delay(60 * 1000);
58 }
The sketch begins by importing the SD library and the SPI library. Three
variables and one constant are dei ned. The chipSelect constant should refer
to the pin that acts as the CS pin for the SD card on your board. On the Ethernet
board specii ed at the beginning of this chapter, the SD card is connected to pin
4. Refer to the documentation of your shield if you're unsure. This is the pin
that will be used to talk to the SD card. The light variable will hold the sensor
value from the LDR. The lightPin is the pin on which these readings will take
place. Finally, the iteration variable will show the number of readings; it will
be used to format your data in a spreadsheet.
setup() begins with coni guring the serial port for debugging, something you
are probably used to by now. On line 14, a status message is sent serially from
the Arduino, telling the user that the SD card is about to be initialized. The SD
card initialization is done on line 19, but before that, on line 16, the Arduino's
default Chip Select pin (digital pin 10) is set as an output. This is required for
the SD library to work, even if the pin is not connected to your card. The SD
library will fail without this.
The SD card is initialized on line 19, by using the pin previously dei ned in the
chipSelect constant. If the SD card fails to initialize, but your card is correctly
formatted in FAT32, check to see if you are using the right pin number for your
board. If the initialization fails, the sketch will inform the user; otherwise a
message will be printed to the serial port informing that everything went well.
loop() starts on line 27. First, the sketch reads the value on the lightPin and
stores it in the light variable. When this data has been read in, it is time to open
the SD i le. This is done on line 33; the sketch calls the i le called light.txt .
If this i le exists, it will be opened; otherwise, the i le will be created. Because
the sketch uses the FILE_WRITE parameter, it will be opened for reading and
writing. The sketch then checks if the i le has been opened on line 36. If it is
open, a String is created, and populated with data: the iteration variable and
the light variable, separated by a comma. On line 46, this string is printed to
the serial port, and then, using SD . println() , appended to the data i le. After
this has been done, the i le is closed, and all the data is l ushed to the SD card.
Search WWH ::




Custom Search