#define F_CPU 16000000UL
#include <avr/io.h>
#include <util/delay.h>
#include <string.h>
#include <math.h>
#include <stdio.h>
#define LCD_Port PORTD //Definir LCD Port (PORTC, PORTD) como entrada
#define LCD_DPin DDRD //Definir Pins (PD4-PD7) como salida
#define RSPIN PD2
#define ENPIN PD3
void LCD_Action( unsigned char cmnd );
void LCD_Init (void);
void LCD_Clear();
void LCD_Print (const char *str);
void LCD_Printpos (char row, char pos, char *str);
float x = 0;
unsigned char xchar;
void LCD_Init (void)
{
LCD_DPin = 0xFF; //Controlar Pins (D4-D7)
_delay_ms(15);
LCD_Action(0x02);
LCD_Action(0x28);
LCD_Action(0x0c);
LCD_Action(0x06);
LCD_Action(0x01);
_delay_ms(2);
}
void LCD_Action( unsigned char cmnd )
{
LCD_Port = (LCD_Port & 0x0F) | (cmnd & 0xF0);
LCD_Port &= ~ (1<<RSPIN);
LCD_Port |= (1<<ENPIN);
_delay_us(1);
LCD_Port &= ~ (1<<ENPIN);
_delay_us(200);
LCD_Port = (LCD_Port & 0x0F) | (cmnd << 4);
LCD_Port |= (1<<ENPIN);
_delay_us(1);
LCD_Port &= ~ (1<<ENPIN);
_delay_ms(2);
}
void LCD_Clear()
{
LCD_Action (0x01);
_delay_ms(2);
LCD_Action (0x80);
}
void LCD_Print (const char *str)
{
int i;
for(i=0; str[i]!=0; i++)
{
LCD_Port = (LCD_Port & 0x0F) | (str[i] & 0xF0);
LCD_Port |= (1<<RSPIN);
LCD_Port|= (1<<ENPIN);
_delay_us(1);
LCD_Port &= ~ (1<<ENPIN);
_delay_us(200);
LCD_Port = (LCD_Port & 0x0F) | (str[i] << 4);
LCD_Port |= (1<<ENPIN);
_delay_us(1);
LCD_Port &= ~ (1<<ENPIN);
_delay_ms(2);
}
}
void LCD_Printpos (char row, char pos, char *str)
{
if (row == 0 && pos<16)
LCD_Action((pos & 0x0F)|0x80);
else if (row == 1 && pos<16)
LCD_Action((pos & 0x0F)|0xC0);
LCD_Print(str);
}
int main()
{
float n;
LCD_Clear();
LCD_Init(); //ActivaR Pantalla LCD
LCD_Print(" Voltimetro");
DDRC = 0; // puerto 0 entrada del ADC
ADCSRA= 0x8F;
ADMUX= 0x40;
ADCSRA|=(1<<ADSC); // Inicia la conversion
while (1){
ADCSRA|=(1<<ADSC); //inicia la conversion
while((ADCSRA&(1<<ADIF))==0); // espera a que termine la conversion
n = ADC&1023;
LCD_Action (0x80);
LCD_Print(" Voltimetro");
x =n*0.00488; // 4.49
char string[]="";
LCD_Action (0xC0);
sprintf(string, "%d", (int)x); // 4
LCD_Print(string);
sprintf(string, ".");
LCD_Print(string);
sprintf(string, "%d", ((int)(x*100)%100));
LCD_Print(string);
}
}
void reverse(char* str, int len)
{
int i = 0, j = len - 1, temp;
while (i < j) {
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
}
int intToStr(int x, char str[], int d)
{
int i = 0;
while (x) {
str[i++] = (x % 10) + '0';
x = x / 10;
}
while (i < d)
str[i++] = '0';
reverse(str, i);
str[i] = '\0';
return i;
}
void ftoa(float n, char* res, int afterpoint)
{
int ipart = (int)n;
float fpart = n - (float)ipart;
int i = intToStr(ipart, res, 0);
if (afterpoint != 0) {
res[i] = '.'; // add dot
fpart = fpart * pow(10, afterpoint);
intToStr((int)fpart, res + i + 1, afterpoint);
}
}