我目前正在尝试设计一个可以通过蓝牙与安卓手机(Galaxy Nexus)通信的控制器。我面临着一些挑战。另外,我没有太多实际的编程经验。
控制器的核心是一个 Arduino 微控制器,它扫描 8 个数字引脚和 6 个模拟引脚(10 位)的状态,并通过串行将数据发送到 HC-05 蓝牙芯片。然后,安卓手机应该读取通过蓝牙发送的串行信息,然后将数据包传输到另一部手机——这需要我一段时间来实现,因为我对互联网的工作原理知之甚少——或者分析和解释它以采取进一步行动采取
我所要求的是有关执行此操作的最佳方法的见解。现在最好是什么意思?我们希望它是实时的,所以当我按下按钮或底部组合时,Android 手机会以足够快的速度采取行动,人类不会察觉到延迟。
然后我希望能够将手机在串行缓冲区中读取的信息与相应的按钮或模拟引脚相关联。万一出现错误或避免它们不同步
这是我到目前为止所拥有的。我还没有测试过这段代码,部分原因是我仍在学习如何编程这个项目的android部分,部分原因是我想要一些关于我是否愚蠢的反馈,或者这实际上是一种有效的方式去做这个:
//Initialization
/*
This Program has three functions:
1) Scan 8 digital pins and compile their state in a single byte ( 8 bits)
2) Scans 6 Analogue inputs corresponding to the joysticks and triggers
3) Send this info as packets through seril --> Bluetooth
*/
#include <SoftwareSerial.h>// import the serial software library
#define A = 2
#define B = 3
#define X = 4
#define Y = 5
#define LB = 6
#define RB = 7
#define LJ = 8
#define RJ = 9
#define RX = 10
#define TX = 11
//Pin 12 and 13 are unused for now
SoftwareSerial Bluetooth(RX,TX); //Setup software serial using the defined constants
// declare other variables
byte state = B00000000
void setup() {
//Setup code here, to run once:
//Setup all digital pin inputs
pinMode(A,INPUT);
pinMode(B,INPUT);
pinMode(X,INPUT);
pinMode(Y,INPUT);
pinMode(LB,INPUT);
pinMode(RB,INPUT);
pinMode(LJ,INPUT);
pinMode(RJ,INPUT);
//Setup all analogue pin inputs
//setup serial bus and send validation message
Bluetooth.begin(9600);
Bluetooth.println("The controller has successfuly connected to the phone")
}
void loop() {
//Main code here, to run repeatedly:
//Loop to sum digital inputs in a byte, left shift the byte every time by 1 and add that if the pin is high
for(byte pin = 2, b = B00000001; pin < 10; pin++, b = b << 1){ if (digitalRead(pin)== HIGH) state += b; }
//Send digital state byte to serial
Bluetooth.write(state);
//Loop to read analgue pin 0 to 5 and send it to serial
for( int pin = 0, testByte = 0x8000; pin < 6 ; pin++, testByte = testByte >> 1) { Bluetooth.write(analogRead(pin)+testByte); }
}
//Adding some validation would be wise. How would I go about doing that?
// Could add a binary value of 1000_0000_0000_0000, 0100_0000_0000_0000, 0010_0000_0000_0000 ... so on and then use a simple AND statement at the other end to veryfy what analogue reading the info came from
// so say the value for analgue is 1023 and came from analgue pin 1 I would have 0100_0011_1111_1111 now using an bitwise && I could check it against 0100_0000_0000_0000 if the result is 0100_0000_0000_0000 then I know this is the analogu reading from pin 1
//could easily implement a test loop with a shiting bit on the android side
我做这样的位移是没有意义的吗?最终,如果我没记错的话,所有数据都以字节(8 位数据包)发送,那么Bluetooth.write(analogRead(pin)+testByte)
实际发送两个字节还是截断int
数据?它将如何分解,我如何在 android 端恢复它?
您将如何实施?有什么见解或建议吗?