电位器与第二个arduino板的通信状态
communicating state of a potentiometer with a second arduino board
我正在尝试让 arduino 板读取连接到主 arduino 板的电位器的状态,而不用物理电缆将电位器连接到第二块板
我试过使用 Wire.write 和 Wire.read 只传输一个值。
arduino大师代码:
#include <Wire.h>
const int dial = A0;
int reading = 0;
void setup() {
pinMode(dial, INPUT);
Wire.begin();
}
void loop() {
reading = analogRead(dial);
Wire.beginTransmission(9);
Wire.write(reading);
Wire.endTransmission();
}
slave arduino代码:
#include <Wire.h>
int reading = 0;
void setup() {
Wire.begin(9);
Serial.begin(9600);
Wire.onReceive(receiveEvent);
}
void receiveEvent(int bytes) {
reading = Wire.read();
}
void loop() {
Serial.println(reading);
}
当我读取串行监视器时,slave arduino 中的电位器或 "reading" 以 6 个间隔(从 0 到 255,然后下降到 0 和这样做 6 次)。我希望它能在电位器的整个范围内达到 1023 的上限。
你的 ADC 是 10 位的,一个字节都放不下。 (Wire.write(value)
将值作为单个字节发送)。您需要以 2 个字节发送 reading
。下面是如何制作 2 个字节。
byte data1 = highByte(reading);
byte data2 = lowByte(reading);
在接收端,这样重构一个int
。
byte data1 = Wire.read();
byte data2 = Wire.read();
reading = int(data1) << 8 | data2;
我正在尝试让 arduino 板读取连接到主 arduino 板的电位器的状态,而不用物理电缆将电位器连接到第二块板
我试过使用 Wire.write 和 Wire.read 只传输一个值。
arduino大师代码:
#include <Wire.h>
const int dial = A0;
int reading = 0;
void setup() {
pinMode(dial, INPUT);
Wire.begin();
}
void loop() {
reading = analogRead(dial);
Wire.beginTransmission(9);
Wire.write(reading);
Wire.endTransmission();
}
slave arduino代码:
#include <Wire.h>
int reading = 0;
void setup() {
Wire.begin(9);
Serial.begin(9600);
Wire.onReceive(receiveEvent);
}
void receiveEvent(int bytes) {
reading = Wire.read();
}
void loop() {
Serial.println(reading);
}
当我读取串行监视器时,slave arduino 中的电位器或 "reading" 以 6 个间隔(从 0 到 255,然后下降到 0 和这样做 6 次)。我希望它能在电位器的整个范围内达到 1023 的上限。
你的 ADC 是 10 位的,一个字节都放不下。 (Wire.write(value)
将值作为单个字节发送)。您需要以 2 个字节发送 reading
。下面是如何制作 2 个字节。
byte data1 = highByte(reading);
byte data2 = lowByte(reading);
在接收端,这样重构一个int
。
byte data1 = Wire.read();
byte data2 = Wire.read();
reading = int(data1) << 8 | data2;