| avjarun 
 
 
 Joined: 28 Mar 2021
 Posts: 13
 
 
 
			    
 
 | 
			
				| DAC - COMPARATOR HELP |  
				|  Posted: Tue Jul 08, 2025 6:34 am |   |  
				| 
 |  
				| Hello all. 
 I am trying to trigger an Interrupt using comparator, but struggling with the code as the interrupt never triggers.
 Have an ADC INPUT on RA2 - Connected to Analog Hall Effect Sensor that varies between analog value 132 to 135 and I would like have that as an interrupt.
 Can someone advice if what I think can be implemented and if yes, where am I am wrong. Pls point me in the right direction.
 
 
 
  	  | Code: |  	  | 
 #include <16F18325.h>
 #include <stdio.h>
 #fuses RSTOSC_HFINTRC_PLL,NOBROWNOUT,NOWDT,MCLR,PUT
 #use delay(clock=32000000)
 #use i2c(Master, SDA=PIN_C0, SCL=PIN_C1, slow=100000, FORCE_SW, stream=SSD1306_STREAM)
 
 #define SSD1306_ADDRESS 0x78
 #define SSD1306_128_32
 
 
 #include <SSD1306OLED.c>
 
 unsigned long pulse_count = 0;
 unsigned long counter = 0;
 unsigned long lcounter = 0;
 
 #bit C1OUT = getenv("SFR:CM1CON0").6  // Comparator 1 output
 
 #byte PORTA = 0x00C
 #byte PORTC = 0x00E
 
 
 #bit LED = PORTA.5
 #bit LEDACT = PORTA.4
 #bit EON=PORTC.2
 
 
 char text[10];
 byte adcValue;
 
 int previous_state = 0; // 0 = below threshold, 1 = above
 int16 threshold = 133;
 
 
 #INT_COMP
 void comp_isr() {
 
 LEDACT=!LEDACT;
 
 if (C1OUT) {
 counter++;
 LED = !LED;
 }
 }
 
 
 void ssd1306_init() {
 // Initialize SSD1306 for 128x32 display
 SSD1306_Begin(SSD1306_SWITCHCAPVCC, SSD1306_ADDRESS);
 
 SSD1306_Display(); // Update display
 }
 
 
 void showCounter(){
 sprintf(text, "%06lu", counter); // Format as 5 digits
 SSD1306_DrawText(26, 10, text, 2);
 SSD1306_Display();
 
 }
 
 void main() {
 
 set_tris_a(0b001100);
 set_tris_c(0b001011);
 
 setup_adc_ports(NO_ANALOGS);
 
 
 
 EON=1;
 LED = 1;
 LEDACT=0;
 delay_ms(1000);
 
 ssd1306_init();  // Initialize OLED
 ssd1306_ClearDisplay(); // Clear screen
 showCounter();
 
 LED = 0;
 
 
 setup_dac(DAC_VSS_VDD);
 dac_write(132);  // DAC as reference
 
 
 setup_adc_ports(sAN2);
 setup_comparator(CP1_C3_DAC | CP1_INT_L2H | CP1_HYST);
 
 clear_interrupt(INT_COMP);
 enable_interrupts(INT_COMP);
 enable_interrupts(PERIPH);
 enable_interrupts(GLOBAL);
 
 while (TRUE) {
 
 
 if (lcounter != counter) {
 showCounter();
 lcounter = counter;
 }
 
 
 
 
 }
 }
 | 
 |  | 
	
		| Ttelmah 
 
 
 Joined: 11 Mar 2010
 Posts: 19967
 
 
 
			    
 
 | 
			
				|  |  
				|  Posted: Tue Jul 08, 2025 7:12 am |   |  
				| 
 |  
				| Key thing. the DAC only offers 32 levels. 0-31. These have 1/32 the supply for each step. You don't tell us what '132' to '135' 'represents?. Counts of
 the ADC?. In 8 bit or 10 bit mode if so?.
 
 However this would be in DAC counts:
 For 8bit adc, 16 counts.
 For 10 bit, just 4 counts.
 and of course the variation would have to be a lot more than just 3 ADC counts
 for this to be even remotely useable.....
 
 Look at figure 24-1 in the dats sheet.
 |  |