在控制器的核心部分是一块Arduino微控制器,它扫描8个数字引脚和6个模拟引脚(10位),并通过串行发送数据到HC-05蓝牙芯片。然后,安卓手机应读取通过蓝牙发送的串行信息,并将数据包传输到另一部手机,这需要我花费一些时间来实现,因为我对互联网的了解很少,或者分析和解释信息以采取进一步的行动。
我请求的是关于如何最好地完成此任务的见解。那么什么是最好的方式?我希望它是实时的,所以当我按下一个按钮或多个按钮的组合时,安卓手机可以快速地采取行动,人类无法感知延迟。
然后,我希望能够将手机读取的串行缓冲区中的信息与相应的按钮或模拟引脚相关联。以防出现错误或避免它们失去同步。
以下是我目前已有的内容,我还没有测试过这段代码,部分原因是因为我仍在学习如何编写这个项目的安卓部分,另一部分原因是我想得到一些反馈, 以确定是否存在更好的方案。
//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端恢复它呢?
你会如何实现这个功能?有什么见解或建议吗?