I'am working with arduino and ADK und I have problems to get Information from Arduino-Sensors. At the moment I can send Information from Phone to control LED or servos.... . But it is impossible for me to send Data via acc.write(msg,3) to smarthphone. I'am using this example Dev-O-Rama and try to extend this example to get sensor data(without success). To get sensordata I'am using code from ADK example. Everytime when I try to send data from arduino with: acc.write(msg,3) it seems everything freezing. Have someone a working "little" example or a hint what can cause this behavior?
LG Marcel
I figure it's the Android application that's freezing?
Try using the USBControl library in my project
The arduino write code is very simple:
//Batt update, 0.1 Hz loop
if (acc.isConnected() && millis()-timer_batt >= 1000/BATT_FREQ) {
timer_batt = millis();
//Serial.print("b");
msg[0] = SYNC;
msg[1] = BATTERY_LEVEL;
msg[2] = getBatt();
acc.write(msg, 3);
}
Make sure you're limiting the writing frequency, and reading quickly enough on both sides. There's a strange behaviour where the connection will appear to hang if there's too much data being buffered.
It's hard to say what to do without knowing what kind of data you are sending. Basically you have to make sure use the acc.write() method with the correct parameters. The first one is the byte array itself and the second one is the number of bytes in the array. So if your byte array is 5 bytes in size you need to call it like that: acc.write(msg, 5).
It is even better to make it more dynamic by using the sizeof Arduino function:
acc.write(msg, sizeof(msg));
Related
This is my first question ever asked on this board
The project explained short:
5 sensors, connected with an esp32 board are transmitting 1000 samples/second, each sample has 16 bit. Those values should be transmitted via BLE (With the BLE Arduino library and an ESP32). The connected device (Smartphone) should read those values and do something with them (Also via BLE, with the following library: https://github.com/RobotPajamas/Blueteeth). The ESP32 is the Server! Java is used in Android Studio!
The problem:
While testing the BLE connection a simple "hello world" was transmitted as the value for a characteristic. Every time i received the "hello world" on the android-device-side, a variable was incremented: The problem is, the variable only got incremented 4 times in one second. This means (assuming 1 char in a string equals 1 byte) 11byte*4(1/s)=44byte/s are being transmitted. -> This clearly is not enough (should not BLE transmit ~2MBit/s (minus the protocol-data))
Code Fragments
ESP32: BLE-Server that transmits value
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b"
#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8"
class MyCallbacks: public BLECharacteristicCallbacks {
void onWrite(BLECharacteristic *pCharacteristic) {
std::string value = pCharacteristic->getValue();
if (value.length() > 0) {
Serial.println("*********");
Serial.print("New value: ");
for (int i = 0; i < value.length(); i++)
Serial.print(value[i]);
Serial.println();
Serial.println("*********");
}
}
};
void setup() {
Serial.begin(115200);
BLEDevice::init("MyESP32");
BLEServer *pServer = BLEDevice::createServer();
BLEService *pService = pServer->createService(SERVICE_UUID);
BLECharacteristic *pCharacteristic = pService->createCharacteristic(
CHARACTERISTIC_UUID,
BLECharacteristic::PROPERTY_READ |
BLECharacteristic::PROPERTY_WRITE
);
pCharacteristic->setCallbacks(new MyCallbacks());
pCharacteristic->setValue("Hello World");
pService->start();
BLEAdvertising *pAdvertising = pServer->getAdvertising();
pAdvertising->start();
}
void loop() {
// put your main code here, to run repeatedly:
delay(2000);
}
Android Studio Code (Snippet of the receiving source):
try
{
while(sampleBluetoothData)
{
this.selectedDevice.readCharacteristic(MainActivity.characteristicUUID, MainActivity.serviceUUID, (response, data) ->
{
if (response != BlueteethResponse.NO_ERROR) {
return;
}
Log.d("AUSGANG", new String(data) + "times: "+ i);
i++;
});
}
}
catch (Exception e)
{
e.printStackTrace();
}
The write on the ESP32 side is a blank example code of the Arduino IDE, the read on the Android-side is made by the BLE-Library publisher. Yes the Log.d effects the performance, but it does not drop it that much.
The variable "data" of the Android code is the received char-array. The bluetooth-reading runs on a background thread.
Question I ask myself now:
Is the Android-Studio library the problem or the Arduino library
Is this a normal behaviour, that if a value of a characteristic does not change, it is being transmitted quite slowly.
How fast can you update a value of a characteristic
Thank you in advance!
BLE can definitely transfer much more than 4 portions of 11 bytes per second.
Approach of reading:
Generally, continuos reading all the time is NOT the expected BLE way - it's better to subscribe to data changes, so ESP32 will notify only when needed (e.g. do selectedDevice.subscribeToCharacteristic once, instead of reading in a loop, but then ESP32 code should be changed accordingly)
I guess selectedDevice.readCharacteristic requests asynchronous BLE read, and when you call it in while(sampleBluetoothData), your Bluetooth library is adding more and more read requests. Maybe it would be wise to request new read only after the previous read is done - in read callback add if(sampleBluetoothData) { this.readAgain(); }
Consider making a testing prototype from this kickstart example: BLEProof on github - Android & ESP32, read, write, notify (but it uses just system API without Bluetooth library, you approach is better, it's easier and safer to use the library).
What else to check:
Android side: are you sure that your code doesn't go inside of if (response != BlueteethResponse.NO_ERROR) ?
Android side: to ensure Bluetooth library is not overloaded with read requests, try adding a delay 50 milliseconds in the reading loop (just to check, it's not a solution)
Android side: are you sure that you don't have other BLE read/writes while you read those data?
ESP32 side: use shorter BLE connection interval (BLE throughput article) - add pAdvertising->setMinPreferred(0x06); and pAdvertising->setMaxPreferred(0x20); before pAdvertising->start(); (but that sets only "preferred" interval, Android may ignore that)
Using read requests, you are mainly limited by the connection interval for transfer speeds - that is 2 intervals for request + response.
If for example your client has a connection interval of 50ms, you should expect to read a characteristic of up to 20 bytes 10 times per second.
If another client has a connection interval of 30ms, this rate improves to 16.6 reads per second.
The fastest negotiatiable connection interval is 7.5ms for a maximum of 66.6 reads per second (10.7kbps with 20 byte reads).
I was reading BLE wikipedia page and the minimum data rate is 125Kbit/s , so I think that in your case is viable, because you only will transmit 16Kbit/s. Take a look in BLE wikipedia.
I have spent much time trying to find out where is my mistakes while Im flashing the PIC16F688. The Pic has successfully flashed using PicKit2. Im using the Pic to convert analog pressure sensor to digital output and sending the data via Bluetooth, but the Bluetooth is not receiving stable numbers of data. The data is consist of 4 character decimal number that is between 0 and 1023.
The problem is that the Bluetooth can't wait at specific number and keep reading it, instead, it is reading the 4 digits in random.
I think my mistake is within the configuration of internal oscillator.
I'm attaching my code, the code is written to configure the flexiforce sensor circuit that outputs analog voltage up to 5v, and then the pic duty is to convert it to digital as I mentioned above.
it might be my wiring is not correct, please If you could help out with this one
and what configuration "at edit project" do I need to choose for Mikro PRO software?
I used "Bluetooth terminal" app to see my data asynchronous from Bluetooth.
Thank you.
char *temp = "0000";
unsigned int adc_value;
char uart_rd; int i;
void main()
{
OSCCON = 0x77;
ANSEL = 0b00000100;
CMCON0 = 0X07;
TRISA = 0b00001100;
UART1_Init(9600);
Delay_ms(100);
while (1)
{
adc_value = ADC_Read(2);
temp[0] = adc_value/1000+48;
temp[1] = (adc_value/100)%10+48;
temp[2] = (adc_value/10)%10+48;
temp[3] = adc_value%10+48;
for (i=0;i<4; i++)
UART1_Write(temp[i]);
UART1_Write(13);
Delay_ms(1000);
}
}
You can use itoa function to convert ADC integer value to characters for sending over UART. If there is error in calculation then you wont get appropriate value. Below code snippet for your reference :
while (1)
{
adc_value = ADC_Read(2);
itoa(adc_value, temp, 10);
for (i=0;i<4; i++)
UART1_Write(temp[i]);
UART1_Write(13);
Delay_ms(1000);
}
Please check Baud Rate you have configured at both ends is same or not. If baudrate mismatches then you will get Random value at Bluetooth Terminal where you are reading values.
What i would suggest, if you have a logic analyser, hook it up. If you don't recalculate your oscillator speed with the datasheet. It could just be that the internal oscillator is not accurate enough. What also works, is to write a function in assembly that waits a known time (by copy-pasting a lot of NOPs and using this to blink a led. Then start a stopwatch and count, say, 100 blinks. This is what i used to do before i had a logic analyser. (They are quite cheep on ebay).
I’m currently trying to design a controller that would communicate through Bluetooth to an android phone (Galaxy Nexus). I’m facing a few challenges. Also, I don’t have much practical programming experience.
At the core of the controller resides an Arduino microcontroller who scans the state of 8 digital pins and six analogue pins (10 bits) and sends the data through serial, to an HC-05 Bluetooth chip.
The android phone should then read the serial information sent through Bluetooth and either transmit the packet to another phone - That will take me a while to implement as I know very little of how the internet works - or analyse and interpret it for further action to be taken
What I’m asking for are insight as to the best way to go about doing this. Now what does best mean?
We’ll I want it to be real time so when I press a button or a combination of bottoms, boom, the android phone takes action fast enough for a human not to perceive a delay.
Then I want to be able to associate the information the phone reads in the serial buffer to the corresponding button or analogue pin. In case there is an error or to avoid that they fall out of sync
Here is what I have so far. I have not tested this code yet, partly because I’m still learning how to program the android part of this project, partly because I want some feedback as to whether I’m being silly or this is actually an effective way to go about doing this:
//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
Is it pointless for me to be doing bit shifts like this? Ultimately, if I’m not mistaken, all data is sent as bytes ( 8 bits packets) so will the Bluetooth.write(analogRead(pin)+testByte) actually send two bytes or will it truncate the int data? how will it be broken down and how can I recuperate it on the android end?
How would you go about implementing this? Any insights or words of advice?
It's great that you are learning this! Some suggestions:
Your code will be easier to read, understand and maintain if you space it out a bit, particularly by adding newlines...
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);
}
}
Also, you can use the shift operators with values other than one. so instead of keeping a shift mask that you then add in, you just use the a simple variable. A more classic way to do what you expressing in the first looop would be something like this:
#define PIN_OFFSET 2
for ( int i=0; i < 8; i++) {
if (digitalRead( i+PIN_OFFSET)== HIGH)
state += (1 << i);
}
The second loop could be done similarly:
for( int pin = 0; pin < 6; pin++) {
short testByte = 0x8000 >> pin;
short result = analogRead(pin) + testByte;
Bluetooth.write( result >> 8);
Bluetooth.write( result & 0xFF);
}
Note that the Bluetooth.write() call sends a byte, so this code sends first the most significant byte, then the least.
Lastly, you probably want to zero your state variable at be beginning of loop() -- otherwise, once a bit is set it will never get cleared.
You may want to think about what you are sending to the phone. It will be binary data, and that can be difficult to deal with -- how do you know the start and end, and often a value will be misinterpretted as a control character messing you up big time. Consider changing it into a formatted, human readable string, with a newline at the end.
I hope that helps.
The Arduino end of this is more than fast enough to do what you want to do and you need not worry in the slightest about minimising the number of bytes you send out from the micro to the phone when you're talking about such a tiny amount of data. I'm not quite clear what you're sending to the phone; are you wanting a different value for each button so when a button is pressed it sends out something like:
Button Was Pressed, Button Number (Two bytes)
And if it's an analogue value:
Analogue Value Read, Analogue Value MSB, Analogue Value LSB (assuming the analogue value is greater than eight bits
I don't know the Arduino code you're using, but my suspicion is that this line:
Bluetooth.write(analogRead(pin)+testByte)
Would send one byte which is the addition of the analogue value and whatever testByte is.
Would you be able to post a link to the documentation for this API?
Any delay with all this will come at the phone end. Please don't concern yourself in the slightest about trying to save a byte or two at the Arduino end! (I'm currently doing a project with a Cortex M3 sending data via a Bluetooth module to Android phones and we're shipping several k of data around. I know from this experience the difference between two and twenty bytes is not of consequence in terms of delay.)
It may be good for you to opt for ready available bluetooth terminal apps for your android handset. On Google play, few apps are:
1) https://play.google.com/store/apps/details?id=arduino.bluetooth.terminal&hl=en
2) https://play.google.com/store/apps/details?id=com.sena.bterm&hl=en
(and few more are availble on Google play).This will help you to focus only on controller side development.
Helo.
Im developing an application that transferes data over bluetooth(with a flight recorder device). When i am recieving a lot of data data(3000 - 40000 lines of text, depends of the file size) my aplication seems to stop recieving the data. I recieve the data with InputStream.read(buffer). For example: I send a command to the flight recorder, it starts sending me a file(line by line), on my phone i recieve 120 lines and then the app stucks.
Intresting is that on my HTC Desire the app stucks just sometimes, on the Samsung Galaxy S phone the application stucks every single time i try to recive more than 50 lines.
The code is based on the BluetoothChat example. This is the part of code where i am listening to the BluetoothSocket:
byte[] buffer = new byte[1024];
int bytes =0;
while(true)
{
bytes = mmInStream.read(buffer);
readMessage = new String(buffer, 0, bytes);
Log.e("read", readMessage);
String read2 = readMessage;
//searching for the end of line to count the lines(the star means the start of the checksum)
int currentHits = read2.replaceAll("[^*]","").length();
nmbrOfTransferedFligts += currentHits;
.
.
.
//parsing and saving the recieved data
I must say that i am running this in a while(true) loop, in a Thread, that is implemented in an android Service. The app seems to stuck at "bytes = mmInStream.read(buffer);"
I have tried to do this with BufferedReader, but with no success.
Thanks.
The app seems to stuck at "bytes = mmInStream.read(buffer);"
But that is normal behavior: InputStream.read(byte[]) blocks when there is no more data available.
This suggests to me that the problem is on the other end or in the communication between the devices. Is is possible that you have a communication problem (which is a bit different on the Galaxy vs. the Desire) that is preventing more data from being received?
Also, I would suggest that you wrap a try/catch around the read statement to be sure that you catch any possible IOException's. Though I guess you would have seen it in logcat if that were happening.
Speaking of logcat, I would suggest that you look at the logcat statements that Android itself it generating. I find that it generates a lot for Bluetooth and this might help you to figure out whether there really is any more data to be read().
This one really has me banging my head. I'm sending alphanumeric data from an Android app, through the BluetoothChatService, to a serial bluetooth adaptor connected to the serial input of a radio transceiver.
Everything works fine except when I try to configure the radio on-the-fly with its AT-commands. The AT+++ (enter command mode) is received OK, but the problem comes with the extended-ascii characters in the next two commands: Changing the radio destination address (which is what I'm trying to do) requires CCh 10h (plus 3 hex radio address bytes), and exiting the command mode requires CCh ATO.
I know the radio can be configured OK because I've done it on an earlier prototype with the serial commands from PIC basic, and it also can be configured by entering the commands directly from hyperterm. Both these methods somehow convert that pesky CCh into a form the radio understands.
I've have tried just about everything an Android noob could possibly come up with to finagle the encoding such as:
private void command_address() {
byte[] addrArray = {(byte) 0xCC, 16, 36, 65, 21, 13};
CharSequence addrvalues = EncodingUtils.getString(addrArray, "UTF-8");
sendMessage((String) addrvalues);
}
but no matter what, I can't seem to get that high-order byte (CCh/204/-52) to behave as it should. All other (< 127) bytes, command or data, transmit with no problem. Any help here would be greatly appreciated.
-Dave
Welll ... turns out the BluetoothChat code re-creates the byte array with message.getBytes() before sending to the service. (after all, being chat code it would normally source only regular ascii strings) As others on this site have pointed out, getBytes() can create encoding issues in some cases. So, for purposes of sending these extended-ascii commands, I don't mess with strings and just send the byte array to the service with
private void sendCommand(byte[] cmd) {
mChatService.write(cmd);
}
The so-called command array is first initialized with placeholders for the hex radio address elements
byte[] addrArray = {(byte) 0xCC, 16, 0, 0, 0, 13};
and then filled in with the help of the conversion method
radioArray = HexStringToByteArray(radioAddr1);
which can be found here: HexStringToByteArray#stackoverflow