/********************************************* Laser Communication Text Data Echoer Authors: Keith Carter, Michael Muccio Cornell University, Electrical and Computer Engineering ECE 476, Spring 2003 This program is used to program a Mega32 MCU to be the receiver or transmitter for a serial text data laser communication system. It receives serial data and retransmits it. Chip type : ATmega32 Program type : Application Clock frequency : 16.000000 MHz Memory model : Small Internal SRAM size : 2048 External SRAM size : 0 Data Stack size : 512 *********************************************/ #include #include #include #include #include //set baud to 38.4 kbps #define baudnum 25 #define halfbaudnum 13 //global variables char bitcnt; // bit counter char Txbyte; // data to be transmitted char Rxbyte; // received data char sb; // number of stop bits (1, 2, ...) char carry // carry bit //the data transmit and receive subroutines void put(void); void get(void); //Transmit Byte void put(void) { bitcnt=9+sb; //initiate bit counter Txbyte=~Txbyte; //invert byte for easier handling carry=1; //set carry to 1 for start bit //while loop transmits the data bits using delay while(bitcnt>0) { //transmit opposite of what is in carry if (carry) { PORTD.1=0; } else { PORTD.1=1; #asm("nop") } delay_us(baudnum); //1 bit delay carry=(Txbyte&0b00000001); //move LSB to carry1 Txbyte=Txbyte>>1; //shift transmit byte right bitcnt--; //decrement bitcnt, 1 bit sent } PORTD.1=1; } //Receive Byte void get(void) { Rxbyte = 0x00; //clear receive byte bitcnt=9+sb; //initialize bit counter //while loop waits for start bit while(PIND.0 != 0) { // hang out } //delay to middle of start bit delay_us(halfbaudnum); //while loop samples at middle of bits //stops at bitcnt of 2 to avoid shifting //in stop bit while(bitcnt>2) { delay_us(baudnum); //1 bit delay Rxbyte=Rxbyte>>1; //shift receive byte right 1 //sample bit //move value to MSB of receive byte if (PIND.0) { Rxbyte=Rxbyte | 0b10000000; } else { Rxbyte=Rxbyte & 0b01111111; } bitcnt--; //decrement bitcnt, 1 bit received } } void main(void) { DDRD=0b00000010; // direction for UART pins sb=1; // set to 1 stop bit Txbyte=12; // clear the screen put(); delay_ms(1500); Txbyte=12; // clear the screen again put(); //infinite loop receives data and echoes by immediately retransmitting while (1) { get(); // receive a byte Txbyte=Rxbyte; // transfer data put(); // send a byte Rxbyte = 0x00; // clear receive byte } }