Example code from todays lecture: switch and rangefinder

// Tip the Can - written by Ted Burke - 16-10-2019

// pin numbers
int red = 2;
int green = 3;
int blue = 4;
int trig = 6;
int echo = 7;

void setup()
{
  pinMode(red, OUTPUT);   // red
  pinMode(green, OUTPUT); // green
  pinMode(blue, OUTPUT);  // blue

  pinMode(trig, OUTPUT);  // HC-SR04 trigger pin

  Serial.begin(9600);     // open serial connection to laptop
}

int button_was_pressed = 0; // global flag variable

void loop()
{
  // Read the distance from the rangefinder
  int duration;                          // stores echo pulse duration in microseconds
  float distance;                        // stores the distance in metres
  digitalWrite(trig, HIGH);              // begin trigger pulse
  delayMicroseconds(20);                 //
  digitalWrite(trig, LOW);               // end trigger pulse
  duration = pulseIn(echo, HIGH, 10000); // measure echo pulse duration
  distance = 340e-6 * (duration/2);      // convert to distance in metres
  Serial.print(distance);                // print out the distance
  Serial.println(" metres");             //
  delay(100);                            // 100 ms delay

  // Check the switch
  if (digitalRead(9) == 1)
  {
    button_was_pressed = 1;
  }

  // Decide what to do with the LEDs
  if (button_was_pressed == 0 && (distance > 0.8 || distance == 0))
  {
    // This code runs if the button has not been pressed and
    // the distance is either greater than 0.8m or zero, which
    // indicates a timeout
    // "&&" means logical AND
    // "||" means logical OR
    digitalWrite(red, HIGH);
    digitalWrite(green, LOW);
    digitalWrite(blue, LOW);
  }
  else if (button_was_pressed == 0 && distance <= 0.8)
  {
    // This code runs if the button has not been pressed and
    // the distance is less than 0.8m (but not zero)
    digitalWrite(red, LOW);
    digitalWrite(green, HIGH);
    digitalWrite(blue, LOW);
  }
  else
  {
    // This code runs if neither of the previous two blocks did
    digitalWrite(red, LOW);
    digitalWrite(green, LOW);
    digitalWrite(blue, HIGH);
  }
}
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s