This is my code.
I wanna receive two values in Arduino from android app.
I can receive one value but I can't two values.
Here is my code.
I wanna send two values with Bluetooth.send().
How can I do that?
I use bluetoothSPP in android studio.
I wanna receive Go ,Back, Right, Left and seconds in arduino.
so If i receive Go and 2sec, my arduino rc car go for 2 sec.
//Arduino code
#include<SoftwareSerial.h>
#include <Servo.h>
SoftwareSerial BT(blueTx,blueRx);
Servo servo;
char input1;
char input2;
void loop() {
if(BT.available()){
if(Serial.available()){
Serial.println("------");
Serial.println(BT.read());
}
input1 = BT.read();
input2 = BT.read();
}
}
// Android code , i use bluetoothSPP and send method
blockStartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!list.isEmpty()) {
delayHandler.postDelayed(new Runnable() {
#Override
public void run() {
while(!list.isEmpty()) {
String blockName = list.get(0);
num1 = inputNum.getText().toString();
list.remove(0);
adapter.notifyDataSetChanged();
if (blockName == "GO") {
Bluetooth.send("G", true);
Bluetooth.send(num1, true);
} else if (blockName == "BACK") {
Bluetooth.send("K", true);
Bluetooth.send(num1, true);
} else if (blockName == "LEFT") {
Bluetooth.send("L", true);
Bluetooth.send(num1, true);
} else if (blockName == "RIGHT") {
Bluetooth.send("R", true);
Bluetooth.send(num1, true);
}
// inputNum.setText(null);
}
}
}, 10);
}
I had similar problem in the problem , though I did'nt use bluetooth spp , but give this a shot , try to send byte array in send
I designed my input like a,b and convert this to byte array , in your case send it like G/K/L/R,num1 see the comma added , to convert this to byte array use getBytes() , in aurdino do the following :
void loop() {
if(Serial.available()){
int available = Serial.available();
for(int i=0; i< available; i++){
char a = Serial.read();
if(i < 1){
input1 = a;
}
if(i > 1){
int c =(int)a - 48;
input2 *= 10;
input2 += c;
}
}
}
Explanation skip comma which is second character(1) , first character is normal so add it to input1 , second one is number so extract ascii values starts from 48 and get the number from it.Input2 is of type int with initial value of 0 , Enjoy!
Related
I tried to increase++ a number (i) each time the distance between the camera and my face is between 40 cm and 80 cm. Unfortunately when it happen the textview shows (The number of occurrence is: 50). Help me please
public void update(final Messsage msg) {
for(int i = 0; i < 50; ++i) {
if (msg.getDistanceToFace() > 40 && msg.getDistanceToFace() < 80) {
textView.setText("The number of occurrence is: " + i);
textView.setTextColor(Color.GREEN);
}
}
}
you should probably add a break after you set the text, the way you coded it will set a text for all the iteration of i but you will only see the last one (50)
If you only want to increase the number when the face is a certain length away, shouldn't you do something more on the lines of this?
public void update(final Messsage msg) {
int i = 0;
if (msg.getDistanceToFace() > 40 && msg.getDistanceToFace() < 80) {
i++;
textView.setText("The number of occurrence is: " + i);
textView.setTextColor(Color.GREEN);
}
}
Maybe you'll need to have that i a global variable or an argument to the function, not sure without having more of the code.
If you don't want the i to increase really fast (because it increments each time the update function is called and the phone is close to the face), a simple code to do that would be something like
public void update(final Messsage msg) {
boolean isCloseToFace = false;
int i = 0;
if (msg.getDistanceToFace() > 40 && msg.getDistanceToFace() < 80) {
if (!isCloseToFace) {
i++;
isCloseToFace = true;
}
textView.setText("The number of occurrence is: " + i);
textView.setTextColor(Color.GREEN);
} else {
isCloseToFace = false;
}
}
I am an android noobie. What I am trying to do is to make this String an ArrayList. This is done. When i Print it On (with tv.setText) , the result is what i need but in this if i have right below i cannot find the "1".
The result i want to have is to store the text between the noumbers inside another ArrayList but to go there i have to be able to read the strings from the ArrayList.
public class MainActivity extends AppCompatActivity {
String text = "1Hello12People22Paul22Jackie21Anna12Fofo2";
TextView tv;
List<String> chars = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tv);
PrinThemNow();
}
public void PrinThemNow(){
chars = Arrays.asList(text.split(""));
tv.setText(toString().valueOf(chars));
for(int i=0;i<chars.size();i++){
if(toString().valueOf(chars.get(i)) == " 1"){
Toast.makeText(this,"I found One",Toast.LENGTH_LONG).show();
//This if is not working while the TV's text shows " 1"
}
}
}
}
First, just a tip, from string to char[] you can use
char[] chars = myString.toCharArray();
because it has no sense to save a char array as a string ArrayList
but now the problem. you have your string and you wanna print the text between the numbers.
It's not really clear what is your goal but lets try.
I will suppose you used the char[] because it's 10 times better and easier
case 1) you wanna print text betweens "1"s
//lets loop the chars
bool firstOneFound = false;
int firstOccurrence = -1;
int secondOccurrence = -1;
int i = 0;
for(char c : chars){
//is it equals to 1?
if(c.equals('1')){
//check if we are already after the first 1
if(firstOneFound){
//if yes, we found the final one
secondOccurrence = i;
break;
}
else{
//this is the first occurrence
firstOccurrence = i;
firstOneFound = true;
}
}
i++;
}
if(firstOccurrence != -1 && secondOccurrence != -1){
String myFinalString = myString.subString(firstOccurrence, secondOccurrence);
}
case 2) you wanna print all text except numbers (maybe with a space instead)
for(char c : chars){
//check if it's a number
if(c >= '0' && c <= '9'){
//replace the number with anything else
c = ' '; //if you wanna have it as a space
}
}
//print the final string
String myFinalString = new String(chars);
NOTE:
You can also use ArrayList of string, just replace ' with "
hope it helps
I'm trying to send long String to Android via bluetooth.
but,
It looks like the picture.
some characters are changed.
how can I get an exact full string?
arduino code :
for(int i=0;i<16;i++){
String rec = String(P[i], HEX);
if(rec.length()<2) rec = "0"+rec;
BTSerial.println(rec);
delay(50);
P is a byte array. Thanks.
Try it without String objects:
// return '0' .. 'F'
char hexnibble(byte nibble) {
nibble &= 0x0F; // just to be sure
if (nibble > 9) return 'A' + nibble - 10;
else return '0' + nibble;
}
void loop() {
byte P[16];
// ... fill P somehow ...
char rec[33];
for(int i=0;i<16;i++){
rec[2*i] = hexnibble(P[i] >> 4);
rec[2*i+1] = hexnibble(P[i] & 0x0F);
}
rec[32] = 0; // string terminator
Serial.println(rec); // just for debugging
delay(1000);
}
Updated question: I am trying to connect to a terminal emulator using a library in android, this will connect to a serial device and should show me sent/received data. I should be able to send data over the connection via a text box below the terminal or by typing in the terminal itself and hitting enter on the keyboard in both cases.
When I was sending data via textbox I had to append \n to the data to get to a new line when I pressed the enter key like so:
mEntry = (EditText) findViewById(R.id.term_entry);
mEntry.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
/* Ignore enter-key-up events. */
if (event != null && event.getAction() == KeyEvent.ACTION_UP) {
return false;
}
Editable e = (Editable) v.getText();
String data = e.toString() + "\n";
sendOverSerial(data.getBytes());
TextKeyListener.clear(e);
return true;
}
});
And the write method:
public void write(byte[] bytes, int offset, int count) {
super.write(bytes, offset, count);
if (isRunning()) {
doLocalEcho(bytes);
}
return;
}
When I was hitting enter after typing in the terminal session itself no new line was occurring at all. So I had to test the data for \r and replace it with \r\n:
private void doLocalEcho(byte[] data) {
String str = new String(data);
appendToEmulator(data, 0, data.length);
notifyUpdate();
}
public void write(byte[] bytes, int offset, int count) {
// Count the number of CRs
String str = new String(bytes);
int numCRs = 0;
for (int i = offset; i < offset + count; ++i) {
if (bytes[i] == '\r') {
++numCRs;
}
}
if (numCRs == 0) {
// No CRs -- just send data as-is
super.write(bytes, offset, count);
if (isRunning()) {
doLocalEcho(bytes);
}
return;
}
// Convert CRs into CRLFs
byte[] translated = new byte[count + numCRs];
int j = 0;
for (int i = offset; i < offset + count; ++i) {
if (bytes[i] == '\r') {
translated[j++] = '\r';
translated[j++] = '\n';
} else {
translated[j++] = bytes[i];
}
}
super.write(translated, 0, translated.length);
// If server echo is off, echo the entered characters locally
if (isRunning()) {
doLocalEcho(translated);
}
}
So that worked fine, now when I typed in the terminal session itself and hit enter i got the newline I wanted. However now every time I send data from the text box with with \n there was an extra space between every newline as well as getting the extra newline.
http://i.imgur.com/gtdIH.png
So I thought that when counting the number of carriage returns peek ahead at the next byte, and if it is '\n' don't count it:
for (int i = offset; i < offset + count; ++i) {
if (bytes[i] == '\r' &&
(
(i+1 < offset + count) && // next byte isn't out of index
(bytes[i+1] != '\n')
) // next byte isn't a new line
)
{
++numCRs;
}
}
This fixed the problem of the spaces...but that was rather stupid as I am now back in a circle to the original problem, if I type directly in the terminal there is no new line, as it sees the \r\n and sees the next byte is invalid. What would be the best way to get both working together? I either have these weird extra spaces and all input is fine, or normal spacing and I can't enter text directly from the terminal, only the textbox. I assume it's really easy to fix, I just am scratching my head looking at it.
EDIT: Not fixed, thought I had but then when I enter directly from the terminal enter does not produce a new line. It must be because the \n is ignored after the \r
I have most of this fixed. When counting the number of carriage returns peek ahead at the next byte, and if it is '\n' don't count it:
for (int i = offset; i < offset + count; ++i) {
if (bytes[i] == '\r' &&
(
(i+1 < offset + count) && // next byte isn't out of index
(bytes[i+1] != '\n')
) // next byte isn't a new line
)
{
++numCRs;
}
}
The only problem left now is that I still get the prompt back twice like this:
switch#
switch#
I have a strange problem in my application
Some users send me the error:
java.lang.ArrayIndexOutOfBoundsException
i , myself , have never experienced that error. Here is the code:
for(int i =0; i<length*2; i+=2) {
if(charsLeft[i/2]==1)
temp[i]=word[i/2];//IT HAPPENS HERE
....
length = word.length;
charsLeft = new int[length];
temp = new String[length*2];
When a users goes back to home screen , the application saves and later loads the data this way:
public Bundle saveState(Bundle bundle) {
synchronized (surfaceHolder) {
if (bundle != null) {
bundle.putStringArray("word",game.word.word);
bundle.putIntArray("charsLeft",game.word.charsLeft);
bundle.putInt("length",game.word.word().length());
bundle.putStringArray("temp",game.word.temp);
bundle.putCharArray("characters", game.word.characters);
...
}
}
return bundle;
}
public synchronized void restoreState(Bundle bundle) {
synchronized (surfaceHolder) {
mPaused = true;
if (bundle != null) {
game.word.word = bundle.getStringArray("word");
game.word.length = bundle.getInt("length");
game.word.init();
game.word.charsLeft = bundle.getIntArray("charsLeft");
game.word.temp = bundle.getStringArray("temp");
game.word.characters = bundle.getCharArray("characters");
...
}
}
}
Does anyone see where it goe
EDIT
full loop
for(int i =0; i<(length)*2; i+=2) {
if(charsLeft[i/2]==1)
temp[i]=word[i/2];
else
temp[i]="_";
temp[i+1]=" ";
}
Example word[0] = a word[1] = n .....
->"answer"
the loop diveds the word in spaces and the letter or if the letter isnt guessed yet by a _
ex. a n s _ e _
EDIT:
I think I found the error :
A thread was calling the loop while an other thread could reassign word to another value , and if the loop was called before the value of length was changed then you have an error.
I changed the loop to this
temp = new String[word.length*2];
for(int i =0; i<(word.length*2); i+=2) {
if(charsLeft[i/2]==1)
temp[i]=word[i/2];
Now lets hope its fixed
Forget your loop if all you want to do is divide the word by spaces or blanks. Just using split:
String[] words = word.split( "\s|_" );
That will spit the word into an array of words on either a space or an underscore.