最近在学习arduino 1.0的代码,关注了一下arduino reference里的几个function的实现。
能看懂大概的意思,想继续深入研究,但是对arduino硬件和软件接口的知识不了解。
比如analogRead函数的实现,首先是给ADMUX赋值。对328p来说,ADMUX实际上就是0x7c。
为什么要给0x7c赋值呢,为什么要赋值为(1 << 6) | (pin & 0x07)呢?
这部分知识属于“硬件和软件接口”的知识,如果能知道这部分知识,不需要参考别人的代码,
完全可以自己写一个analogRead函数出来。
请问怎么样获取这些知识呢?
希望大侠们解惑,谢谢。
int analogRead(uint8_t pin)
{
uint8_t low, high;
// set the analog reference (high two bits of ADMUX) and select the
// channel (low 4 bits). this also sets ADLAR (left-adjust result)
// to 0 (the default).
// ADMUX = (analog_reference << 6) | (pin & 0x07);
ADMUX = (1 << 6) | (pin & 0x07);
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
// the MUX5 bit of ADCSRB selects whether we're reading from channels
// 0 to 7 (MUX5 low) or 8 to 15 (MUX5 high).
ADCSRB = (ADCSRB & ~(1 << MUX5)) | (((pin >> 3) & 0x01) << MUX5);
#endif
// without a delay, we seem to read from the wrong channel
//delay(1);
// start the conversion
sbi(ADCSRA, ADSC);
// ADSC is cleared when the conversion finishes
while (bit_is_set(ADCSRA, ADSC));
// we have to read ADCL first; doing so locks both ADCL
// and ADCH until ADCH is read. reading ADCL second would
// cause the results of each conversion to be discarded,
// as ADCL and ADCH would be locked when it completed.
low = ADCL;
high = ADCH;
// combine the two bytes
return (high << 8) | low;
} |