刚才,我碰巧有过复杂的类型转换(我仍然不能完全理解它们的类型)。
我通过串行链接将 0 - 1024 个值作为 4 个字节(int)从 Arduino 传输到处理。很快我意识到我也可以发送短消息(2 个字节)来获得 2 倍的通信速度(而且我需要它非常快)。
所以这就是我在 arduino 上的 C++ 中所拥有的:
// variable to store the value coming from the sensor
unsigned short sensorValue = 0;
//Time when I last sent the buffer (serial link seems to need some rest)
unsigned long last_time_sent = millis();
//Buffer to save data I've collected
byte buffer[256];
//Position in buffer
byte buffer_pos = 0;
while(1) {
//Get 0 - 1024
sensorValue = analogRead(sensorPin);
//(Try to) convert Short to two bytes. I don't even which is first and which is last
for(byte i=0; i<2; i++) {
//Some veird bit-shifting, all saved in buffer with an offset
buffer[i+buffer_pos] = (byte)(sensorValue >> ((2-i) * 8));
}
//Iterate buffer position
buffer_pos+=2;
//Currently, I send the data allways
if(true||millis()-last_time_sent>30||buffer_pos+2>=255)
Serial.write(buffer, buffer_pos);
//Temporary delay for serial link to rest
delay(50);
}
现在,在 Processing 中,java 代码如下所示:
void serialEvent(Serial uselessParameter) {
while (myPort.available() >= 2) {
//java doesn't allow unsigned variables
short number = 0;
for(byte i=0; i<2; i++) {
byte received = (byte)myPort.read();
println("Byte received: "+Integer.toString((int)received));
number |= myPort.read() << (2-i)*8;
}
//Save data for further rendering
graph.add(number); //Array of integers, java doesn't let me make array of short
}
//Clean old data
while(graph.size()>MAX_GRAPH_SIZE)
graph.remove(0);
}
我认为我在 arduino 方面出了点问题,因为我在输出中看到了这一点:
收到的字节:0
收到的字节:-1
结果 2 字节数:-256
Arduino 应该发送大约 681 的值。(我有一个 1 位显示器来大致检查这些值)。