Friday, August 15, 2014

Servomotors practise, Servo Motor Control using AVR ATmega8

I had bought some chinese servomotors and decided to make a laser toy for my cat.






#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

//TCCR0
#define CS0 0
#define CS1 1
#define CS2 2
#define TOIE0 0

// 4 MHz
int clock = 0;
int move_x = 20;
int move_y = 20;
int clock2 = 0;
int manual = -1;
int pressed = -1;
int x_increase = 0, y_increase = 0;

ISR(TIMER0_OVF_vect) // Interrupt when timer TNC0 is full
{

 clock++; // not great way to compute time
 if (clock == move_y) // every 1 - 2 ms pin is cleared
 {
  PORTC = PORTC ^ 0b00010000; // PD4
 }
 if (clock == move_x) // i got values through trial and error min 14 max 32
 {
  PORTC = PORTC ^ 0b00100000; // PD5
 }

 if(clock >= 251) // every 20 ms send impulse
 {
  PORTC = 0b00110000;
  clock = 0;
  clock2++;
 }

 if( manual == -1 && clock == 0 ) // If NOT user controlled
 {
  if(clock2 == 100) // about every 2 seconds
  {
   move_x = 26;
   move_y = 17;
  }
  else if(clock2 == 200) // move motors
  {
   move_x = 30;
   move_y = 20;
  }
  else if(clock2 == 300)
  {
   move_x = 20;
   move_y = 22;
  }
  else if(clock2 == 400)
  {
   move_x = 25;
   move_y = 21;
  }
  else if(clock2 >= 500)
  {
   move_x = 32;
   move_y = 19;
   clock2 = 0;
  }
 }

 if( manual == 1 && clock == 0 ) // If user controlled
 {
  if(clock2 >= 7) // Every 1/4 s move motor if button is pressed
  {
   if(x_increase == 1) move_x++;
   if(x_increase == -1) move_x--;

   if(y_increase == 1) move_y++;
   if(y_increase == -1) move_y--;

   x_increase = 0;
   y_increase = 0;
   clock2 = 0;
  }
 }

 if ((PIND & (1 << 0)) == 0 && pressed == -1)  // if utton is pressed
 {
  _delay_ms(50); // Switch debounce
  if ((PIND & (1 << 0)) == 0 && pressed == -1)
  {
   manual = -manual; // change control type
   pressed = 1; // check if pressed
  }
 }
 if ((PIND & (1 << 0)) == 1  && pressed == 1) // don't change controls 100 times
 {
  _delay_ms(50);
  if ((PIND & (1 << 0)) == 1 && pressed == 1) // move motors
  {
   pressed = -1; // 1 press
  }
 }
 if ((PIND & (1 << 1)) == 0 && move_x < 32 )  // other buttons
 {
  x_increase = 1;
 }
 if ((PIND & (1 << 2)) == 0 && move_x > 16) // for controlling motors
 {
  x_increase = -1;
 }
 if ((PIND & (1 << 3)) == 0 && move_y < 32)
 {
  y_increase = 1;
 }
 if ((PIND & (1 << 4)) == 0 && move_y > 16)
 {
  y_increase = -1;
 }
}


int main()
{
 DDRC=0xFF; // output
 DDRD=0x00; // input

 PORTD=0b00011111; // pull up on buttons
    // TIMER0
 TCCR0|=(0<<CS2)|(0<<CS1)|(1<<CS0);   // no frequency divider
 TIMSK|=(1<<TOIE0);   // interrupt on overflow of TNC0

 sei(); // allow interrupts

 while(1);
}



1 comment :

  1. Is casino poker online legal in Oklahoma?
    According to the United 온라인바카라사이트 States Supreme Court ruling, online poker gambling is w88 login an act of skill played by 가입 머니 주는 사이트 a professional gambler. This ruling 해적 룰렛 is a 더굿토토

    ReplyDelete