Raspberry Pi Pico Microcontroller

From Sensors in Schools
Jump to navigation Jump to search

References

Object Oriented Programming

Button Class

// Button.h
#ifndef BUTTON_H
#define BUTTON_H

class Button {
public:
    Button(int pin);
    bool isPressed();

private:
    int buttonPin;
};

#endif
// Button.cpp
#include "Button.h"
#include "Arduino.h"

Button::Button(int pin) {
    buttonPin = pin;
    pinMode(buttonPin, INPUT);
}

bool Button::isPressed() {
    return digitalRead(buttonPin) == HIGH;
}


LED Class

// LED.h
#ifndef LED_H
#define LED_H

class LED {
public:
    LED(int pin);
    void turnOn();
    void turnOff();

private:
    int ledPin;
};

#endif
// LED.cpp
#include "LED.h"
#include "Arduino.h"

LED::LED(int pin) {
    ledPin = pin;
    pinMode(ledPin, OUTPUT);
}

void LED::turnOn() {
    digitalWrite(ledPin, HIGH);
}

void LED::turnOff() {
    digitalWrite(ledPin, LOW);
}

Switch using Button and LED

#include "Button.h"
#include "LED.h"

const int buttonPin = 2; // Connect the button to pin 2
const int ledPin = 13;   // Connect the LED to pin 13

Button myButton(buttonPin);
LED myLED(ledPin);

void setup() {
    Serial.begin(9600);
}

void loop() {
    if (myButton.isPressed()) {
        myLED.turnOn();
        Serial.println("Button Pressed!");
    } else {
        myLED.turnOff();
    }
}

Explanation:

  • Button Class: The Button class is responsible for handling the button. It has a constructor to initialize the pin and a method (isPressed) to check if the button is pressed.
  • LED Class: The LED class is responsible for handling the LED. It has a constructor to initialize the pin and methods (turnOn and turnOff) to control the LED.
  • Sketch:
    • In the sketch, we create instances of the Button and LED classes and connect them to the specified pins.
    • In the loop function, we continuously check if the button is pressed using the isPressed method. If it is pressed, the LED is turned on; otherwise, it's turned off.
    • Make sure to connect the button to the defined buttonPin and the LED to the defined ledPin. Adjust the pin numbers in the sketch accordingly based on your hardware setup.