/*
Author: Malek Azadegan
*/
#include <Servo.h>
#include <RTClib.h>
#include <time.h>
#include <SdFat.h>
Servo myServo;
RTC_DS1307 rtc;
SdFat sd;
SdFile myFile;
int potPin = 0;
int potPinVal;
const int chipSelect = 10;
void setup() {
Serial.begin(115200);
if (!rtc.begin()) {
Serial.println("Couldn't find RTC");
Serial.flush();
abort();
}
// log file
if (!sd.begin(chipSelect, SPI_HALF_SPEED)) {
sd.initErrorHalt();
}
// open log file
if (!myFile.open("log.txt", O_RDWR | O_CREAT | O_AT_END)) {
sd.errorHalt("opening log.txt for write failed");
}
Serial.println("SD Contents:");
Serial.println("\tSIZE\tNAME");
sd.ls(LS_R | LS_SIZE);
Serial.println("\t------");
myServo.attach(9); // Servo is attached to pin #9
}
int calcAngle(int a) {
if (a > 90) {
return (a - 90) * -1;
}
return abs(a - 90);
}
void loop() {
// positioning the servo
potPinVal = analogRead(potPin); // read the value of the potentiometer
potPinVal = map(potPinVal, 0, 1023, 0, 180); // scale it to the equivalent value in [0,180]
potPinVal = abs(potPinVal - 180); // "finish the circle"
myServo.write(potPinVal); // set the servo position
// preparing log
DateTime now = rtc.now(); // get time from RTC
time_t t = now.unixtime() - UNIX_OFFSET; // get as unix timestamp minus the 30 year offset
struct tm *lt = localtime(&t); // strftime requires a tm struct holding date components
char buffer[40];
strftime(buffer, sizeof(buffer), "[%Y/%m/%d %H:%M:%S]", lt); // format timestamp
sprintf(buffer, "%s Angle: %d degrees", buffer, calcAngle(potPinVal)); // include angle
Serial.println(buffer); // Log the servo position to the console
myFile.println(buffer); // Log the servo position to the log file
delay(1000); // one second between iterations of the loop
}