|
Code:
// headerfile
#include <avr/io.h>
#include <avr/interrupt.h>
#include "delay.h"
#define F_CPU 8000000UL
#define OC3C_PORT E
#define OC3C_PIN PE5
#define OC3B_PORT E
#define OC3B_PIN PE4
#define DDR(a) __CONCAT(DDR,a)
#define PORT(a) __CONCAT(PORT,a)
#define PIN(a) __CONCAT(PIN,a)
#define HALT 0
#define LEFT 1
#define RIGHT 2
#define FORWARD 1
#define BACKWARD 2
void MotorInit();
void Motor_Dir(uint8_t dir);
void Motor_Speed(uint8_t dir,uint8_t speed);
Code:
void MotorInit()
{
// DEFINING SPEED OF PWM
TCCR3A= (1<<COM3B1)|(1<<COM3C1); // Clear OC3B & OC3C on compare match
TCCR3B |= (1<<WGM33); // Phase and frequency correct PWM mode
// CLOCK SPEED = F_CPU/ RESCALAR--------PRESCALAR = 8
TCCR3B |= (1<<CS31);
ICR3 = 1250; // 200 Hz
// SET THE PINS TO OUTPUT
DDR(OC3C_PORT)|=(1<<OC3C_PIN);
DDR(OC3B_PORT)|=(1<<OC3B_PIN);
// DEFINE OUTPUT FOR CONTROL PINS
DDRE|=0X0F; // PE4 to PE7 as output
}
/*----------------------------------------------------
DEFINING SPEED (0 TO 255) & DIRECTION OF THE MOTOR_Speed
DIR = 0 for STOP ROTAION
= 1 for FORWARD
= 2 for BACKWARD
----------------------------------------------------*/
void Motor_Speed(uint8_t dir,uint8_t speed)
{
// DIRECTION
if(dir == 0)
{
PORTE&=(~(1<<PE4));
PORTE&=(~(1<<PE5));
}
else if(dir == 2)
{
PORTE&=(~(1<<PE4));
PORTE|=(1<<PE5);
OCR3B=speed;
}
else if(dir == 1)
{
PORTE&=(~(1<<PE5));
PORTE|=(1<<PE4);
OCR3C=speed;
}
// SPEED
uint8_t sreg=SREG;
cli();
SREG=sreg;
}
//---------------------------------------------
I wrote the following code as well For test
Code:
void Moving(uint8_t AngDir , uint8_t VectDir , uint8_t Speed);
void Moving(uint8_t AngDir , uint8_t VectDir , uint8_t Speed)
{
if(AngDir!=0)
{
Motor_Speed(VectDir,Speed); // Moves straight with speed of 0.5 m/s
Motor_Dir(AngDir);
_delay_us(1);
}
else
{
Motor_Dir(0); // assure steering wheel is straight
Motor_Speed(VectDir,Speed); // Moves straight with speed of 1 m/s
}
}
|