Can't read serial data from Arduino!!

rubino25

Member
Licensed User
Longtime User
<Solved>Can't read serial data from Arduino!!

Hi all .. I'm trying to connect my Samsung galaxy s 2 to Arduino via bloetooth. With the phone I can easily send data to the device, but I can not receive it! I tried everything, but nothing. But if I send them to the phone via the PC with a USB bluetooth, everything is ok! Can anyone help me? :BangHead::BangHead::BangHead:
Android code:
B4X:
Sub Timer_buffer_Tick
   If connected Then
   lbl_connected.Visible = True
   lbl_connected.Text = "Device connected..."
   lbl_connected.TextColor = Colors.Green
   If text_serial_in.Ready Then 'check if there is any data waiting to be read
         'buffer_in_lenght = text_serial_in.Read(buffer_in, 0, buffer_in.Length )
         'text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Received: " & converter.fromchars(buffer_in))
         text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Received: " & text_serial_in.ReadLine )
      End If
      If (seek_pwm1_old <> seek_pwm1.Value) Then
         text_serial_out.Write("p1" & seek_pwm1.Value)
         text_serial_out.Flush
         text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Sended pwm1 value: " & seek_pwm1.Value)
         seek_pwm1_old = seek_pwm1.Value
      Else If (seek_pwm2_old <> seek_pwm2.Value) Then
         text_serial_out.Write("p2" & seek_pwm2.Value)
         text_serial_out.Flush
         text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Sended pwm2 value: " & seek_pwm2.Value)
         seek_pwm2_old = seek_pwm2.Value
      Else If (seek_pwm3_old <> seek_pwm3.Value) Then
         text_serial_out.Write("p3" & seek_pwm3.Value)
         text_serial_out.Flush
         text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Sended pwm3 value: " & seek_pwm3.Value)
         seek_pwm3_old = seek_pwm3.Value
      End If
   Else
      lbl_connected.Visible = Not(lbl_connected.Visible)
   lbl_connected.Text = "No device connected..."
   lbl_connected.TextColor = Colors.Red
   End If
End Sub

arduino code:
B4X:
Serial.println("Connected to Bloetooth.");
  delay(500);
  if (Serial.available() > 0) { //Se sono presenti dati nel buffer
    command_type = Serial.read();
    delay(2);
    if (command_type == 's') { //se il comando è s indica lo stato della connessione 
      stato_connessione = Serial.read();
      if (stato_connessione == 49) { //se lo stato è uguale a 1
        delay(2);
        Serial.write("Connected to Bloetooth.");
        digitalWrite(led_connesso, HIGH);
      }
      else if (stato_connessione == 48) { //se lo stato è uguale a 0
        delay(2);
          Serial.print("Disconnected from Bloetooth.");
        digitalWrite(led_connesso, LOW);
      }
    }
 
Last edited:

rubino25

Member
Licensed User
Longtime User
Solved .. There was a problem with the electrical connection between the module and arduino! :sign0013::BangHead::BangHead::BangHead::BangHead::BangHead::BangHead:
 
Upvote 0

rubino25

Member
Licensed User
Longtime User
So, if someone were to serve, here is the code for Arduino and Android!
In my case I used:
1 Arduino Uno;
1 Ardumoto by Sparkfun;
2 Sharp ir sensor;
1 GVS Shield for IO;

Arduino Code:
B4X:
byte pwm_1 = 3; //Pin Velocità motore 1
byte pwm_2 = 11; //Pin Velocità motore 2
byte dir_1 = 12; //Pin Direzione motore 1
byte dir_2 = 13; //Pin Direzione motore 2
byte command_type = 0; //Tipo di comando
byte command = 0; // Parametri comando
byte pwm_speed = 255; //Velocità motori
byte pwm_speed2 = 255; //Velocità motori 2
byte pwm_diff = 25; //Differenza per equilibrare i motori per farli andare diritti
byte led_connesso = 13; //pin per indicare che la connessione è stata stabilita
char stato_connessione;
int analog = 0; //valore per lettura dei sensori sharp
char char_in[10];
boolean stato_movimento = false;
String stringa_sharp= "";

void setup()
{
  // Inizio comunicazione seriale a 9600
  Serial.begin(9600);
  pinMode(pwm_1, OUTPUT);
  pinMode(pwm_2, OUTPUT);
  pinMode(dir_1, OUTPUT);   
  pinMode(dir_2, OUTPUT);
  pinMode(led_connesso, OUTPUT);
}

void loop()
{
  if (Serial.available() > 0) { //Se sono presenti dati nel buffer
    command_type = Serial.read();
    delay(2);
    if (command_type == 's') { //se il comando è s indica lo stato della connessione 
      stato_connessione = Serial.read();
      if (stato_connessione == 49) { //se lo stato è uguale a 1
        delay(2);
        Serial.println("Connected to Bloetooth.");
        digitalWrite(led_connesso, HIGH);
      }
      else if (stato_connessione == 48) { //se lo stato è uguale a 0
        delay(2);
          Serial.println("Disconnected from Bloetooth.");
        digitalWrite(led_connesso, LOW);
      }
    }
    if (stato_connessione == 49) {
      if (command_type == '*') { //per leggere i sensori
        char sharp_id; //per sapere quale sensore sharp leggere
        sharp_id = Serial.read();
        if (sharp_id == 48) {
          analog = analogRead(A1);
          stringa_sharp = "Sharp Dx: ";
          stringa_sharp = stringa_sharp + analog;
          Serial.println(stringa_sharp);
          stringa_sharp= "";
        }
        else if (sharp_id == 49) {
          analog = analogRead(A0);
          stringa_sharp = "Sharp Sx: ";
          stringa_sharp = stringa_sharp + analog;
          Serial.println(stringa_sharp);
          stringa_sharp= "";
        }
      }
      if (command_type == 'c') {
        command = Serial.read();
        switch (command) {
        case 'u':
          cambia_velocita();
          digitalWrite(dir_1, LOW);
          digitalWrite(dir_2, LOW);
          stato_movimento = true;
          break;  
        case 'd':
          cambia_velocita();
          digitalWrite(dir_1, HIGH);
          digitalWrite(dir_2, HIGH);
          stato_movimento = true;
          break; 
        case 'r':
          cambia_velocita();
          digitalWrite(dir_1, HIGH);
          digitalWrite(dir_2, LOW);
          stato_movimento = true;
          break; 
        case 'l':
          cambia_velocita();
          digitalWrite(dir_1, LOW);
          digitalWrite(dir_2, HIGH);
          stato_movimento = true;
          break; 
        case 's':
          analogWrite(pwm_1, 0);
          digitalWrite(dir_1, HIGH);
          analogWrite(pwm_2, 0);
          digitalWrite(dir_2, HIGH);
          stato_movimento = false;
          break; 
        }
      }
      if (command_type == 'p') {
        int cont = 0;
        char slider = 0;
        char valore[5];
        slider = Serial.read(); //identifica lo slider per il pwm
        delay(2);
        while (Serial.available() > 0) {
          valore[cont] = Serial.read();
          cont ++;
          delay(5);
        }
        if (slider == 49) { //se lo slider è l'1
          pwm_speed = atoi(valore);
        }
        else if (slider == 50) { //se lo slider è il 2
          pwm_speed2 = atoi(valore);
        }
        else if (slider == 51) { //se lo slider è il 3
          pwm_speed = atoi(valore);
          pwm_speed2 = atoi(valore);
        }
        if (stato_movimento == true) { //richiamo routine per cambio velocità
          cambia_velocita();
        }
        for (int i = 0; i < 3; i++) { //pulisco array
          valore[i] = 0;
        }
      }  
    }
  }
}

void cambia_velocita() {
  analogWrite(pwm_1, map(pwm_speed,0,255,0,255 - pwm_diff));
  analogWrite(pwm_2, pwm_speed2);
}
Chiedo scusa per i commenti in italiano, ma non mi andava di aggiornarli....

Android code:
B4X:
'Activity module
Sub Process_Globals
   Dim Serial1 As Serial
   Dim text_serial_in As TextReader
   Dim text_serial_out As TextWriter
   Dim Timer_buffer As Timer
   Dim connected As Boolean 
   Dim text_log As List
   text_log.Initialize
End Sub

Sub Globals
   Dim seek_pwm1 As SeekBar
   Dim seek_pwm2 As SeekBar
   Dim seek_pwm3 As SeekBar
   Dim lbl_pwm1 As Label
   Dim lbl_pwm2 As Label
   Dim lbl_pwm3 As Label
   Dim seek_pwm1_old As Int
   Dim seek_pwm2_old As Int
   Dim seek_pwm3_old As Int 
   Dim lbl_connected As Label 
   Dim buffer_in(35) As Char
   Dim buffer_in_lenght As Int 
   Dim converter As ByteConverter
End Sub

Sub Activity_Create(FirstTime As Boolean)
 If FirstTime Then
      Serial1.Initialize("Serial1")
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Serial Loaded")
      Timer_buffer.Initialize("Timer_buffer", 200)
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Timer Loaded")
      Timer_buffer.Enabled = True      
   End If
   Activity.LoadLayout ("Main")
   Activity.AddMenuItem("Connect", "mnuConnect")
   Activity.AddMenuItem("Disconnect", "mnuDisconnect")
   Activity.AddMenuItem("Log", "mnuLog")
   text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Activity loaded")
   lbl_pwm1.text = 0
   lbl_pwm2.text = 0
   lbl_pwm3.text = 0
   seek_pwm1_old = 0
   seek_pwm2_old = 0
   seek_pwm3_old = 0
End Sub

Sub Activity_Resume
If Serial1.IsEnabled = False Then
      Msgbox("Please enable Bluetooth...", "Bluetooth module is disabled..")
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Bloetooth is not enabled on resume")
   Else
      Serial1.Listen 'listen for incoming connections
   End If
End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub mnuConnect_Click
   Dim PairedDevices As Map
   PairedDevices = Serial1.GetPairedDevices
   Dim list_device As List
   list_device.Initialize
   text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Found " & PairedDevices.Size & " devices")
   For i = 0 To PairedDevices.Size - 1
      list_device.Add(PairedDevices.GetKeyAt(i))
   Next
   Dim res As Int
   res = InputList(list_device, "Choose device...", -1) 'show list with paired devices
   If res <> DialogResponse.CANCEL Then
      Serial1.Connect(PairedDevices.Get(list_device.Get(res))) 'convert the name to mac address
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Selected " & PairedDevices.Get(list_device.Get(res)))
   End If
End Sub

Sub mnuDisconnect_Click
   If connected Then
      text_serial_out.Write("p1" & 0)
      text_serial_out.Flush
      seek_pwm1.Value = 0
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Sended pwm1 value: " & seek_pwm1.Value)
      text_serial_out.Write("p2" & 0)
      text_serial_out.Flush
      seek_pwm2.Value = 0
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Sended pwm2 value: " & seek_pwm2.Value)
      text_serial_out.Write("p3" & 0)
      text_serial_out.Flush
      seek_pwm3.Value = 0
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Sended pwm3 value: " & seek_pwm3.Value)
      text_serial_out.Write("cs")
      text_serial_out.Flush
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Sended Stop command")
      text_serial_out.Write("s0")
      text_serial_out.Flush
   End If
   Serial1.Disconnect
   connected = False
   text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Disconnected from device")
End Sub

Sub mnuLog_Click
   StartActivity(logserial)
End Sub

Sub Serial1_Connected (Success As Boolean)
   If Success Then
      ToastMessageShow("Connected successfully!", False)
      text_serial_in.Initialize(Serial1.InputStream)
      text_serial_out.Initialize(Serial1.OutputStream)
      connected = True
      text_serial_out.Write("s1")
      text_serial_out.Flush
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Connected successfully")
   Else
      connected = False
      Msgbox(LastException.Message, "Error connecting!!")
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Error connecting")
   End If
End Sub

Sub Timer_buffer_Tick
   If connected Then
   lbl_connected.Visible = True
   lbl_connected.Text = "Device connected..."
   lbl_connected.TextColor = Colors.Green
   If text_serial_in.Ready Then 'check if there is any data waiting to be read
         'buffer_in_lenght = text_serial_in.Read(buffer_in, 0, buffer_in.Length )
         'text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Received: " & converter.fromchars(buffer_in))
         text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Received: " & text_serial_in.ReadLine )
      End If
      If (seek_pwm1_old <> seek_pwm1.Value) Then
         text_serial_out.Write("p1" & seek_pwm1.Value)
         text_serial_out.Flush
         text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Sended pwm1 value: " & seek_pwm1.Value)
         seek_pwm1_old = seek_pwm1.Value
      Else If (seek_pwm2_old <> seek_pwm2.Value) Then
         text_serial_out.Write("p2" & seek_pwm2.Value)
         text_serial_out.Flush
         text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Sended pwm2 value: " & seek_pwm2.Value)
         seek_pwm2_old = seek_pwm2.Value
      Else If (seek_pwm3_old <> seek_pwm3.Value) Then
         text_serial_out.Write("p3" & seek_pwm3.Value)
         text_serial_out.Flush
         text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Sended pwm3 value: " & seek_pwm3.Value)
         seek_pwm3_old = seek_pwm3.Value
      End If
   Else
      lbl_connected.Visible = Not(lbl_connected.Visible)
   lbl_connected.Text = "No device connected..."
   lbl_connected.TextColor = Colors.Red
   End If
End Sub

Sub btn_up_Click
   If connected Then
      text_serial_out.Write("cu")
      text_serial_out.Flush
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Sended Up command")
   End If
End Sub

Sub btn_left_Click
   If connected Then
      text_serial_out.Write("cl")
      text_serial_out.Flush
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Sended Left command")
   End If
End Sub

Sub btn_down_Click
   If connected Then
      text_serial_out.Write("cd")
      text_serial_out.Flush
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Sended Down command")
   End If
End Sub

Sub btn_right_Click
   If connected Then
      text_serial_out.Write("cr")
      text_serial_out.Flush
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Sended Right command")
   End If
End Sub

Sub btn_stop_Click
   If connected Then
      text_serial_out.Write("cs")
      text_serial_out.Flush
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Sended Stop command")
   End If
End Sub

Sub seek_pwm1_ValueChanged (Value As Int, UserChanged As Boolean)
   If connected Then 
      lbl_pwm1.text = seek_pwm1.Value 
   End If
End Sub

Sub seek_pwm2_ValueChanged (Value As Int, UserChanged As Boolean)
   If connected Then
      lbl_pwm2.text = seek_pwm2.Value 
   End If
End Sub

Sub seek_pwm3_ValueChanged (Value As Int, UserChanged As Boolean)
   If connected Then
      lbl_pwm3.text = seek_pwm3.Value 
   End If
End Sub

Sub lbl_pwm1_LongClick
   Try
      Dim Id As InputDialog
      Id.InputType = Id.INPUT_TYPE_TEXT 
      Id.Input = ""
      Id.Hint = "Tap to set...!"
      Id.HintColor = Colors.ARGB(255,0,0,0)
      ret = DialogResponse.CANCEL
      ret = Id.Show("", "Set Pwm 1 Value", "Set", "Cancel", "", Null)
      If ret = -3 Then
         Return
      Else If (ret = -1) AND (Id.Input > 255) Then
         ToastMessageShow("The variable must not exceed 255.", True)
          Return
      Else If (ret = -1) AND (Id.Input <= 255) Then
         seek_pwm1.Value= Id.Input
         lbl_pwm1.text = Id.Input 
         Return
      End If   
   Catch
      ToastMessageShow("Can't set Pwm 1 value! See the log for details.", False)
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "An error occurred while writing Pwm 1: " & LastException.Message)
   End Try
End Sub

Sub lbl_pwm2_LongClick
   Try
      Dim Id As InputDialog
      Id.InputType = Id.INPUT_TYPE_TEXT 
      Id.Input = ""
      Id.Hint = "Tap to set..."
      Id.HintColor = Colors.ARGB(255,0,0,0)
      ret = DialogResponse.CANCEL
      ret = Id.Show("", "Set Pwm 2 Value", "Set", "Cancel", "", Null)
      If ret = -3 Then
         Return
      Else If (ret = -1) AND (Id.Input > 255) Then
         ToastMessageShow("The variable must not exceed 255.", True)
          Return
      Else If (ret = -1) AND (Id.Input <= 255) Then
         seek_pwm2.Value= Id.Input
         lbl_pwm2.text = Id.Input 
         Return
      End If   
   Catch
      ToastMessageShow("Can't set Pwm 2 value! See the log for details.", False)
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "An error occurred while writing Pwm 2: " & LastException.Message)
   End Try
End Sub

Sub lbl_pwm3_LongClick
   Try
      Dim Id As InputDialog
      Id.InputType = Id.INPUT_TYPE_TEXT 
      Id.Input = ""
      Id.Hint = "Tap to set...!"
      Id.HintColor = Colors.ARGB(255,0,0,0)
      ret = DialogResponse.CANCEL
      ret = Id.Show("", "Set Pwm 3 Value", "Set", "Cancel", "", Null)
      If ret = -3 Then
         Return
      Else If (ret = -1) AND (Id.Input > 255) Then
         ToastMessageShow("The variable must not exceed 255.", True)
          Return
      Else If (ret = -1) AND (Id.Input <= 255) Then
         seek_pwm3.Value= Id.Input
         lbl_pwm3.text = Id.Input 
         Return
      End If   
   Catch
      ToastMessageShow("Can't set Pwm 3 value! See the log for details.", False)
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "An error occurred while writing Pwm 3: " & LastException.Message)
   End Try
End Sub
Sub btn_sharp_sx_Click
   If connected Then
      text_serial_out.Write("*1")
      text_serial_out.Flush
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Requested the value of the Left Sharp sensor.")
   End If
End Sub
Sub btn_sharp_dx_Click
   If connected Then
      text_serial_out.Write("*0")
      text_serial_out.Flush
      text_log.Add(DateTime.Time(DateTime.Now) & " --> " & "Requested the value of the Right Sharp sensor.")
   End If
End Sub
 
Upvote 0

mitsusdev

Member
Licensed User
Longtime User
Thanks a lot rubino25.

I ordered a arduino board yesterday. As soon as I get the tests.

Regards
 
Upvote 0

agus mulyana

Member
Licensed User
Longtime User
Dear

execuse me, i need to send a serial data from arduino to Mobole Phone (LG), and i use basic4android to receiver it, but, there are a problem when the arduino send serial data, bluetooth communciation suddenly stopped/broken, i use an arduino UNO and HC-05/HC-06 Bluetooth, please help me...thank you
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…