Control a DC Motor Using Swift Language
by madmachineio in Circuits > Arduino
134 Views, 0 Favorites, 0 Comments
Control a DC Motor Using Swift Language
In this mission, let's DIY a small fan. You will use a DC motor and control its speed using a potentiometer.
What You Will Need
The parts you will need are all included in this Maker kit.
- SwiftIO board
- Shield
- Motor
- Fan blade
- Potentiometer module
- 4-pin cable
DC Motor
DC motor, or Direct Current Motor, could convert the electricity into motion.
It normally has two legs, a positive one and a negative one. As you connect it to the power, it will start to rotate. And if you connect the legs in an opposite direction, the motor still works but will rotate the opposite way.
Then why does it rotate when applying voltage? That's because as the current flows, there will be an electromagnet field, and will thus cause the motor to rotate. The speed of rotation could be controlled by the PWM signal. You could adjust its duty cycle to change the speed.
The Circuit
Place the shield on top of your SwiftIO board.
Connect the potentiometer module to pin A0 using a 4-pin cable.
Connect Motor Driver module to pin PWM2B (D10). Then connect the DC motor to the module and attach the fan blade to the shaft.
The Code
// Import the SwiftIO library to use everything in it. import SwiftIO // Import the board library to use the Id of the specific board. import SwiftIOBoard // Initialize the analog pin and the PWM pin let a0 = AnalogIn(Id.A0) let motor = PWMOut(Id.PWM2B) while true { // Read the input value and use it to set the duty cycle of pwm. let value = a0.readPercent() motor.setDutycycle(value) sleep(ms: 50) }
Code Analysis
import SwiftIO import SwiftIOBoard
Import the two libraries: SwiftIO and SwiftIOBoard. SwiftIO is used to control the input and output of the SwiftIO board. SwiftIOBoard defines the pin name of the board.
let a0 = AnalogIn(Id.A0) let motor = PWMOut(Id.PWM2B)
Initialize the analog pin A0 for the potentiometer and the PWM pin PWM2B for the motor.
let value = a0.readPercent() motor.setDutycycle(value) sleep(ms: 50)
In the dead loop, read the input value in percentage, then use this value to set the duty cycle of the PWM output. So as you rotate the potentiometer, the motor speed will change accordingly. Then set a suitable sleep time.
Ok, that's all about the code. It is quite straightforward.
Run the Project
After you download the code, the fan will start to rotate. You could feel the breeze from it. When rotating the potentiometer, the motor will gradually speed up or slow down with it.