Skip to content

Instantly share code, notes, and snippets.

@kern
Created January 23, 2012 03:03
Show Gist options
  • Save kern/1660204 to your computer and use it in GitHub Desktop.
Save kern/1660204 to your computer and use it in GitHub Desktop.
#include "Time.h"
#include "SD.h"
#define SAMPLE_TIME 40
#define MAX_ENTRIES 100
#define MAX_ENTRIES_PER_FILE 25000
#define BUTTON_PIN 9
int running = 0;
int entries = 0;
int entries_in_file = 0;
File file;
int open() {
int n = 0;
char filename[256];
int found = 0;
while (!found) {
snprintf(filename, sizeof filename, "%i.csv", n);
if (!SD.exists(filename)) {
found = 1;
} else {
n++;
}
}
file = SD.open(filename, FILE_WRITE);
return (int) file;
}
void close() {
file.close();
}
void write_header() {
file.println("Time,X,Y,Z");
}
void write_entry(int time, int x, int y, int z) {
char entry[256];
snprintf(entry, sizeof entry, "%i,%i,%i,%i", time, x, y, z);
file.println(entry);
entries++;
entries_in_file++;
}
void start_tone() {
tone(6, 262);
delay(250);
noTone(6);
}
void stop_tone() {
tone(6, 262);
delay(250);
noTone(6);
delay(100);
tone(6, 262);
delay(250);
noTone(6);
}
void start_running() {
if (open()) {
start_tone();
write_header();
running = 1;
entries = 0;
entries_in_file = 0;
}
}
void stop_running() {
close();
running = 0;
stop_tone();
}
void reopen_file() {
close();
open();
write_header();
entries_in_file = 0;
}
int button_pressed() {
return digitalRead(BUTTON_PIN) == LOW;
}
void setup() {
SD.begin();
pinMode(BUTTON_PIN, INPUT);
// Wait for everything to initialize.
delay(5000);
}
void loop() {
if (running) {
int offset = entries * SAMPLE_TIME;
int x = analogRead(0);
int y = analogRead(1);
int z = analogRead(2);
write_entry(offset, x, y, z);
delay(SAMPLE_TIME);
if (entries >= MAX_ENTRIES) {
stop_running();
} else if (entries_in_file >= MAX_ENTRIES_PER_FILE) {
reopen_file();
}
} else if (button_pressed()) {
start_running();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment