Atmega328 模数转换器

Atmega328 Analog-to-Digital Converter

我正在努力了解 ADC 与 arduino 和带有按钮的 LCD 屏蔽。我喜欢在 Atmel Studio 工作,并通过研究和数据表编写自己的库。我的目标是将 ADC 值写入屏幕。如果我使用 analogRead() 函数编写 Arduino Sketch,它可以工作,但我无法使用我的 Atmel Studio 程序让它读取 LCDw 上的任何内容。 LCD 确实可以工作,因为我可以在 LCD 上写其他信息。我的程序如下。任何想法都会有帮助。谢谢!!!

模拟表头

 #include<util/delay.h>

 void adc_init(void)
 {
     ADMUX = (1<<REFS0);     //select AVCC as reference
     ADCSRA = (1<<ADEN) | 7;  //enable (ADEN) and prescale = 128 (16MHz/128 = 125kHz)
 }

 int readAdc(char chan)
 {
     ADMUX = (1<<REFS0) | (chan & 0x0f);  //select ref (REFS0) and channel
     ADCSRA |= (1<<ADSC);                 //start the conversion
     while (ADCSRA & (1<<ADSC));          //wait for end of conversion
     return ADC;                            //Return 16 Bit Reading Register
 }

主程序

 #ifndef F_CPU
 #define F_CPU 16000000UL // 16 MHz clock speed
 #endif


 #define D4 eS_PORTD4
 #define D5 eS_PORTD5
 #define D6 eS_PORTD6
 #define D7 eS_PORTD7
 #define RS eS_PORTB0
 #define EN eS_PORTB1

 #include <avr/io.h>
 #include <util/delay.h>
 #include <stdio.h>
 #include "lcd328.h"
 #include "myHeader328.h"

 /*--------------------------------------------------------
 -- initScreen() initializes the screen
 --------------------------------------------------------*/
 void initScreen()
 {
     Lcd4_Init();  //Initialize Screen
     Lcd4_Clear();  //Clear Screen
     Lcd4_Set_Cursor(1,0);
     Lcd4_Write_String("Count:0");
 }

 /*--------------------------------------------------------
 -- refreshScreen() refreshed the screen
 --------------------------------------------------------*/
 void refreshScreen(int count2)
 {
     char countStr[5];
     sprintf(countStr, "%i", count2);
     Lcd4_Set_Cursor(1,6);
     Lcd4_Write_String(countStr);
     _delay_ms(50);
 }

 /*--------------------------------------------------------
 -- main()
 --------------------------------------------------------*/

 int main(void)
 {
     DDRD = 0xFF;
     DDRB = 0xFF;
     DDRC = 0x00;
     initScreen();
     PORTB = PORTB | (1<<PORTB2);  //Turn on backlight
     int adcOut = 4;
     while(1)
     {
         adcOut = readAdc(0);
         refreshScreen(adcOut);
         _delay_ms(500);

     }
 }

您必须在主循环中调用 adc_init()

/*--------------------------------------------------------
 -- main()
 --------------------------------------------------------*/

 int main(void)
 {
     DDRD = 0xFF;
     DDRB = 0xFF;
     DDRC = 0x00;
     initScreen();
     adc_init();       //!!!!!
     PORTB = PORTB | (1<<PORTB2);  //Turn on backlight
     int adcOut = 4;
     while(1)
     {
         adcOut = readAdc(0);
         refreshScreen(adcOut);
         _delay_ms(500);

     }
 }