| 1 | /* |
| 2 | Program : cro.c |
| 3 | author : Ajith Kumar ([email protected]) |
| 4 | License : GNU GPL version 3 or above |
| 5 | On receiving a single byte command,reads ADC channel 0 500 times, with 100 usec timegap |
| 6 | and returns a 'D' followed by 500 bytes of data. No error checking implemented. |
| 7 | */ |
| 8 | |
| 9 | #include <avr/io.h> |
| 10 | |
| 11 | #define READBLOCK 1 // code for readblock is 1 |
| 12 | #define NS 500 // Maximum 1800 for ATmega32, with 2K RAM |
| 13 | #define TG 100 // 100 usec between samples |
| 14 | |
| 15 | uint8_t tmp8, dbuffer[NS]; |
| 16 | uint16_t tmp16; |
| 17 | |
| 18 | |
| 19 | int main (void) |
| 20 | { |
| 21 | // Initialize the RS232 communication link to the PC 38400, 8, 1, N |
| 22 | UCSRB = (1 << RXEN) | (1 << TXEN); |
| 23 | UBRRH = 0; |
| 24 | UBRRL = 12; // At 8MHz clock (12 =>38400 baudrate) |
| 25 | UCSRC = (1 <<URSEL) | (1 << UCSZ1) | (1 << UCSZ0); // 8,1,N |
| 26 | ADCSRA = (1 << ADEN); // Enable the ADC |
| 27 | |
| 28 | for(;;) // Infinite loop waiting for commands from PC |
| 29 | { |
| 30 | while ( !(UCSRA & (1<<RXC)) ); // wait for data from PC |
| 31 | if(UDR == 1) // '1' is our command |
| 32 | { |
| 33 | TCCR1B = (1 << CS11); // TC1 in Normal mode, 8 MHz/8, 1 usec per count |
| 34 | ADMUX = (1 << REFS0) |(1 << ADLAR) | 0; // 8 bit mode, AVCC ref, channel 0 |
| 35 | ADCSRA |= ADIF; // reset ADC DONE flag |
| 36 | for(tmp16 = 0; tmp16 < NS; ++tmp16) // Digitize nsamples times |
| 37 | { |
| 38 | TCNT1 = 1; |
| 39 | ADCSRA |= (1 << ADSC) | 1; // Start AD conversion, ADC clock divider is 1 |
| 40 | while ( !(ADCSRA & (1<<ADIF)) ) ; // wait for conversion to complete |
| 41 | dbuffer[tmp16] = ADCH; // Collect Data and store it |
| 42 | ADCSRA |= ADIF; // reset ADC DONE flag |
| 43 | while(TCNT1L < TG) ; // Wait on counter for the specified time gap |
| 44 | } |
| 45 | // Why we are NOT sending data inside the above loop. Think about it. |
| 46 | |
| 47 | while( !(UCSRA & (1 <<UDRE) ) ); // Wait for transmit buffer empty flag |
| 48 | UDR = 'D'; // Send the response byte in all cases |
| 49 | for(tmp16=0; tmp16 < NS; ++tmp16) // Send the collected data to the PC |
| 50 | { |
| 51 | while( !(UCSRA & (1 <<UDRE) ) ); |
| 52 | UDR = dbuffer[tmp16]; |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | } |