我目前正在使用Android手机将我的项目通过蓝牙发送到arduino,当我选择旋转器的项目时我只发送1个字符时没问题。但是,当发送一个字符然后发送一个整数时,它不起作用。 android spinner用于向arduino发送数据:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (btSocket != null) {
switch (position) {
case 0:
msg("In ed!");
break;
case 1:
try {
btSocket.getOutputStream().write("m".toString().getBytes());
btSocket.getOutputStream().write(Integer.toHexString(1).getBytes());
} catch (IOException e) {
msg("Error1");
}
break;
case 2:
try {
btSocket.getOutputStream().write("m".toString().getBytes());
btSocket.getOutputStream().write(Integer.toHexString(2).getBytes());
} catch (IOException e) {
msg("Error2");
}
break;
case 3:
try {
btSocket.getOutputStream().write("m".toString().getBytes());
btSocket.getOutputStream().write(Integer.toHexString(3).getBytes());
} catch (IOException e) {
msg("Error3");
}
}
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// sometimes you need nothing here
}
});
}
arduino代码:
char data; //Variable for storing received data
int blueVal;
void setup()
{
Serial.begin(9600); //Sets the baud for serial data transmission
}
void loop()
{
if(Serial.available() > 0) // Send data only when you receive data:
{
Serial.println("Begin receiving");
data = Serial.read(); //Read the incoming data & store into data
blueVal = Serial.read();
Serial.println(data); //Print Value inside data in Serial monitor
Serial.println(blueVal);
}
}`
微调器选择微调器的第一项时的结果:
Begin receiving
m
-1
Begin receiving
1
-1
arduino收到两次数据和未知的&#39; -1&#39;数据,结果应该是:
Begin receiving
m
1
感谢您的帮助!