这是一个项目的开始,我遇到了一个问题。现在,我的应用程序只做两件事。检测并连接到特定的SparkFun蓝牙模块/sheild,该模块由Arduino控制。这个很好用。
它应该做的另一件事(但不是),是打开/关闭由Arduino控制的LED灯。我将在下面布局代码和一些日志。
Arduino Sketch
char Incoming_value = 0; //Variable for storing Incoming_value
const int pwmPin = 13;
void setup()
{
Serial.begin(9600); //Sets the data rate in bits per second (baud) for serial data
transmission
pinMode(pwmPin, OUTPUT); //Sets digital pin 13 as output pin
}
void loop()
{
if(Serial.available() > 0)
{
Incoming_value = Serial.read(); //Read incoming data, store it into variable Incoming_value
Serial.print(Incoming_value); //Print Value of Incoming_value in Serial monitor
Serial.print("\n"); //New line
if(Incoming_value == '1') //Checks whether value of Incoming_value is equal to 1
digitalWrite(pwmPin, HIGH); //If value is 1 then LED turns ON
else if(Incoming_value == '0') //Checks whether value of Incoming_value is equal to 0
digitalWrite(pwmPin, LOW); //If value is 0 then LED turns OFF
}
}我不使用仿真器。这是在手机上测试的。下面是相关的代码。提醒,这是用科特林写的。
MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
...........
<snip>
...........
button_led_on.setOnClickListener { sendCommand("1")}
button_led_off.setOnClickListener { sendCommand("0")}
}
private fun sendCommand(input: String) {
if (bluetoothSocket != null) {
try {
bluetoothSocket!!.outputStream.write(input.toByteArray())
Log.i(LOGTAG, "Button clicked, info sent: $input")
} catch (e: IOException) {
e.printStackTrace()
}
}
}如前所述,一切都很好地编译和运行。蓝牙部分工作,按钮所有的工作,似乎是他们应该工作。
单击应用程序中的“led on”或“led”按钮在日志中显示如下内容
Logcat
2019-09-24 09:47:15.891 9403-9403/com.example.Picatcher D/MainActivity:按下按钮,信息发送:1
2019-09-24 09:47:24.975 9403-9403/com.example.Picatcher D/MainActivity:按下按钮,信息发送:0
阿迪诺那边什么都没发生。看看Arduino上的串行监视器,我只看到当我点击应用程序中的“led”按钮时才会看到下面的内容。单击“引导”按钮时,什么都不会显示。
09:47:24.994 -> 255
我觉得我在Arduino...but上没有正确配置的东西,我不知道那可能是什么。我试过其他几个帖子中建议的不同的引脚,但这也不起作用。
发布于 2019-09-25 01:24:43
草图看上去不错,Android逻辑看起来也不错。假设您的连接在蓝牙模块和Arduino之间是可靠的,并且您是成对的,那么我将排除您通过蓝牙套接字发送的确切内容。我找到了一些与您的项目一模一样的源代码,尽管是用Java:https://github.com/Mayoogh/Arduino-Bluetooth-Basic/blob/master/LED-master/app/src/main/java/com/led_on_off/led/ledControl.java编写的。
我将验证您是否正确地进行了蓝牙连接,并且您发送的数据是正确的。我注意到您记录的内容与实际发送的内容不同(在Android上)。我还注意到了一些关于设置SPP的内容,不确定这是什么,但这听起来很重要。
发布于 2019-09-30 21:41:06
拔了很多头发之后。我终于发现问题不在于我的Kotling代码或Arduino代码。问题是我用的蓝牙屏蔽。
我不知道为什么,但是用另一个替换它,不做任何代码更改,它都开始像预期的那样工作。
https://stackoverflow.com/questions/58085285
复制相似问题