Atmega16 v2
Atmega16 v2
Atmega16 v2
h>
#include <alcd.h>
#include <delay.h>
#define POT_CHANNEL 7
#define LDR_CHANNEL 0
// global variables
int pot_value = 0;
int ldr_value = 0;
// function prototypes
void read_pot();
void read_ldr();
void display_keypad();
// main function
void main(void) {
// initialize ADC
ADCSRA |= (1 << ADEN); // enable ADC
ADCSRA |= (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0); // set ADC prescaler to 128
// initialize LCD
lcd_init(20);
// initialize keypad
KEYPAD_DDR |= 0x0F; // set columns as output and rows as input
KEYPAD_PORT |= 0xF0; // enable pull-up resistors on rows
// main loop
while (1) {
read_pot();
read_ldr();
display_keypad();
}
}
void init_adc() {
// Set ADC reference voltage to AVCC
ADMUX |= (1 << REFS0);
// Set ADC result to right-adjusted
ADMUX &= ~(1 << ADLAR);
// Enable ADC and set prescaler to 128
ADCSRA |= (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0);
}
char read_keypad() {
// Initialize keypad pins
keypad_ddr = keypad_row_pins | keypad_col_pins;
keypad_port = keypad_row_pins | keypad_col_pins;
void main() {
// Initialize ADC and LCD
init_adc();
lcd_init(20);
lcd_clear();
lcd_gotoxy(0, 0);
lcd_puts("Keypad input:");
while (1) {
// Read input from keypad
char keypad_key = read_keypad();
void init_adc()
{
ADMUX=(1<<REFS0);
ADCSRA=(1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
}
char keypad_get_key()
{
int r, c;
for (r=0; r<4; r++)
{
KEYPAD_PORT = (1 << (r+4));
for (c=0; c<4; c++)
{
if (!(KEYPAD_PIN & (1 << c)))
{
return (r*4+c+1);
}
}
}
return 0;
}
void lcd_show_keypad()
{
lcd_clear();
lcd_puts("Keypad:");
while (1)
{
char key = keypad_get_key();
if (key != 0)
{
lcd_gotoxy(0, 1);
lcd_putc(' ');
lcd_putc(key + '0');
delay_ms(500);
}
}
}
void lcd_show_adc7()
{
char buf[16];
lcd_clear();
while (1)
{
int val = read_adc(7);
lcd_gotoxy(0, 0);
sprintf(buf, "ADC7: %4d", val);
lcd_puts(buf);
delay_ms(500);
}
}
void lcd_show_adc0()
{
char buf[16];
lcd_clear();
while (1)
{
int val = read_adc(0);
lcd_gotoxy(0, 0);
sprintf(buf, "ADC0: %4d", val);
lcd_puts(buf);
delay_ms(500);
}
}
void lcd_show_ldr()
{
char buf[16];
lcd_clear();
while (1)
{
int val = read_adc(0);
float ldr_resistance = (float)val / 1024 * 5000 / val;
lcd_gotoxy(0, 0);
sprintf(buf, "LDR: %.2f Ohm", ldr_resistance);
lcd_puts(buf);
delay_ms(500);
}
}
int main(void)
{
lcd_init(20);
KEYPAD_DDR |= 0x0F;
KEYPAD_PORT |= 0xF0;
init_adc();
while (1)
{
char key = keypad_get_key();
switch (key)
{
case 'A':
lcd_show_adc7();
break;
case 'B':
lcd_show_adc7();
break;
case 'C':
lcd_show_ldr();
break;
case 'D':
lcd_show_keypad();
break;
}
}
}