NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.
August 14, 2011
by kle8309
|
I recently got a relay module from Ebay for a good price (I think) of $14.5. I
decided to use my laptop to send command over the uart cable to control a simple
motor. To do that, I used VS C# app since they support serialPort. Once the MCU
decodes the uart command, it will pull the IO pin low or high depending on the
user command.
Here is the code for the MCU:
#define F_CPU 14745600
#include <stdio.h>
#include <math.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <inttypes.h>
#include "../libnerdkits/delay.h"
#include "../libnerdkits/lcd.h"
#include "../libnerdkits/uart.h"
//#define MAX_STRING_LEN 10
//
uint8_t baudrateH, baudrateL;
int8_t SetBaudRate(uint16_t baud)
{ uint16_t baudrate;
baudrate = (float)F_CPU/16/baud-1;
baudrateH = baudrate >> 8;
baudrateL = baudrate & 0xff;
UBRR0H = baudrateH; //(F_CPU/16/BAUD-1)>>8;
UBRR0L = baudrateL; //(F_CPU/16/BAUD-1)&&0xff;
UCSR0B = (1<<RXEN0)|(1<<TXEN0); // enable uart
UCSR0C = (1<<UCSZ00) | (1<<UCSZ01); //8 bits
return(1);
}
int main() {
// start up the LCD
lcd_init();
FILE lcd_stream = FDEV_SETUP_STREAM(lcd_putchar, 0, _FDEV_SETUP_WRITE);
lcd_home();
// start up the serial port
uart_init();
FILE uart_stream = FDEV_SETUP_STREAM(uart_putchar, uart_getchar, _FDEV_SETUP_RW);
stdin = stdout = &uart_stream;
//int i=0;
//uint16_t baud = 9600;
char x =' ';
//char msg[MAX_STRING_LEN];
SetBaudRate(9600);
// set output
DDRC|=0xFF;
PORTC|=0xFF;
DDRB|=0xFF;
PORTB|=0xFF;
while(1) {
if (uart_char_is_waiting()){
x= getchar();
}// end if
lcd_line_one();
fprintf_P(&lcd_stream, PSTR("You Entered: %c "),x);
if(x=='1'){
PORTC&=~(1<<PC5);
}
else if(x=='2'){
PORTC&=~(1<<PC4);
}
else if(x=='3'){
PORTC&=~(1<<PC3);
}
else if(x=='4'){
PORTC&=~(1<<PC2);
}
else if(x=='5'){
PORTC&=~(1<<PC1);
}
else if(x=='6'){
PORTC&=~(1<<PC0);
}
else if(x=='7'){
PORTB&=~(1<<PB5);
}
else if(x=='8'){
PORTB&=~(1<<PB4);
}
else{
lcd_line_two();
fprintf_P(&lcd_stream, PSTR("Reset All Relays "));
PORTC|=0xFF;
PORTB|=0xFF;
}
}// end while
return 0;
}
|
August 14, 2011
by kle8309
|
Here is what it look like in action
relays in action |
Post a Reply
Please log in to post a reply.