Hardware Reference
In-Depth Information
of the button, you cannot use a delay() function to wait 1000ms between each
update. Instead, you use the millis() function, which returns the number of
milliseconds since the Arduino was last reset. You can make the Arduino send
data every time the millis() function returns a multiple of 1000ms, effectively
creating a nonblocking 1-second delay between transmissions. To do this, you
can use the modulo operator ( % ). Modulo returns the remainder of a division. If,
for example, you executed 1000%1000 , you would find that the result is 0 because
1000/1000=1, with a remainder of 0. 1500%1000 , on the other hand, would return
500 because 1500/1000 is equal to 1, with a remainder of 500. If you take the
modulus of millis() with 1000 , the result is zero every time millis() reaches
a value that is a multiple of 1000. By checking this with an if() statement, you
can execute code once every second.
Examine the code in Listing 6-9 and load it onto your Arduino Leonardo.
Ensure that you've selected “Arduino Leonardo” from the Tools > Board menu
in the Arduino IDE.
Listing 6-9: Temperature and Light Data Logger—csv_logger.ino
//Light and Temp Logger
const int TEMP =0; //Temp sensor on analog pin 0
const int LIGHT =1; //Light sensor on analog pin 1
const int LED =3; //Red LED on pin 13
const int BUTTON =2; //The button is connected to pin 2
boolean lastButton = LOW; //Last button state
boolean currentButton = LOW; //Current button state
boolean running = false; //Not running by default
int counter = 1; //An index for logged data entries
void setup()
{
pinMode (LED, OUTPUT); //Set blue LED as output
Keyboard.begin(); //Start keyboard emulation
}
void loop()
{
currentButton = debounce(lastButton); //Read debounced state
if (lastButton == LOW && currentButton == HIGH) //If it was pressed…
running = !running; //Toggle running state
lastButton = currentButton; //Reset button value
if (running) //If logger is running
Search WWH ::




Custom Search