Geek Factor: Arduino Code

Here's the code we promised you in the current issue of Macworld. To download a Zip archive containing this code as well as the compiled script, click here.

long MINUTES = 15;  // take a break every 15 minutes
long SNOOZE  = 1;   // pester you every minute after that
int SENSOR_PIN = 0; // the pin the sensor's connected to

long next_alert = 0; // time of next alert (0 = no pending alert)
void setup() {
  Serial.begin(9600); // configure the serial port for 9600 bps 
  delay(10);
}

// Arduino's main loop
void loop() {

  if (analogRead(SENSOR_PIN) < 20) { // No one on the sensor 
  
    delay(2000); // Wait two seconds
    if (analogRead(SENSOR_PIN) < 20) { // Still no one there?
      if (next_alert != 0) {  // If there's a timer set, unset it
        next_alert = 0;
        Serial.print("U"); // Tell the Mac you stood Up
      }
    }
  } else {  // Some pressure on the sensor
  
    if (next_alert == 0) {  // Set a new alert if there was none
      next_alert = millis() + MINUTES * 60 * 1000;   
      Serial.print("D"); // Tell the Mac you sat Down
    }    
    if (millis() > next_alert) { // You've been sitting too long
      next_alert = millis() + SNOOZE * 60 * 1000; 
      Serial.print("B"); // Tell the Mac it's Break time
    }
  }
  delay(250);
  
}

Shop ▾
arrow up Amazon Shop buttons are programmatically attached to all reviews, regardless of products' final review scores. Our parent company, IDG, receives advertisement revenue for shopping activity generated by the links. Because the buttons are attached programmatically, they should not be interpreted as editorial endorsements.

Subscribe to the Best of Macworld Newsletter

Comments