【发布时间】:2019-09-28 20:12:55
【问题描述】:
我正在尝试使用 attiny85 中的 ADC 读取模拟电压。但是无论给出什么输入,ADC 寄存器总是读取 1023。
此外,当用万用表测量 ADC 引脚时,它显示接近 3.1V。我以为它被拉高了,但事实是,当我将引脚连接到其模拟输入时,引脚上的电压会干扰输入电压电路。我不知道为什么会这样。相同的代码在 6 个月前运行良好,但现在不行了。原因不明。谁能解释我实际上做错了什么?我使用 USBasp 作为我的程序员,使用 attiny85 作为我的目标微控制器,使用 arduino 作为我的编译器。我也尝试使用 WinAVR 进行编译,但模拟输入引脚的电压仍然接近 3.1V。 在此先感谢:)
#define F_CPU 16000000UL
#define myTx PB1 //PB1
#define myRx PB0 //PB0
#define ADC_CH_2 PB4
#define ADC_CH_3 PB3
#include <SoftwareSerial.h>
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
float ADCval;
int i = 0, p;
SoftwareSerial myPort(myRx, myTx); //rx,tx
ISR(ADC_vect) {
p = ADCW;
ADCval = (float)p * 5.00f / 1024.0f;
//logging the data
myPort.print(i++);
myPort.print(" ADC: ");
myPort.print(p);
myPort.print(" voltage: ");
myPort.println(ADCval);
}
int main(void) {
myPort.begin(9600);
MCUCR &= ~(1 << PUD); //disabling Pull Up Disable i.e, enabling pullups
//I/O configuration
DDRB &= ~(1 << ADC_CH_2) & ~(1 << ADC_CH_3); //configuring as input
PORTB |= (1 << ADC_CH_2) | (1 << ADC_CH_3); // writing 1 to an input pin activates pullup-resistor
DIDR0 |= (1 << ADC_CH_2) | (1 << ADC_CH_3); // disable digital buffer
myPort.print("DDRB: ");
myPort.println(DDRB);
myPort.print("PORTB: ");
myPort.println(PORTB);
//ADC configuration
ADCSRA |= (1 << ADEN); //enable ADC
ADCSRA |= (1 << ADIE); //enable conversion complete interrupt
ADCSRA |= (1 << ADPS0) | (1 << ADPS1) | (1 << ADPS2); // prescaler 128 - 16000000/128=125khz;
myPort.print("ADCSRA: ");
myPort.println(ADCSRA);
ADMUX &= ~(1 << ADLAR); // right most shift in ADCH and ADCL i.e, ADCH has two MSB bits and ADCL has 8 LSB bits
ADMUX |= (1 << REFS1) | (1 << REFS2); ADMUX &= ~(1 << REFS0); //Vref as 2.56V
ADMUX |= (1 << MUX1) | (1 << MUX0) ; ADMUX &= ~(1 << MUX2) & ~(1 << MUX3); //adc3
sei(); // enable all interrupts
myPort.print("ADMUX: ");
myPort.println(ADMUX);
while (1)
{
_delay_ms(1000);
ADCSRA |= 1 << ADSC;
myPort.print("DDRB: ");
myPort.println(DDRB);
myPort.print("ADMUX: ");
myPort.println(ADMUX);
myPort.print("ADCSRA: ");
myPort.println(ADCSRA);
myPort.print("PORTB: ");
myPort.println(PORTB);
}
return 0;
}
更新
下图描述了我在相同输入电压下不同 ADC 通道的输出。
【问题讨论】:
-
我正在调查该代码,但我想问一下,可以吗? ADMUX &= ~(1
-
ISR 中的浮点运算和串行数据记录充其量是不明智的。
-
@dunajski 实际上变量 temp 是 ADMUX。在这里输入代码时我忘了更改它。
-
有一条法律,当你问一些事情时,有人只回答一个问题:-)。我问的其他问题怎么样,然后我认为你应该编辑你的帖子,让他在没有这些错误的情况下回答更“有吸引力”。
-
我很抱歉@dunajski,我将对其进行编辑并重新发布。谢谢你纠正我。
标签: arduino embedded avr attiny winavr