Андроид-ардуино. Вывод данных с ардуино в textview

156
01 февраля 2020, 06:30

Мне нужно просто получать данные с ардуина и выводить на textview построчно. С данным кодом текст не выводится. Подскажите пожалуйста другой вариант или ошибку данного кода

     public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

private static final String TAG = "bluetooth1";
TextView mytext;
Button button1, button2; //айди
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID сервиса
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-адрес Bluetooth модуля
private static String address = "98:D3:31:FB:2C:73";  //Вместо “00:00” Нужно нудет ввести MAC нашего bluetooth
@Override
protected void onCreate(Bundle savedInstanceState) {    ////////////////тУТ
            super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    button1 = findViewById(R.id.button2); ///////// ТУТ
    button2 = findViewById(R.id.button3); ////////////// ТУТ
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    checkBTState();
   /*button1.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            sendData("1");
            Toast.makeText(getBaseContext(), "Включаем LED", Toast.LENGTH_SHORT).show();  //выводим на устройстве сообщение
        }
    });
    button2.setOnClickListener(new OnClickListener() {
        public void onClick(View v)
        {
            sendData("0");
            Toast.makeText(getBaseContext(), "Выключаем LED", Toast.LENGTH_SHORT).show();
        }
    });*/
    mytext = findViewById(R.id.mytext);
    Handler h;
    final int ArduinoData = 1;
    h = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                default:
                    byte[] readBuf = (byte[]) msg.obj;
                    String strIncom = new String(readBuf, 0, msg.arg1);
                    mytext.setText("Данные от Arduino: " + strIncom);
                    break;
            }
        };
    };

}
@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}
public void clickButton1() {
    sendData("1");
    Toast.makeText(getBaseContext(), "Включаем LED", Toast.LENGTH_SHORT).show();  //выводим на устройстве сообщение
}
public void clickButton2() {
    sendData("0");
    Toast.makeText(getBaseContext(), "Выключаем LED", Toast.LENGTH_SHORT).show();
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    if (id == R.id.nav_gallery) {
        Intent intent;
        intent = new Intent(this, galery.class);
        startActivity(intent);

    }  else if (id == R.id.nav_manage) {
        Intent intent;
        intent = new Intent(this, nastroiki.class);
        startActivity(intent);
    }  else if (id == R.id.nav_send) {
        Intent intent = new Intent(this, aboutdevelopers.class);
        startActivity(intent);
    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}


@Override
public void onResume() {
    super.onResume();
    Log.d(TAG, "...onResume - попытка соединения...");
    // Set up a pointer to the remote node using it's address.
    BluetoothDevice device = btAdapter.getRemoteDevice(address);
    // Two things are needed to make a connection:
    //   A MAC address, which we got above.
    //   A Service ID or UUID.  In this case we are using the
    //     UUID for SPP.
    try {
        btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) {
        errorExit("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }
    // Discovery is resource intensive.  Make sure it isn't going on
    // when you attempt to connect and pass your message.
    btAdapter.cancelDiscovery();
    // Establish the connection.  This will block until it connects.
    Log.d(TAG, "...Соединяемся...");
    try {
        btSocket.connect();
        Log.d(TAG, "...Соединение установлено и готово к передачи данных...");
    } catch (IOException e) {
        try {
            btSocket.close();
        } catch (IOException e2) {
            errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
        }
    }
    // Create a data stream so we can talk to server.
    Log.d(TAG, "...Создание Socket...");
    try {
        outStream = btSocket.getOutputStream();
    } catch (IOException e) {
        errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
    }
}
public void Ontext() {
}
@Override
public void onPause() {
    super.onPause();
    Log.d(TAG, "...In onPause()...");
    if (outStream != null) {
        try {
            outStream.flush();
        } catch (IOException e) {
            errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
        }
    }
    try     {
        btSocket.close();
    } catch (IOException e2) {
        errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
    }
}
private void checkBTState() {
    // Check for Bluetooth support and then check to make sure it is turned on
    // Emulator doesn't support Bluetooth and will return null
    if(btAdapter==null) {
        errorExit("Fatal Error", "Bluetooth не поддерживается");
    } else {
        if (btAdapter.isEnabled()) {
            Log.d(TAG, "...Bluetooth включен...");
        } else {
            //Prompt user to turn on Bluetooth
            Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }
}
private void errorExit(String title, String message){
    Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
    finish();
}
private void sendData(String message) {
    byte[] msgBuffer = message.getBytes();
    Log.d(TAG, "...Посылаем данные: " + message + "...");
    try {
        outStream.write(msgBuffer);
    } catch (IOException e) {
        String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
        if (address.equals("98:D3:31:FB:2C:73"))
            msg = msg + ".\n\nВ переменной address у вас прописан 00:00:00:00:00:00, вам необходимо прописать реальный MAC-адрес Bluetooth модуля";
        msg = msg +  ".\n\nПроверьте поддержку SPP UUID: " + MY_UUID.toString() + " на Bluetooth модуле, к которому вы подключаетесь.\n\n";
        errorExit("Fatal Error", msg);
    }
}
//////////////////////////////////////////////////////////////////

}

READ ALSO
Не верно определяются устройства

Не верно определяются устройства

Написал небольшой код, который в моем случае воспроизводит проблему, и не определяет устройства правильно

147
Почему Visual Studio ругается на fseek(f,-sizeof(char),SEEK_CUR)

Почему Visual Studio ругается на fseek(f,-sizeof(char),SEEK_CUR)

Мне нужно было перенести указатель файла на один символ назадПоэтому я использовал fseek(f,-sizeof(char),SEEK_CUR);

135
strcpy_s вызывает ошибку [закрыт]

strcpy_s вызывает ошибку [закрыт]

Хотите улучшить этот вопрос? Переформулируйте вопрос, чтобы он соответствовал тематике «Stack Overflow на русском»

145
Обработка исключений C++

Обработка исключений C++

Есть одна исключительная ситуация, но нужно чтобы на нее было 2 разных реакции

184