Controlling a DC Motor with a Switch using Raspberry Pi - Python Language

Here's some sample Python code for controlling a motor with a switch:

This code uses the RPi.GPIO library to control the GPIO pins on a Raspberry Pi. It sets up the switch pin as an input with a pull-up resistor, and the motor pin as an output. It then enters a loop where it reads the state of the switch, and if the state has changed, it sets the motor pin high or low depending on the switch state.

To use this code, you will need the following electronic components:

  1. A Raspberry Pi
  2. A DC motor
  3. A switch
  4. A breadboard
  5. Jumper wires
  6. A power supply for the motor, usually 6 to 12V DC will work depending on the motor.

You will also need to connect the components together in a circuit, here's a simple circuit diagram: To connect the circuit, you will need to follow these steps:

  1. Connect the positive lead of the power supply to one of the power rail on the breadboard, and the negative lead to the other rail.
  2. Connect the positive lead of the motor to the same rail as the positive lead of the power supply, and the negative lead of the motor to the same rail as the negative lead of the power supply.
  3. Connect one end of the switch to the same rail as the positive lead of the power supply, and the other end to a free row on the breadboard.
  4. Connect the free row of the switch to a free GPIO pin on the Raspberry Pi, the code I provided uses pin 23.
  5. Connect the motor control pin (GPIO 18) on the Raspberry Pi to the same row as the negative lead of the motor.

You can buy all the electronic items from amazon or any other online or physical store.

  1. Raspberry Pi: You can buy any version of Raspberry Pi like Raspberry Pi 4 Model B
  2. DC Motor: You can buy a DC motor like this one: "DC 6V-12V Mini Electric Motor"
  3. Switch: You can buy a switch like this one: "Momentary Push Button Switch"
  4. Breadboard: You can buy a breadboard like this one: "Solderless Breadboard"
  5. Jumper wires: You can buy jumper wires like this one: "Dupont Jumper Wires"
  6. Power supply

You can also check the motor's voltage requirement before buying the power supply.

Please let me know if you have any questions or if there's anything else I can help you with.

No comments:

Post a Comment

Please disable your ad blocker to support this website.

Our website relies on revenue from ads to keep providing free content.