Java код
Java код
package com.example.rgz;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textInfo = findViewById(R.id.textInfo);
listViewPairedDevice = findViewById(R.id.pairedlist);
butPanel = findViewById(R.id.ButPanel);
buttonRed = findViewById(R.id.imageButtonRed);
buttonBlue = findViewById(R.id.imageButtonBlue);
if (!
getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) {
Toast.makeText(this, "BLUETOOTH NOT supported",
Toast.LENGTH_LONG).show();
finish();
return;
}
myUUID = UUID.fromString(UUID_STRING_WELL_KNOWN_SPP);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on this hardware
platform", Toast.LENGTH_LONG).show();
finish();
return;
}
@SuppressLint("MissingPermission")
@Override
protected void onStart() {
super.onStart();
if (!bluetoothAdapter.isEnabled()) {
Intent enableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
setup();
}
}
@SuppressLint("MissingPermission")
private void setup() {
@SuppressLint("MissingPermission") Set<BluetoothDevice> pairedDevices
= bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
pairedDeviceArrayList = new ArrayList<>();
listViewPairedDevice.setOnItemClickListener((parent, view,
position, id) -> {
listViewPairedDevice.setVisibility(View.GONE);
String itemValue = (String)
listViewPairedDevice.getItemAtPosition(position);
String MAC = itemValue.substring(itemValue.length() - 17);
BluetoothDevice device2 =
bluetoothAdapter.getRemoteDevice(MAC);
myThreadConnectBTdevice = new ThreadConnectBTdevice(device2);
myThreadConnectBTdevice.start();
});
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (myThreadConnectBTdevice != null)
myThreadConnectBTdevice.cancel();
}
@SuppressLint("MissingSuperCall")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
if (requestCode == REQUEST_ENABLE_BT) {
if (resultCode == Activity.RESULT_OK) {
setup();
} else {
Toast.makeText(this, "Bluetooth не включён",
Toast.LENGTH_SHORT).show();
finish();
}
}
}
@SuppressLint("MissingPermission")
private ThreadConnectBTdevice(BluetoothDevice device) {
try {
bluetoothSocket =
device.createRfcommSocketToServiceRecord(myUUID);
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressLint("MissingPermission")
@Override
public void run() {
boolean success = false;
try {
bluetoothSocket.connect();
success = true;
} catch (IOException e) {
e.printStackTrace();
runOnUiThread(() -> {
Toast.makeText(MainActivity.this, "Нет соединения.
Проверьте устройство!", Toast.LENGTH_LONG).show();
listViewPairedDevice.setVisibility(View.VISIBLE);
});
try {
bluetoothSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (success) {
runOnUiThread(() -> butPanel.setVisibility(View.VISIBLE));
myThreadConnected = new ThreadConnected(bluetoothSocket);
myThreadConnected.start();
}
}
try {
in = socket.getInputStream();
out = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
in = null;
out = null;
}
connectedInputStream = in;
connectedOutputStream = out;
}
@Override
public void run() {
while (true) {
try {
byte[] buffer = new byte[1];
int bytes = connectedInputStream.read(buffer);
String strIncom = new String(buffer, 0, bytes);
sb.append(strIncom);
int endOfLineIndex = sb.indexOf("\r\n");
if (endOfLineIndex > 0) {
String sbprint = sb.substring(0, endOfLineIndex);
sb.delete(0, sb.length());
}
} catch (IOException e) {
break;
}
}
}
buttonRed.setImageResource(isRedOn ? R.drawable.onlamp :
R.drawable.offlamp);
Toast.makeText(MainActivity.this, isRedOn ? "RED LED ON" : "RED
LED OFF", Toast.LENGTH_SHORT).show();
}
}
buttonBlue.setImageResource(isBlueOn ? R.drawable.onlamp :
R.drawable.offlamp);
Toast.makeText(MainActivity.this, isBlueOn ? "BLUE LED ON" :
"BLUE LED OFF", Toast.LENGTH_SHORT).show();
}
}
//Сервопривод
public void swapleft(View v) {
if (myThreadConnected != null) {
byte[] bytesToSend = "c".getBytes();
myThreadConnected.write(bytesToSend);
Toast.makeText(MainActivity.this, "Servo turned left",
Toast.LENGTH_SHORT).show();
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity"
android:id="@+id/osnova"
android:background="#e7e8ea"
android:contextClickable="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textInfo"
android:textSize="22dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:visibility="visible" />
<ListView
android:layout_width="250dp"
android:layout_height="wrap_content"
android:id="@+id/pairedlist"
android:layout_below="@+id/textInfo"
android:layout_alignParentStart="true"
android:layout_marginTop="30dp"
android:layout_marginLeft="20dp"
android:visibility="visible" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e7e7e5"
android:id="@+id/ButPanel"
android:visibility="gone">
<ImageButton
android:id="@+id/imageButtonRed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|top"
android:layout_marginTop="20dp"
android:layout_marginRight="30dp"
android:contentDescription="Red Lamp Button"
android:onClick="onClickRed"
android:src="@drawable/offlamp" />
<TextView
android:id="@+id/red"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|top"
android:layout_marginTop="80dp"
android:layout_marginRight="40dp"
android:text="RED"
android:textSize="30dp" />
<ImageButton
android:id="@+id/imageButtonBlue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|top"
android:layout_marginTop="20dp"
android:layout_marginLeft="40dp"
android:contentDescription="Blue Lamp Button"
android:onClick="onClickBlue"
android:src="@drawable/offlamp" />
<TextView
android:id="@+id/blue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|top"
android:layout_marginTop="80dp"
android:layout_marginLeft="40dp"
android:text="BLUE"
android:textSize="30dp" />
<!--SERVO-->
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton3"
android:layout_gravity="left|top"
android:src="@drawable/arrowleft"
android:layout_marginTop="150dp"
android:layout_marginLeft="30dp"
android:onClick="swapleft" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SERVO"
android:id="@+id/servo"
android:layout_gravity="center_horizontal|top"
android:textSize="30dp"
android:layout_marginTop="160dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton4"
android:layout_gravity="right|top"
android:layout_marginTop="150dp"
android:layout_marginRight="30dp"
android:src="@drawable/arrowright"
android:onClick="swapright" />
</FrameLayout>
</RelativeLayout>
Ардуино код:
#include <Servo.h>
Servo myServo;
int val;
int d12 = 12;
int d13 = 13;
int servoPin = 9;
int pos = 90; // Начальная позиция сервопривода
void setup() {
Serial.begin(9600);
pinMode(d12, OUTPUT);
pinMode(d13, OUTPUT);
myServo.attach(servoPin);
myServo.write(pos);
}
void loop() {
if (Serial.available()) {
val = Serial.read();
if(val == 'a')
{
digitalWrite(d12, HIGH);
Serial.print("D12 ON");
}
if(val == 'A')
{
digitalWrite(d12, LOW);
Serial.print("D12 OFF");
}
if(val == 'b')
{
digitalWrite(d13, HIGH);
Serial.print("D13 ON");
}
if(val == 'B')
{
digitalWrite(d13, LOW);
Serial.print("D1 OFF");
}
if (val == 'c') {
pos = max(pos - 10, 0);
myServo.write(pos);
Serial.print("Servo left, pos: ");
Serial.println(pos);
}
if (val == 'd') {
pos = min(pos + 10, 180);
myServo.write(pos);
Serial.print("Servo right, pos: ");
Serial.println(pos);
}
}
}