|
|
Example 2.1 - Motors
Thing to learn: switching devices on and off that need more voltage and/or current than you can supply with a microcontroller pin.
The code part is basically the same as the led on/off example in part 1. Just a few names are changed and the button works now as a toggle switch so the motor stays on with one press and turns off after the second press etc. Nothing very fancy here, just a normal transistor switch circuit to control bigger loads.
Parts:- ATiny45
- 100 nF capacitor
- Push button
- 10k ohm resistor
- BD675 NPN-transistor (or similar with enough power handling for the motor)
- 1N4007 diode (or similar)
- Motor or a fan, we're going to run it on 12 volts

Example 2.1

Example 2.1
/**
* MetkuMods - http://metku.net/
* How to get started with AVR microcontrollers, part 2
* Example 2.1 - Motors
*
* Author: Aki Korhonen
* Date: 2009-04-29
*/
// If clock speed isn't set in the project settings then it is set here
#ifndef F_CPU
#define F_CPU 1000000UL // 1 MHz
#endif
#include <avr/io.h>
#include <util/delay.h>
// Motor is connected to PB4 (pin 3 on the chip)
#define MOTORPIN 4
// Button is connected to PB3 (pin 2 on the chip)
#define BTNPIN 3
int main(void)
{
DDRB = 0x17; // PB3 input, others output (0x1F-0x08=0x17 or 31-8=23)
PORTB = 0x08; // Enable internal pull-up resistor on PB3 and set others low
uint8_t buttonPressed = 0;
while(1)
{
// Check if PB3 is low (button connects it to ground)
// PB3 is normally high as it has been pulled up by the internal resistor
if(bit_is_clear(PINB, BTNPIN) && buttonPressed == 0)
{
buttonPressed = 1;
if(bit_is_clear(PINB, MOTORPIN))
PORTB |= _BV(MOTORPIN); // Turn motor on
else
PORTB &= ~(_BV(MOTORPIN)); // Turn motor off
_delay_ms(100);
}
else if(!bit_is_clear(PINB, BTNPIN) && buttonPressed == 1)
{
buttonPressed = 0;
}
}
return 0;
}
| | Pages: 1 2 3 4 5 6 | |


Content in english!
Sisältö suomeksi!






