PIC18F4520: Serial Digital-to-Analog Conversion

From Mech
Jump to navigationJump to search

Since PIC microcontrollers do not offer analog outputs, a Digital-to-Analog converter (DAC) must be used to obtain an analog signal. An eight bit digital number can be converted to analog by using eight of the output pins from the PIC MCU to a separate DAC chip, however if more than one conversion is neccessary, this will quickly use up many of the available output pins from the PIC microcontroller, and require extensive wiring. Luckily, there is an easier and more effective way of doing this using communication. utilizes two lines to communicate, usually called SCL and SDA (a clock line and a data line). A "master" produces an signal which is sent to the "slave" to work with. Many slaves can be controlled by one master, as long as no slave addresses are used more than once (the number of possible slave addresses is limited by the specific chip being used as a slave). If the slave chip has two programmable address bits, then four slaves can be controlled by one master. If there are three address bits, then eight slaves can be controlled by one master. Communication begins with a start condition (the clock line being held high while the data line is dropped low) and ends with a stop condition (clock line held high while the data line is brought from low to high).

Startstopcond.jpg



Between the start and stop conditions are different bytes of information. These will differ with each application and each device you are communicating with, although many will have some sort of addressing byte, a command byte, and then information bytes. After every byte sent, the slave will send back an acknowledge bit, prompting the master to send the next byte of information.

C Programming

The basic building blocks of programming for communication are shown below.

Function Description
i2c_start() Sends a start condition
i2c_write() Writes a data byte to the slave
i2c_stop() Sends a stop condition


Using these three functions, one can program whatever information is required to the slave device.

Example of Communication

This example shows how to use to communicate with a DAC. The PIC MCU will take an analog input (0-5V), and through communication it will utilize an external DAC to display the input voltage. Obviously this is of no practical use, but is meant as an excercise with and digital-to-analog conversion.