/*  Generic illustration of Arduino code organization
    for 60-223 Intro to Physical Computing at Carnegie Mellon University

    The overall structure is:
      1. Read information about the world
      2. Change internal state variables
      3. Drive outputs
      4. Report data back to the user

    Note that this "sketch" is illustrative only and not actually useful!

    This document released to the public domain by the author in 2022
    Robert Zacharias, rzachari@andrew.cmu.edu
*/

// create const int global variables for pin numbers (comma separated is fine)
// these are dumb sample names--use good names in your actual code!
const int SOMEPIN = A0,
          ANOTHERPIN = A2,
          YETANOTHERPIN = 10,
          OUTPUTPIN = 8;

// create global variables to store data to be shared across different functions
int someVariable,
    someOtherVariable,
    yetAnotherVariable;

// create state variables as needed
bool motionDetected = true,
     LEDstate = true;
int mappedValue;


void setup() {
  // set up all pinMode()s, turn on serial feedback, etc.
}

void loop() {

  // these functions essentially jump to different sections of the code
  // which are defined below the loop()
  // see this page for more info:
  // https://courses.ideate.cmu.edu/60-223/s2022/tutorials/code-bites#grouping-related-code-into-functions

  checkInputs();

  updateInternalState();

  driveOutputs();

  // it's often wise to limit this last step so it doesn't run too quickly
  // use Event-Loop Programming structure for that purpose, *not* a delay()!
  // see this page for more info:
  // https://courses.ideate.cmu.edu/60-223/s2022/tutorials/code-bites#blink-without-blocking
  reportBack();

  // it is usually ok to have a *brief* delay in your loop to, for instance,
  // stabilize input readings, but do keep it quick
  delay(5);

}

void checkInputs() {

  someVariable = analogRead(SOMEPIN);
  someOtherVariable = analogRead(ANOTHERPIN);
  yetAnotherVariable = digitalRead(YETANOTHERPIN);

}

void updateInternalState() {

  if (someVariable > 200) {
    LEDstate = true;
  } else {
    LEDstate = false;
  }

  if (someOtherVariable <= 555) {
    motionDetected = false;
  } else {
    motionDetected = true;
  }

  mappedValue = map (someVariable, 10, 20, 300, 400);

}

void driveOutputs() {

  // simple way to turn an output on if motionDetected is true, and off if false
  // (this works because false == LOW and true == HIGH)
  digitalWrite(OUTPUTPIN, motionDetected);

}


void reportBack() {

  // see this page for more information on serial feedback formatting:
  // https://courses.ideate.cmu.edu/60-223/s2022/tutorials/code-bites#casting-the-contents-of-serialprint-to-string-types
  Serial.println((String)
                 "someVariable = " + someVariable + ";"
                 + "someOtherVariable = " + someOtherVariable + ";"
                 + "mappedValue = " + mappedValue);
}
