Here's some sample Arduino code for controlling a motor with a switch:
This code uses the Arduino's digitalRead() function to read the state of the switch, and digitalWrite() function to control the motor pin. If the switch is pressed, the motor pin is set to HIGH, which causes the motor to run in forward direction. If the switch is not pressed, the motor pin is set to LOW, which causes the motor to stop.
To use this code, you will need the following electronic components:
- An Arduino UNO or any arduino board
- A DC motor
- A switch
- A breadboard
- Jumper wires
- 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:
- 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.
- 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.
- 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.
- Connect the free row of the switch to a digital pin on the Arduino board, the code I provided uses pin 2.
- Connect the motor control pin (digital pin 9) on the Arduino board 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.
- Arduino UNO: You can buy an "Arduino UNO R3"
- DC Motor: You can buy a DC motor like this one: "DC 6V-12V Mini Electric Motor"
- Switch: You can buy a switch like this one: "Momentary Push Button Switch"
- Breadboard: You can buy a breadboard like this one: "Solderless Breadboard"
- Jumper wires: You can buy jumper wires like this one: "Dupont Jumper Wires"
- Power supply: You can buy a power supply like this one: "DC 6V-12V Power Supply"
No comments:
Post a Comment