Thursday 23 August 2012

AVR Code for ADC conversion from a Water Flow Sensor to LCD16*2





/*
 * Water_Flow_Sensor.c
 *
 * Created: 3/03/2012 5:55:20 PM
 *  Author: Dean
 *
 * Water flow sensor to measure the flow rate from a Proteus flow switch;
 *
 * 0.8 - 9.5 L/min
 * Analogue Input 0 - 5V ADC0
 * POWERTIP PC1602-H LCD 16*2
 *
 * INT0 - RESET BUTTON - resets the MAX and MIN
 *
 * DISPLAY READOUT
 *  ________________
 * |FLOW  3.63 L/MIN|
 * |MIN 2.81MAX 4.93|
 * |________________|
 */


#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>

#include "defines.h"
#include "lcd_lib.h"
#include "a2d.h"

// declared in a2d.h and used to indicate adc interrupt
extern volatile unsigned char a2dCompleteFlag;


// prototypes
void set_display(void);
ISR(INT0_vect); // resets max and min


// globals
volatile u16 gmax = 0; // start at lowest value
volatile u16 gmin = 1024; // start at highest value


int main(void) {

u16 iflow; // holds adc raw data for flow
float fflow; // float conversion of above
char buffer[8]; // reserve memory
char* str = buffer; // string for flow value to LCD


MCUCR |= _BV(ISC01);  // falling edge of INT0
GICR |= _BV(INT0); // enable INT0
LCDinit();
a2dInit();

set_display(); // set all the display static readings
a2dStartConvert();

while(1){
if (a2dCompleteFlag){
iflow = ADCW;
a2dCompleteFlag = FALSE; // set ready for next conversion
a2dStartConvert(); // start ADC

fflow = 0.0093 * (float)iflow;  // 9.5L/min / 1024 = 0.0093

dtostrf(fflow,3,2,str);
LCDGotoXY(5,0);
LCDstring(str);

if (iflow < gmin) { // update max or min if changed
gmin = iflow;
LCDGotoXY(4,1);
LCDstring(str);
} else if(iflow > gmax){
gmax = iflow;
LCDGotoXY(12,1);
LCDstring(str);
}
}
}
}

ISR(INT0_vect){
gmax = 0; // reset max and min
gmin = 1024;
}


void set_display(void){
LCDclr();
LCDcursorOFF();
LCDGotoXY(3,0);
LCDstring("WATER FLOW");
LCDGotoXY(2,1);
LCDstring("SENSOR V1.0");

_delay_ms(1000);
LCDclr();
LCDhome();
LCDstring("FLOW       L/MIN");
LCDGotoXY(0,1);
LCDstring("MIN     MAX");
}

No comments:

Post a Comment