Maxim-Dallas 1-wire Temperature Sensor Example


This example demonstrates communications between a MINI-MAX/51 board and 1-wire temperature sensors such as DS18XX (DS1820,DS18B20,DS18B20X,DS18S20,DS1822) using the 1-wire bus. The example detects the temperature sensor that is connected to the board automatically using Read Family Code command.

Toolkit:Micro C 8051 Development System

Location:C:\bipom\devtools\MicroC\Examples\8051\tiny\OneWire\DS18XX

Code Example


{
	unsigned char TmpL,TmpH,Err,FC;
	unsigned int Temp;
	char sign;

    // Set the serial port to 19200 Baud 

	serinit(19200>>1);   
	for(;;)
	{
		Err =Reset_Ch0();						// Reset the 1-wire bus

		if (!Err)								// Error ? 	

		{          
			WriteByte_Ch0(0xCC);				// Skip ROM 

			WriteByte_Ch0(0x44);				// Start Conversion

			delay(1);							// 500uS delay

			Err =Reset_Ch0();					// Reset the 1-wire bus 

		}    
		if(Err) {printf("ERROR: 1-wire bus reset\n");} 
		else
		{
// Read Temperature		

			WriteByte_Ch0(0xCC);			// Skip ROM 

			WriteByte_Ch0(0xBE);			// Read Scratch Pad

    		TmpL=ReadByte_Ch0();			// Read Temperature - Low  Byte

			TmpH=ReadByte_Ch0();			// Read Temperature - High Byte

//	Read Family Code    

			Err =Reset_Ch0();				// Reset the 1-wire bus 

			WriteByte_Ch0(0x33);			// Read Rom

			FC=ReadByte_Ch0();				// Read Family Code  

//	Temp = {TmpH,TmpL}

			Temp	= TmpH;
  			Temp	<<= 8;
  			Temp	|= TmpL;
//	Detect the sign 			

			sign='+';             
			if (TmpH>0x7F)
    		{
    			sign='-';
       			Temp=(Temp^0xFFFF)+1;		//  Temperature - Absolute value 	

    		}
// Detect Temperature Sensor and print the current temperature 

			switch(FC)
			{
				case 0x10:		// DS1820,DS18S20

					printf ("\nSensor: DS1820,DS18S20");
					printf ("\nTemperature: %c%03d.%01d°C",sign,(Temp*5)10,(Temp*5)%10);
				break;
				case 0x28:		// DS18B20

					printf ("\nSensor: DS18B20"); 
					printf ("\nTemperature: %c%03d.%04d°C",sign,Temp>>4,(Temp%16)*625);
				break;
				case 0x22:		// DS1822

					printf ("\nSensor: DS1822"); 
					printf ("\nTemperature: %c%03d.%04d°C",sign,Temp>>4,(Temp%16)*625);
				break;
				default:
					printf ("\nERROR: Unknown 1-wire device,FC = %d",FC);
				break;
			}    			
		}
		printf ("\n");
		delay(1000);
	}
}