0 голосов

Доброго времени суток! Столкнулся с проблемой реализации нескольких сервоприводов, программа работает, но при прокручивании seekbar крутится крутятся все сервоприводы а нужно что бы крутился один на одном seekbar и второй сервопривод на другом seekbar

Помогите пожалуйста ребята

Облазил куча сайтов и ничего подобного не нашел

код arduino ide:

#include <Wire.h>
#include <Multiservo.h>
String readString;
Multiservo myservo1,myservo2;

int servo1pos;
int servo2pos;

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600); 
myservo1.attach(16);
myservo2.attach(17);


myservo1.write(7);
myservo2.write(7);
}

void loop() {
  // put your main code here, to run repeatedly:

while (Serial.available()) {
    delay(3);  //delay to allow buffer to fill 
    if (Serial.available() >0) {
      char c = Serial.read();  //gets one byte from serial buffer
      readString += c; //makes the string readString
    } 
  }

  if (readString.length() >0)
  {
    Serial.println(readString); //see what was received
    
    int commaIndex = readString.indexOf(' ');
    
    String firstValue = readString.substring(0, commaIndex);
     servo1pos = firstValue.toInt();
    
                if ((servo1pos > 0) & (servo1pos < 180)) {    
    myservo1.write(servo1pos);
                delay(15); 
                }
    
  
  }
  
   if(readString.length() >0)
  {
    Serial.println(readString); //see what was received
    
    int commaIndex = readString.indexOf(' ');
    
    String firstValue = readString.substring(0, commaIndex);
     servo2pos = firstValue.toInt();
    
                if ((servo2pos > 0) & (servo2pos < 180)) {    
    myservo2.write(servo2pos);
                delay(15); 
                }
  }
  //очистим строку
  readString = "";

}

код Android Studio MainActivity:

package com.example.manipulator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Handler;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.bluetooth.*;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;



public class MainActivity extends AppCompatActivity {

    private TextView mTextValue;
    public SeekBar mSeekBar1;
    public SeekBar mSeekBar2;

    final int ArduinoData = 1;
    private static final int REQUEST_ENABLE_BT = 0;
    final String LOG_TAG = "myLogs";
    public BluetoothAdapter btAdapter;
    private BluetoothSocket btSocket = null;
    // MAC-адрес Bluetooth модуля
    private static String MacAdress = "98:DA:60:00:52:37";
    // SPP UUID сервиса
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private ConnectedThred MyThred = null;

    public TextView mytext;

    Handler h;

    private int servo1pos,servo2pos;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btAdapter = BluetoothAdapter.getDefaultAdapter();
        mytext = (TextView) findViewById(R.id.textView);


        if (btAdapter != null){
            if (btAdapter.isEnabled()){
                mytext.setText("Bluetooth включен");
            }else
            {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }

        }else
        {
            MyError("Fatal Error", "Bluetooth ОТСУТСТВУЕТ");
        }

        mTextValue = (TextView)findViewById(R.id.textView);


        mSeekBar1 = (SeekBar) findViewById(R.id.mSeekBar1);
        mSeekBar2 = (SeekBar)findViewById(R.id.mSeekBar2);

                                   //1
        mSeekBar1.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            int progress = 0;

            @Override
            public void onProgressChanged(SeekBar seekBar, int poresValue, boolean fromUser) {
                progress = poresValue;
                mTextValue.setText(String.valueOf(seekBar.getProgress()));
                servo1pos = seekBar.getProgress();
                MyThred.sendData(servo1pos + " :");

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                servo1pos = seekBar.getProgress();
                MyThred.sendData(servo1pos + " :");
            }
        });


                                           //2
        mSeekBar2.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
            int progress = 0;

            @Override
            public void onProgressChanged(SeekBar seekBar, int poresValue, boolean fromUser) {
                progress = poresValue;
                mTextValue.setText(String.valueOf(seekBar.getProgress()));
                servo2pos = seekBar.getProgress();
                MyThred.sendData(servo2pos + " :");

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                servo2pos = seekBar.getProgress();
                MyThred.sendData(servo2pos + " :");
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();

        BluetoothDevice device = btAdapter.getRemoteDevice(MacAdress);
        Log.d(LOG_TAG, "***Получили удаленный Device***"+device.getName());

        try {
            btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
            Log.d(LOG_TAG, "...Создали сокет...");
        } catch (IOException e) {
            MyError("Fatal Error", "В onResume() Не могу создать сокет: " + e.getMessage() + ".");
        }

        btAdapter.cancelDiscovery();
        Log.d(LOG_TAG, "***Отменили поиск других устройств***");

        Log.d(LOG_TAG, "***Соединяемся...***");
        try {
            btSocket.connect();
            Log.d(LOG_TAG, "***Соединение успешно установлено***");
        } catch (IOException e) {
            try {
                btSocket.close();
            } catch (IOException e2) {
                MyError("Fatal Error", "В onResume() не могу закрыть сокет" + e2.getMessage() + ".");
            }
        }

        MyThred = new ConnectedThred(btSocket);
        MyThred.start();
    }

    @Override
    public void onPause() {
        super.onPause();

        Log.d(LOG_TAG, "...In onPause()...");

        if (MyThred.status_OutStrem() != null) {
            MyThred.cancel();
        }

        try     {
            btSocket.close();
        } catch (IOException e2) {
            MyError("Fatal Error", "В onPause() Не могу закрыть сокет" + e2.getMessage() + ".");
        }
    }

    private void MyError(String title, String message){
        Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
        finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    //start new class
    //Класс отдельного потока для передачи данных
    private class ConnectedThred extends Thread{
        private final BluetoothSocket copyBtSocket;
        private final OutputStream OutStrem;


        public ConnectedThred(BluetoothSocket socket){
            copyBtSocket = socket;
            OutputStream tmpOut = null;

            try{
                tmpOut = socket.getOutputStream();

            } catch (IOException e){}

            OutStrem = tmpOut;
            //InStrem = tmpIn;
        }


        public void sendData(String message) {
            byte[] msgBuffer = message.getBytes();
            Log.d(LOG_TAG, "***Отправляем данные: " + message + "***"  );

            try {
                OutStrem.write(msgBuffer);
            } catch (IOException e) {}
        }

        public void cancel(){
            try {
                copyBtSocket.close();
            }catch(IOException e){}
        }

        public Object status_OutStrem(){
            if (OutStrem == null){return null;
            }else{return OutStrem;}
        }
    }


    //end of program
}

(2 баллов) 1 1 2

1 Ответ

0 голосов
Возможно Вы копипастили элемент привода или seekbar_ы и они стали с одинаковым номером .

Исправьте нумерацию .

Кстати в коде это видно , что один seekbar идёт на два привода.
(589 баллов) 4 8 19
исправил
Добро пожаловать на Бредборд! Сайт вопросов и ответов на тему Arduino, Raspberry Pi и хоббийной электроники в целом. Цель Бредборда — быть максимально полезным. Поэтому мы строго следим за соблюдением правил, боремся с холиворами и оффтопиком.

    За этот месяц ещё никого.

    ...