/* p7_1.c: A to D conversion of channel 2 - LM34 * This program converts the analog input from channel 2 (PB08) * which is connected to an LM34. External 3.3V is connected VREFA. * The conversion result is scaled to degree F and sent to * UART on SERCOM3 at 9600 Baud. * UART3 is connected to EDBG virtual connection to the host PC COM port. * Use TeraTerm to see the message "YES" on a PC. * * Tested with Atmel Studio 7 v7.0.1006 and Keil MDK-ARM v5.21a. */ #include "samd21.h" #include unsigned char* ARRAY_PORT_PINCFG0 = (unsigned char*)®_PORT_PINCFG0; unsigned char* ARRAY_PORT_PMUX0 = (unsigned char*)®_PORT_PMUX0; unsigned char* ARRAY_PORT_PINCFG1 = (unsigned char*)®_PORT_PINCFG0; unsigned char* ARRAY_PORT_PMUX1 = (unsigned char*)®_PORT_PMUX0; void UART3_init(void); void UART3_write(char data); void UART3_puts(char* s); void delayMs(int n); int main (void) { int result; int temperature; char outbuf[20]; UART3_init(); REG_PM_APBCMASK |= 0x10000; /* enable bus clock for ADC */ REG_GCLK_CLKCTRL = 0x401E; /* GCLK0 to ADC */ REG_ADC_SAMPCTRL = 5; /* sampling time 5 clocks */ ARRAY_PORT_PINCFG0[3] |= 1; /* Use PMUX for PA03 */ ARRAY_PORT_PMUX0[1] = 0x10; /* PA03 = VREFA */ REG_ADC_REFCTRL = 3; /* Use VREFA */ REG_ADC_INPUTCTRL = 0x1802; /* V- = GND; V+ = AIN2 */ ARRAY_PORT_PINCFG1[8] |= 1; /* Use PMUX for PB08 */ ARRAY_PORT_PMUX1[4] = 0x10; /* PB08 = AIN2 */ REG_ADC_CTRLA = 2; /* enable ADC */ while (1) { REG_ADC_SWTRIG = 2; /* start a conversion */ while(!(REG_ADC_INTFLAG & 1)); /* wait for conv complete */ result = REG_ADC_RESULT; /* read conversion result */ temperature = result * 330 / 4096; sprintf(outbuf, "T = %d\r\n", temperature); UART3_puts(outbuf); delayMs(200); } } /* initialize UART3 to transmit at 9600 Baud */ void UART3_init(void) { REG_PM_APBCMASK |= 0x00000020; /* enable bus clock for SERCOM3 */ REG_GCLK_CLKCTRL = 0x4017; /* GCLK0 to SERCOM3 */ REG_SERCOM3_USART_CTRLA |= 1; /* reset SERCOM3 */ while (REG_SERCOM3_USART_SYNCBUSY & 1) {} /* wait for reset to complete */ REG_SERCOM3_USART_CTRLA = 0x40106004; /* LSB first, async, no parity, PAD[0]-Tx, BAUD uses fraction, 8x oversampling, internal clock */ REG_SERCOM3_USART_CTRLB = 0x00010000; /* enable Tx, one stop bit, 8 bit */ REG_SERCOM3_USART_BAUD = 13; /* 1000000/8/9600 = 13.02 */ REG_SERCOM3_USART_CTRLA |= 2; /* enable SERCOM3 */ while (REG_SERCOM3_USART_SYNCBUSY & 2) {} /* wait for enable to complete */ ARRAY_PORT_PINCFG0[22] |= 1; /* allow pmux to set PA22 pin configuration */ ARRAY_PORT_PMUX0[11] = 0x02; /* PA22 = TxD */ } void UART3_write(char data) { while(!(REG_SERCOM3_USART_INTFLAG & 1)) {} /* wait for data register empty */ REG_SERCOM3_USART_DATA = data; /* send a char */ } void UART3_puts(char* s) { while (*s) UART3_write(*s++); } /* millisecond delay based on 1 MHz system clock */ void delayMs(int n) { int i; for (; n > 0; n--) for (i = 0; i < 199; i++) __asm("nop"); }