刚才,我碰巧有过于复杂的类型转换(我仍然不完全理解它们的类型)
我通过串行链接将0到1024个值从Arduino传输到4个字节(int)。很快我就意识到我也可以发短路(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位数的显示来检查大约的值。)
答案 0 :(得分:0)
htons()
将s
horts从h
ost endianness to
n
etwork endianness(htons
:举办网络短片)。ByteArrayOutputStream
;获得所有数据后,将此ByteArrayOutputStream
的基础字节数组包装到ByteBuffer
。ByteBuffer
的{{1}}。