LM35 Project Software
3 min
The firmware required to interface with the sensor performs several tasks.
- Configures the microcontroller to read the analog value
- Converts the analog value to a digital number
- Formats that value for export
Microcontroller
The device chosen is the PIC16F887, and while it is far more in terms of resources it will provide a good base to build on and with for later projects or adding on additional features.
What is needed from the microcontroller is:
- One of the Analog Inputs
- PORTB for the LCD Display
- Comport to share the data with the outside world
Full Code Sample
The full code sample is shown below and can be copied from the code block.
The code sample is also available from GitHub.
unsigned char ch;
unsigned int adc_rd;
char *text;
long tlong;
char *tempc = "000.0";
void deviceSetup(){
INTCON = 0; // disable all interrupts
ANSEL = 0x04; // Configure AN2 pin as analog input
TRISA = 0x04;
ANSELH = 0;
ADCON1 = 0x82; // configure VDD as Vref, and analog channels
TRISA = 0xFF; // designate PORTA as input
UART1_Init(9600);
Delay_ms(100);
}
void main() {
Lcd_Config(&PORTB, 4, 5, 6, 3, 2, 1, 0); // Lcd_Init_EP5, see Autocomplete
LCD_Cmd(LCD_CURSOR_OFF); // send command to LCD (cursor off)
LCD_Cmd(LCD_CLEAR); // send command to LCD (clear LCD)
text = "LM 35 Project"; // assign text to string
LCD_Out(1,1,text); // print string a on LCD, 1st row, 1st column
Delay_ms(2000);
text = "Temp:"; // assign text to string
while (1) {
adc_rd = ADC_read(2); // get ADC value from 2nd channel
LCD_Out(2,1,text); // print string a on LCD, 2nd row, 1st column
tlong = (long)adc_rd * 5000; // covert adc reading to milivolts
tlong = tlong / 1023; // 0..1023 -> 0-5000mV
ch = tlong / 1000; // extract leading temp digit
tempc[1] = ch+48;
ch = (tlong / 100) % 10; // extract 0.1 temp digit
LCD_Chr_CP(48+ch); // write ASCII digit at cursor point
tempc[2] = ch+48;
ch = (tlong / 10) % 10; // extract 0.01 temp digit
tempc[3] = ch+48;
LCD_Chr_CP(48+ch); // write ASCII digit at cursor point
LCD_Chr_CP(48+ch); // write ASCII digit at cursor point
LCD_Chr_CP('C');
tempc[4] = ch+48;
UART1_Write(tempc[2]);
UART1_Write(tempc[3]);
UART1_Write_Text(".");
UART1_Write(tempc[4]);
UART1_Write(13);
UART1_Write(10);
Delay_ms(100);
}
}//~!