Sunday, January 1, 2012

How Fast Relays Are?

From the time I learned about relays, I wondered if they can be used to make an H-Bridge for motors, I asked my professor and he said that you can't because they are slow.

I never knew how slow, till today, so I wrote a small code on my AVR ATmega168 microcontroller

basically, the code send an ON -> delay(x) -> OFF -> delay(x)

where x is a value (in ms) changing every time a button is pressed going down from 15 ms to 1ms

1:  #include <avr/io.h>  
2:  #include <util/delay.h>  
3:  #include <USART.h>  
4:  #define SETBIT(ADDRESS,BIT) (ADDRESS |= (1<<BIT))  
5:  #define CLEARBIT(ADDRESS,BIT) (ADDRESS &= ~(1<<BIT))  
6:  int main(void)  
7:  {  
8:       init_uart();  
9:        SETBIT(DDRB,0);  //Output pin (ON/OFF)
10:       CLEARBIT(DDRB,1); //Input to change time
11:       SETBIT(PORTB,1);  //Enable Pull-Up resistor
12:       for (;;)  
13:       {  
14:            for (uint16_t i=15; i>0; i--)  //repeat 15 times going down, used as delay
15:            {  
16:                 printf("i=%d\n",i);  //just to see whats the current delay value
17:                 _delay_ms(100);  //give me time to release button
18:                 while ((PINB & 0x02)==0x02)  //loop when I don't press button
19:                 {  
20:                      SETBIT(PORTB,0);   //ON
21:                      _delay_ms(i);      //i value as delay
22:                      CLEARBIT(PORTB,0); //OFF 
23:                      _delay_ms(i);
24:                 }  
25:            }  
26:       }  
27:       return 0;  
28:  } 

And then connected the relay, driving it with a NPN



I found that min time is 2ms, at 1ms, no switching will occur ( i was getting highly rippled 5v)



and here is an awesome sound of 1~15ms switching, at 0:16 the time is 1ms



~2ms (500Hz) is the min time (max freq) u can switch a typical relay