我正在使用arduino和appinventor开发一个简单的RPM传感器。我遇到的问题是Android没有收到大于255的整数值或来自Arduino BT的大量垃圾。
arduino的逻辑已经很好了。它在16x2 LCD上正确显示RPM,精度很高。 我也想通过蓝牙将RPM发送到具有appinventor界面的android。它工作但只显示最大值255。即使LCD显示1000+ RPM,在android上总是显示0到255之间。
我尝试使用类型转换(对char,并将其作为文本打印而不成功)。还更改了appinventor上的接收字节数(从1到4个字节)
Arduino的代码:
// include libraries
#include <LiquidCrystal.h>
const int resolution = 500;
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
//hardware global constants;
const int inputPin = 7;
const int ledPin = 13;
//const int bluetoothTx = 9;
//const int bluetoothRx = 8;
//logical variables
int inputState = 0;
int lastPinState;
int counter = 0;
int timeI = 0;
int timeF = 0;
int revolutions;
int cilinderRatio = 2;
int rpm = 0;
char * data = 0;
//---------------------------------------
//BLUETOOTH RESERVED
void setup() {
//set up input Pin and integrated led (pin13)
pinMode(inputPin, INPUT);
pinMode(ledPin, OUTPUT);
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("RPM:");
//Setup Bluetooth Serial Connection to Android
//pinMode(bluetoothTx, OUTPUT);
//pinMode(bluetoothRx, INPUT);
Serial.begin(9600);
}
void loop() {
rpm = 0;
revolutions = 0;
counter = 0;
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
timeI = millis(); //get current running time
do{
//get current state
inputState = digitalRead(inputPin);
//if a pulse occurs, continues
if(inputState == HIGH) {
//if last state is not equal to last state, count it increasing 1
if(lastPinState != inputState)
{
counter += 1;
}
}
lastPinState = inputState; // takes current input State as last state
timeF = millis(); //get final execution time
}while((timeF - timeI) < resolution); //Repeat until reach resolution sample
//lcd.print(counter); //Print how much pulses was counted
// Revolutions is how much resolutions occured in one minute
//since resolution is a seconds fraction, 1000mS * 60S must be
//considered for RPMs
revolutions = counter * (60000 / resolution);
//lcd.print(revolutions); //Print how much turns was counted, in fact
//Revolutions divided by cilinderRatio is equal to RPM
rpm = revolutions / cilinderRatio;
rpm = rpm / 2;
lcd.print(rpm); //Print Revolutions per minute
lcd.print(" ");
Serial.write(rpm);
rpm = 0;
counter = 0;
digitalWrite(ledPin, LOW);
}
P.S。:我已经将接收到的字节更改为2来管理大于255的更好的整数。但是,它显示了很多垃圾超过255.
答案 0 :(得分:1)
我通过分离每个字节来解决问题。
首先,定义了一个2字节类型的数据数组:
byte data[2];
然后在表达式中将rpm的每个字节放在一个字节中:
data[0] = (byte) rpm; //typecast of rpm integer to byte
data[0] = ((byte) rpm >> 8); //typecast and 8-bit shift
答案 1 :(得分:0)
根据Arduino doc on Serial write http://arduino.cc/en/Serial/Write。 Serial.Write一次发送一个字节或一系列字节。因此,您需要将整数RPM转换为数字字符串 使用itoa或类似的东西。
您也可以使用Serial.print()代替直接将整数作为数字发送。