#include #include #include #include "i2cmsu.h" #define DATA_EEMEM_PROTECT_DISABLE 0x0100 #define XT_OSC 0x0001 #define DISABLE_DEBUG 0x0800 #define CP0 0x1010 #define CP1 0x2020 /* CP0,CP1 code protect off*/ /* other bits zero which means WDT disabled Low Voltage prm disabled, brownout disabled power up timer enabled */ __CONFIG((CP1 | CP0) | DATA_EEMEM_PROTECT_DISABLE | XT_OSC | DISABLE_DEBUG); #define bitset(var,bitno) ((var) |= (1 << (bitno))) #define bitclr(var,bitno) ((var) &= ~(1 << (bitno))) #define bittst(var,bitno) (var & (1 << (bitno))) /* read value from ADC, output to serial port via printf */ /* also output to DAC on I2C Bus */ #define DAC 0x58 /* I2C DAC 01011000 */ /* the outer legs of the 10K pot should be hooked up between +5 and 0 */ /* the middle leg (wiper) connected to AN0 */ /* return 8 bit char from Recieve port */ char getch () { unsigned char c; /* while (!RCIF) */ while (!bittst(PIR1,5)); /* check RCIF bit */ c = RCREG; return(c); } /* send 8 bit char to Recieve port */ void putch (c) char c; { /* wait until transmit reg empty */ /* while (!TXIF) */ while (!bittst(PIR1,4)); /* check RCIF bit */ TXREG = c; } void pcrlf () { putch(0x0a); putch(0x0d); } int update_dac(unsigned char val) { i2c_WriteTo(DAC); i2c_PutByte(0x00); i2c_PutByte(val); i2c_Stop(); } main(void) { int adc_value; char dac_value; char inchar; /* set baud rate */ /* setup Async communication */ bitclr(TXSTA, 6); /* 8-bit transmit */ bitset(TXSTA, 5); /* transmit enable*/ bitclr(TXSTA, 4); /* async mode */ bitset(TXSTA, 2); /* high speed mode */ SPBRG = 95; /* 9600 in high baud rate mode, crystal = 14.7456 Mhz */ bitset(TRISC, 7); /* serial port enable */ bitset(TRISC, 6); /* serial port enable */ bitset(RCSTA, 7); /* serial port enable */ bitclr(RCSTA, 6); /* 8-bit reception */ /* set baud rate */ bitset(RCSTA, 4); /* enable recieve */ /* A/D Setup */ TRISA = 0xFF; /* all bits input */ ADCON1 = 0x8E; /* A0 analog input, others digital,right justification of result */ ADCON0 = 0x80; /* sampling freq = Fsoc/32, channel 0 */ bitset(ADCON0,0); /* turn on ADC*/ printf("ADC is configured!!!"); pcrlf(); /* enable I2C */ SSPCON = 0x28; //Master mode SSPADD = 8; // about 400Khz for 14.7456 Mhz, verified to work //bitset(SSPSTAT,7); //disable slew rate control for 100 Khz bitset(SSPCON,5); //SSPEN = 1; bitset(SSPCON,4); //CKP = 1; bitset(TRISC,3); bitset(TRISC,4); // SDA, SCL pins are inputs printf("Hit any key to start "); pcrlf(); inchar=getch(); for(;;) { bitset(ADCON0, 2); /* start conversion */ while (bittst(ADCON0,2)); /* wait for end of conversion */ /* read result */ adc_value = 0; adc_value = adc_value | (ADRESH << 8); adc_value = adc_value | (ADRESL); printf("%x",adc_value); pcrlf(); dac_value = ((adc_value >> 2)) & 0x00ff; /* now write to DAC */ update_dac(dac_value); } }