/*  Filename     ZMCP4921.C	
    Description  MCP4921 12-BIT DAC EXAMPLE PROGRAM	
    Hardware     SLAB-51
    Clock        11.0592 MHz
    Compiler     Keil PK51 v7.10
    Engineer     Kriangsak B.
    Company      Sila Research Co.,Ltd. 
*/

#include <reg51.h>
#include <absacc.h>
#include <assert.h>
#include <ctype.h>
#include <intrins.h>
#include <math.h>
#include <setjmp.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/********** I/O PORT **********/

sbit     MCPCS     = P1^0;
sbit     MCPSCK    = P1^1;
sbit     MCPSDI    = P1^2;
sbit     MCPLDA    = P1^3;

/********** SUB FUNCTION **********/

void mcpword (unsigned int x) {             // mcp4921 write word (12 bit)
    unsigned char i;
    x = x | 0x3000;                         // daca,unbuffered,1x,output control bit
	MCPSCK = 0;
	MCPLDA = 1;
	MCPCS = 0;
    for (i=0;i<=15;i++) {
        if (x & 0x8000) MCPSDI = 1; else MCPSDI = 0;
        x <<= 1;
		MCPSCK = 1;
        _nop_ ();
        _nop_ (); 
        MCPSCK = 0;
    }
    MCPCS = 1;
	MCPLDA = 0;
	_nop_ ();
	_nop_ ();
	MCPLDA = 1;
}

/********** MAIN FUNCTION **********/

void start (void) {               // speed x 1
    SCON = 0x52;             	  // set RS232 parameter
    TMOD = 0x20;
    TH1 = 0xfd; PCON |= 0x80;     // 19200
    TR1  = 1;
}

void main (void) {
    unsigned char a;
	unsigned int y;
    float v,x;

    start ();
	printf ("ZMCP4921.C Example Program ...\n");

	v = 2.5;                                          // 0.00-5.00 volt
	while (1) {
	    if (v>0) x = v * 4095 / 5; else x = 0;        // change volt to 0-4095 data 
        y = x;
 	    mcpword (y);
        printf ("Volt = %1.2f (Data = %d)\n",v,y);
		a = getkey ();
		if (a=='+') v = v + 0.1;
		else if (a=='-') v = v - 0.1;
		else if (a=='a' || a=='A') v = 0;
		else if (a=='z' || a=='Z') v = 5;
    }
}


