Система дистанційного управління електричним засобом транспортування на базі ОС Android

Вживання електричних транспортних засобів з дистанційним управлінням. Канали зв’язку для передачі даних від пульта керування до керуючої машини. Реалізація програмного коду для Arduino Nano. Створення Android-додатку. Автоматизація процесів управління.

Рубрика Программирование, компьютеры и кибернетика
Вид дипломная работа
Язык украинский
Дата добавления 24.07.2014
Размер файла 4,1 M

Отправить свою хорошую работу в базу знаний просто. Используйте форму, расположенную ниже

Студенты, аспиранты, молодые ученые, использующие базу знаний в своей учебе и работе, будут вам очень благодарны.

22.Brokk AB - BROKK // Строй Тех [Електронний ресурс]. - Режим доступу: URL: http://www.stroyteh.ru/company/BROKK. - Загол. з екрану.

23.Multi - Mover - компактные электрические тягачи и электрокары, электротележки. Выгодно купить электрокар, мини тягач или электрическую тележку можно в компании Suffecta // Suffecta [Електронний ресурс]. - Режим доступу: URL: http://suffecta.ru/catalog/multi-mover-kompaktnye-elektrogidravlicheskie-tyagachi/. - Загол. з екрану.

24.Электротележка - электротележки фирмы Crown // Crown [Електронний ресурс]. - Режим доступу: URL: http://www.crown.com/ru/pogruzchiki/elektrotelezhki.html. - Загол. з екрану.

25.Миль Гюнтен Электронное дистанционное управление моделями [Текст] / М. Гютен - ДОСААФ, 1980. - 416 с.

26.Козловский Ю. Е. Производственная культура и эстетика [Текст] / Ю. Е. Козловский - Недра, 1970. - 79 с.

27.Рыжкин В. Я. - Тепловые электрические станции [Текст] / В. Я. Рыжкин - Энергоатомиздат, 1987. - 400 с.

28.Дистанционное управление -- Горная энциклопедия // Горная энциклопедия [Електронний ресурс]. - Режим доступу: URL: http://www.mining-enc.ru/d/distancionnoe-upravlenie/. - Загол. з екрану.

29.Дистанционное управление GSM.Телеметрия. // Icm - tec [Електронний ресурс]. - Режим доступу: URL: http://icm-tec.com/system.htm. - Загол. з екрану.

Додаток А. Код програми для Arduino Nano

#include "EEPROM.h"

#define D1 2

#define M1 3

#define D2 4

#define M2 5

#define HORN 13

#define autoOFF 2500

#define cmdL 'L'

#define cmdR 'R'

#define cmdH 'H'

#define cmdF 'F'

#define cmdr 'r'

#define cmdw 'w'

char incomingByte;

char L_Data[4];

byte L_index = 0;

char R_Data[4];

byte R_index = 0;

char H_Data[1];

byte H_index = 0;

char F_Data[8];

byte F_index = 0;

char command;

unsigned long currentTime, lastTimeCommand, autoOFF;

void setup()

{

Serial.begin(9600);

pinMode(HORN, OUTPUT);

pinMode(D1, OUTPUT);

pinMode(D2, OUTPUT);

EEPROM.write(0,255);

EEPROM.write(1,255);

EEPROM.write(2,255);

EEPROM.write(3,255);

timer_init();

}

void Timer_init()

{

uint8_t sw_autoOFF = EEPROM.read(0);

if(sw_autoOFF == '1')

{

char var_Data[3];

var_Data[0] = EEPROM.read(1);

var_Data[1] = EEPROM.read(2);

var_Data[2] = EEPROM.read(3);

autoOFF = atoi(var_Data)*100;

else if(sw_autoOFF == '0')

autoOFF = 999999;

else if(sw_autoOFF == 255)

autoOFF = 2500;

currentTime = millis();

void loop()

if (Serial.available() > 0)

incomingByte = Serial.read();

if(incomingByte == cmdL)

{

command = cmdL;

memset(L_Data,0,sizeof(L_Data));

L_index = 0;

}

else if(incomingByte == cmdR)

{

command = cmdR;

memset(R_Data,0,sizeof(R_Data));

R_index = 0;

}

else if(incomingByte == cmdH)

{

command = cmdH;

memset(H_Data,0,sizeof(H_Data));

H_index = 0;

}

else if(incomingByte == cmdF)

{

command = cmdF;

memset(F_Data,0,sizeof(F_Data));

F_index = 0;

}

else if(incomingByte == '\r') command = 'e';

else if(incomingByte == '\t') command = 't';

if(command == cmdL && incomingByte != cmdL)

{

L_Data[L_index] = incomingByte;

L_index++;

}

else if(command == cmdR && incomingByte != cmdR)

{

R_Data[R_index] = incomingByte;

R_index++;

}

else if(command == cmdH && incomingByte != cmdH)

H_Data[H_index] = incomingByte;

H_index++;

else if(command == cmdF && incomingByte != cmdF)

{

F_Data[F_index] = incomingByte;

F_index++;

}

else if(command == 'e')

Control_dum (atoi(L_Data),atoi(R_Data),atoi(H_Data));

delay(10);

else if(command == 't')

Flash_Op(F_Data[0],F_Data[1],F_Data[2],F_Data[3],F_Data[4]);

lastTimeCommand = millis();

if(millis() >= (lastTimeCommand + autoOFF))

Control_dum(0,0,0);

void Control_dum (int mLeft, int mRight, uint8_t Horn)

{

bool directionL, directionR;

byte valueL, valueR;

if(mLeft > 0)

{

valueL = mLeft;

directionL = 0;

else if(mLeft < 0)

valueL = 255 - abs(mLeft);

directionL = 1;

else

{

directionL = 0;

valueL = 0;

if(mRight > 0)

valueR = mRight;

directionR = 0;

else if(mRight < 0)

valueR = 255 - abs(mRight);

directionR = 1;

else

directionR = 0;

valueR = 0;

}

analogWrite(M1, valueL);

analogWrite(M2, valueR);

digitalWrite(D1, directionL);

digitalWrite(D2, directionR);

digitalWrite(HORN, Horn);

}

void Flash_Op(char FCMD, uint8_t z1, uint8_t z2, uint8_t z3, uint8_t z4)

{

if(FCMD == cmdr)

Serial.print("FData:");

Serial.write(EEPROM.read(0));

Serial.write(EEPROM.read(1));

Serial.write(EEPROM.read(2));

Serial.write(EEPROM.read(3));

Serial.print("\r\n");

}

else if(FCMD == cmdw)

{

EEPROM.write(0,z1);

EEPROM.write(1,z2);

EEPROM.write(2,z3);

EEPROM.write(3,z4);

timer_init();

Serial.print("FWOK\r\n");

}

Додаток Б Код програми для Android-додатку

ActivityAbout.java

package com.dum_car;

import android.app.Activity;

import android.os.Bundle;

import android.text.Html;

import android.text.method.LinkMovementMethod;

import android.widget.TextView;

public class ActivityAbout extends Activity

{

@Override

protected void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_about);

TextView tv = (TextView) findViewById(R.id.textView2);

tv.setText(Html.fromHtml(getString(R.string.text_about)));

tv.setMovementMethod(LinkMovementMethod.getInstance());

}

@Override

protected void onResume()

{

super.onResume();

@Override

protected void onPause()

{

super.onPause();

}

ActivityAccelerometer.java

package com.dum_car;

import com.dum_car.R;

import java.lang.ref.WeakReference;

import java.util.Locale;

import com.dum_car.cBluetooth;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.app.Activity;

import android.bluetooth.BluetoothAdapter;

import android.content.Context;

import android.content.Intent;

import android.hardware.Sensor;

import android.hardware.SensorEvent;

import android.hardware.SensorEventListener;

import android.hardware.SensorManager;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.TextView;

import android.widget.Toast;

import android.widget.ToggleButton;

import android.content.SharedPreferences;

import android.preference.PreferenceManager;

public class ActivityAccelerometer extends Activity implements SensorEventListener

{

private SensorManager mSensorManager;

private Sensor mAccel;

private cBluetooth bl = null;

private ToggleButton LightButton;

private int xAxis = 0;

private int yAxis = 0;

private int motorLeft = 0;

private int motorRight = 0;

private String address;

private boolean show_Debug;

private boolean BT_is_connect;

private int xMax;

private int yMax;

private int yThreshold;

private int pwmMax;

private int xR;

private String commandLeft;

private String commandRight;

private String commandHorn;

@Override

public void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_accelerometer);

address = (String) getResources().getText(R.string.default_MAC);

xMax = Integer.parseInt((String) getResources().getText(R.string.default_xMax));

xR = Integer.parseInt((String) getResources().getText(R.string.default_xR));

yMax = Integer.parseInt((String) getResources().getText(R.string.default_yMax));

yThreshold = Integer.parseInt((String) getResources().getText(R.string.default_yThreshold));

pwmMax = Integer.parseInt((String) getResources().getText(R.string.default_pwmMax));

commandLeft = (String) getResources().getText(R.string.default_commandLeft);

commandRight = (String) getResources().getText(R.string.default_commandRight);

commandHorn = (String) getResources().getText(R.string.default_commandHorn);

loadPref();

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

mAccel = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

bl = new cBluetooth(this, mHandler);

bl.checkBTState();

LightButton = (ToggleButton) findViewById(R.id.LightButton);

LightButton.setOnClickListener(new OnClickListener()

{

public void onClick(View v)

if(LightButton.isChecked())

if(BT_is_connect) bl.sendData(String.valueOf(commandHorn+"1\r"));

else

if(BT_is_connect) bl.sendData(String.valueOf(commandHorn+"0\r"));

}

mHandler.postDelayed(sRunnable, 600000);

}

private static class MyHandler extends Handler

private final WeakReference<ActivityAccelerometer> mActivity;

public MyHandler(ActivityAccelerometer activity)

{

mActivity = new WeakReference<ActivityAccelerometer>(activity);

}

@Override

public void handleMessage(Message msg)

ActivityAccelerometer activity = mActivity.get();

if (activity != null)

switch (msg.what)

case cBluetooth.BL_NOT_AVAILABLE:

Log.d(cBluetooth.TAG, "Bluetooth is not available. Exit");

Toast.makeText(activity.getBaseContext(), "Bluetooth is not available", Toast.LENGTH_SHORT).show();

activity.finish();

break;

case cBluetooth.BL_INCORRECT_ADDRESS:

Log.d(cBluetooth.TAG, "Incorrect MAC address");

Toast.makeText(activity.getBaseContext(), "Incorrect Bluetooth address", Toast.LENGTH_SHORT).show();

break;

case cBluetooth.BL_REQUEST_ENABLE:

Log.d(cBluetooth.TAG, "Request Bluetooth Enable");

BluetoothAdapter.getDefaultAdapter();

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

activity.startActivityForResult(enableBtIntent, 1);

break;

case cBluetooth.BL_SOCKET_FAILED:

Toast.makeText(activity.getBaseContext(), "Socket failed", Toast.LENGTH_SHORT).show();

break;

}

private final MyHandler mHandler = new MyHandler(this);

private final static Runnable sRunnable = new Runnable()

public void run() { }

};

public void onSensorChanged(SensorEvent e)

{

String directionL = "";

String directionR = "";

String cmdSendL,cmdSendR;

xAxis = Math.round(e.values[0]*pwmMax/xR);

yAxis = Math.round(e.values[1]*pwmMax/yMax);

if(xAxis > pwmMax) xAxis = pwmMax;

else if(xAxis < -pwmMax) xAxis = -pwmMax;

if(yAxis > pwmMax) yAxis = pwmMax;

else if(yAxis < -pwmMax) yAxis = -pwmMax;

else if(yAxis >= 0 && yAxis < yThreshold) yAxis = 0;

else if(yAxis < 0 && yAxis > -yThreshold) yAxis = 0;

if(xAxis > 0)

{

motorRight = yAxis;

if(Math.abs(Math.round(e.values[0])) > xR)

motorLeft = Math.round((e.values[0]-xR)*pwmMax/(xMax-xR));

motorLeft = Math.round(-motorLeft * yAxis/pwmMax);

}

else motorLeft = yAxis - yAxis*xAxis/pwmMax;

else if(xAxis < 0)

{

motorLeft = yAxis;

if(Math.abs(Math.round(e.values[0])) > xR)

motorRight = Math.round((Math.abs(e.values[0])-xR)*pwmMax/(xMax-xR));

motorRight = Math.round(-motorRight * yAxis/pwmMax);

else motorRight = yAxis - yAxis*Math.abs(xAxis)/pwmMax;

else if(xAxis == 0)

motorLeft = yAxis;

motorRight = yAxis;

if(motorLeft > 0)

directionL = "-";

}

if(motorRight > 0)

directionR = "-";

motorLeft = Math.abs(motorLeft);

motorRight = Math.abs(motorRight);

if(motorLeft > pwmMax) motorLeft = pwmMax;

if(motorRight > pwmMax) motorRight = pwmMax;

cmdSendL = String.valueOf(commandLeft+directionL+motorLeft+"\r");

cmdSendR = String.valueOf(commandRight+directionR+motorRight+"\r");

if(BT_is_connect) bl.sendData(cmdSendL+cmdSendR);

TextView textX = (TextView) findViewById(R.id.textViewX);

TextView textY = (TextView) findViewById(R.id.textViewY);

TextView mLeft = (TextView) findViewById(R.id.mLeft);

TextView mRight = (TextView) findViewById(R.id.mRight);

TextView textCmdSend = (TextView) findViewById(R.id.textViewCmdSend);

if(show_Debug)

{

textX.setText(String.valueOf("X:" + String.format("%.1f",e.values[0]) + "; xPWM:"+xAxis));

textY.setText(String.valueOf("Y:" + String.format("%.1f",e.values[1]) + "; yPWM:"+yAxis))

mLeft.setText(String.valueOf("MotorL:" + directionL + "." + motorLeft))

mRight.setText(String.valueOf("MotorR:" + directionR + "." + motorRight));

textCmdSend.setText(String.valueOf("Send:" + cmdSendL.toUpperCase(Locale.getDefault()) + cmdSendR.toUpperCase(Locale.getDefault())));

}

else

{

textX.setText("");

textY.setText("");

mLeft.setText("");

mRight.setText("");

textCmdSend.setText("");

}

private void loadPref()

{

SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

address = mySharedPreferences.getString("pref_MAC_address", address);

xMax = Integer.parseInt(mySharedPreferences.getString("pref_xMax", String.valueOf(xMax)));

xR = Integer.parseInt(mySharedPreferences.getString("pref_xR", String.valueOf(xR)));

yMax = Integer.parseInt(mySharedPreferences.getString("pref_yMax", String.valueOf(yMax)));

yThreshold = Integer.parseInt(mySharedPreferences.getString("pref_yThreshold", String.valueOf(yThreshold)));

pwmMax = Integer.parseInt(mySharedPreferences.getString("pref_pwmMax", String.valueOf(pwmMax)));

show_Debug = mySharedPreferences.getBoolean("pref_Debug", false);

commandLeft = mySharedPreferences.getString("pref_commandLeft", commandLeft);

commandRight = mySharedPreferences.getString("pref_commandRight", commandRight);

commandHorn = mySharedPreferences.getString("pref_commandHorn", commandHorn);

}

@Override

protected void onResume()

{

super.onResume();

BT_is_connect = bl.BT_Connect(address, false);

mSensorManager.registerListener(this, mAccel, SensorManager.SENSOR_DELAY_NORMAL);

}

@Override

protected void onPause()

{

super.onPause();

l.BT_onPause();

mSensorManager.unregisterListener(this);

}

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data)

{

loadPref();

public void onAccuracyChanged(Sensor arg0, int arg1) { }

}

ActivityButtons.java

package com.dum_car;

import com.dum_car.cBluetooth;

import com.dum_car.R;

import java.lang.ref.WeakReference;

import android.app.Activity;

import android.bluetooth.BluetoothAdapter;

import android.content.Intent;

import android.content.SharedPreferences;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.preference.PreferenceManager;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.View.OnTouchListener;

import android.view.MotionEvent;

import android.widget.Button;

import android.widget.Toast;

import android.widget.ToggleButton;

public class ActivityButtons extends Activity

{

private cBluetooth bl = null;

private ToggleButton LightButton;

private Button btn_forward, btn_backward, btn_left, btn_right;

private int motorLeft = 0;

private int motorRight = 0;

private String address;

private int pwmBtnMotorLeft;

private int pwmBtnMotorRight;

private String commandLeft;

private String commandRight;

private String commandHorn;

private boolean BT_is_connect;

@Override

protected void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_buttons);

address = (String) getResources().getText(R.string.default_MAC);

pwmBtnMotorLeft = nteger.parseInt((String)getResources().getText(R.string.default_pwmBtnMotorLeft));

pwmBtnMotorRight = Integer.parseInt((String)getResources().getText(R.string.default_pwmBtnMotorRight));

commandLeft = (String) getResources().getText(R.string.default_commandLeft);

commandRight = (String) getResources().getText(R.string.default_commandRight);

commandHorn = (String) getResources().getText(R.string.default_commandHorn);

loadPref();

bl = new cBluetooth(this, mHandler);

bl.checkBTState();

btn_forward = (Button) findViewById(R.id.forward);

btn_backward = (Button) findViewById(R.id.backward);

btn_left = (Button) findViewById(R.id.left);

btn_right = (Button) findViewById(R.id.right);

btn_forward.setOnTouchListener(new OnTouchListener()

{

public boolean onTouch(View v, MotionEvent event)

if(event.getAction() == MotionEvent.ACTION_MOVE)

motorLeft = pwmBtnMotorLeft;

motorRight = pwmBtnMotorRight;

if(BT_is_connect) bl.sendData(String.valueOf(commandLeft+motorLeft+"\r"+commandRight+motorRight+"\r"));

}

else if (event.getAction() == MotionEvent.ACTION_UP)

{

motorLeft = 0;

motorRight = 0;

if(BT_is_connect)bl.sendData(String.valueOf(commandLeft+motorLeft+"\r"+commandRight+motorRight+"\r"));

}

return false;

btn_left.setOnTouchListener(new OnTouchListener()

{

public boolean onTouch(View v, MotionEvent event)

if(event.getAction() == MotionEvent.ACTION_MOVE)

motorLeft = -pwmBtnMotorLeft;

motorRight = pwmBtnMotorRight;

if(BT_is_connect) bl.sendData(String.valueOf(commandLeft+motorLeft+"\r"+commandRight+motorRight+"\r"));

else if (event.getAction() == MotionEvent.ACTION_UP)

{

motorLeft = 0;

motorRight = 0;

if(BT_is_connect) bl.sendData(String.valueOf(commandLeft+motorLeft+"\r"+commandRight+motorRight+"\r"));

return false;

}

btn_right.setOnTouchListener(new OnTouchListener()

{

public boolean onTouch(View v, MotionEvent event)

if(event.getAction() == MotionEvent.ACTION_MOVE)

motorLeft = pwmBtnMotorLeft;

motorRight = -pwmBtnMotorRight;

if(BT_is_connect) bl.sendData(String.valueOf(commandLeft+motorLeft+"\r"+commandRight+motorRight+"\r"));

}

else if (event.getAction() == MotionEvent.ACTION_UP)

{

motorLeft = 0;

motorRight = 0;

if(BT_is_connect) bl.sendData(String.valueOf(commandLeft+motorLeft+"\r"+commandRight+motorRight+"\r"));

return false;

btn_backward.setOnTouchListener(new OnTouchListener()

{

public boolean onTouch(View v, MotionEvent event)

if(event.getAction() == MotionEvent.ACTION_MOVE)

motorLeft = -pwmBtnMotorLeft;

motorRight = -pwmBtnMotorRight;

if(BT_is_connect) bl.sendData(String.valueOf(commandLeft+motorLeft+"\r"+commandRight+motorRight+"\r"));

}

else if (event.getAction() == MotionEvent.ACTION_UP)

motorLeft = 0;

motorRight = 0;

if(BT_is_connect) bl.sendData(String.valueOf(commandLeft+motorLeft+"\r"+commandRight+motorRight+"\r"));

return false;

LightButton = (ToggleButton) findViewById(R.id.LightButton);

LightButton.setOnClickListener(new OnClickListener()

{

public void onClick(View v)

if(LightButton.isChecked())

if(BT_is_connect) bl.sendData(String.valueOf(commandHorn+"1\r"));

}

else

if(BT_is_connect) bl.sendData(String.valueOf(commandHorn+"0\r"));

mHandler.postDelayed(sRunnable, 600000);

private static class MyHandler extends Handler

{

private final WeakReference<ActivityButtons> mActivity;

public MyHandler(ActivityButtons activity)

mActivity = new WeakReference<ActivityButtons>(activity);

}

@Override

public void handleMessage(Message msg)

{

ActivityButtons activity = mActivity.get();

if (activity != null)

switch (msg.what)

case cBluetooth.BL_NOT_AVAILABLE:

Log.d(cBluetooth.TAG, "Bluetooth is not available. Exit");

Toast.makeText(activity.getBaseContext(), "Bluetooth is not available", Toast.LENGTH_SHORT).show();

activity.finish();

break;

case cBluetooth.BL_INCORRECT_ADDRESS:

Log.d(cBluetooth.TAG, "Incorrect MAC address");

Toast.makeText(activity.getBaseContext(), "Incorrect Bluetooth address", Toast.LENGTH_SHORT).show();

break;

case cBluetooth.BL_REQUEST_ENABLE:

Log.d(cBluetooth.TAG, "Request Bluetooth Enable");

BluetoothAdapter.getDefaultAdapter();

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

activity.startActivityForResult(enableBtIntent, 1);

break;

case cBluetooth.BL_SOCKET_FAILED:

Toast.makeText(activity.getBaseContext(), "Socket failed", Toast.LENGTH_SHORT).show();

break;

}

private final MyHandler mHandler = new MyHandler(this);

private final static Runnable sRunnable = new Runnable()

{

public void run() { }

};

private void loadPref()

{

SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

address = mySharedPreferences.getString("pref_MAC_address", address);

pwmBtnMotorLeft=Integer.parseInt(mySharedPreferences.getString("pref_pwmBtnMotorLeft",String.valueOf(pwmBtnMotorLeft)));

pwmBtnMotorRight = Integer.parseInt(mySharedPreferences.getString("pref_pwmBtnMotorRight", String.valueOf(pwmBtnMotorRight)));

commandLeft = mySharedPreferences.getString("pref_commandLeft", commandLeft);

commandRight = mySharedPreferences.getString("pref_commandRight", commandRight);

commandHorn = mySharedPreferences.getString("pref_commandHorn", commandHorn);

}

@Override

protected void onResume()

{

super.onResume();

BT_is_connect = bl.BT_Connect(address, false);

}

@Override

protected void onPause()

{

super.onPause();

bl.BT_onPause();

}

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data)

{

loadPref();

}

ActivityMCU.java

package com.dum_car;

import java.lang.ref.WeakReference;

import java.text.DecimalFormat;

import android.app.Activity;

import android.bluetooth.BluetoothAdapter;

import android.content.Intent;

import android.content.SharedPreferences;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.preference.PreferenceManager;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.CheckBox;

import android.widget.CompoundButton;

import android.widget.EditText;

import android.widget.Toast;

public class ActivityMCU extends Activity

{

private cBluetooth bl = null;

private Button btn_flash_Read, btn_flash_Write;

private static CheckBox cb_AutoOFF;

private static EditText edit_AutoOFF;

private static String flash_success;

private static String error_get_data;

private String address;

private static StringBuilder sb = new StringBuilder();

@Override

public void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_mcu);

address = (String) getResources().getText(R.string.default_MAC);

btn_flash_Read = (Button) findViewById(R.id.flash_Read);

btn_flash_Write = (Button) findViewById(R.id.flash_Write);

cb_AutoOFF = (CheckBox) findViewById(R.id.cBox_AutoOFF);

edit_AutoOFF = (EditText) findViewById(R.id.AutoOFF);

flash_success = (String) getResources().getText(R.string.flash_success);

error_get_data = (String) getResources().getText(R.string.error_get_data);

loadPref();

bl = new cBluetooth(this, mHandler);

bl.checkBTState();

cb_AutoOFF.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()

{

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)

{

if (isChecked) edit_AutoOFF.setEnabled(true);

else if (!isChecked) edit_AutoOFF.setEnabled(false);

}

btn_flash_Read.setOnClickListener(new OnClickListener()

{

public void onClick(View v)

bl.sendData(String.valueOf("Fr\t"));

}

btn_flash_Write.setOnClickListener(new OnClickListener()

{

public void onClick(View v)

float num1 = 0;

String str_to_send = "Fw";

if(cb_AutoOFF.isChecked())

str_to_send += "1";

}

else str_to_send += "0";

try

{

num1 = Float.parseFloat(edit_AutoOFF.getText().toString());

catch (NumberFormatException e)

String err_data_entry = getString(R.string.err_data_entry);

Toast.makeText(getBaseContext(), err_data_entry, Toast.LENGTH_SHORT).show();

}

if(num1 > 0 && num1 < 100)

{

DecimalFormat myFormatter = new DecimalFormat("00.0");

String output = myFormatter.format(num1);

str_to_send+=String.valueOf(output.charAt(0))+String.valueOf(output.charAt(1)) +String.valueOf(output.charAt(3));

str_to_send += "\t";

Log.d(cBluetooth.TAG, "Send Flash Op:" + str_to_send);

bl.sendData(str_to_send);

}

else

{

String err_range = getString(R.string.mcu_error_range);

Toast.makeText(getBaseContext(), err_range, Toast.LENGTH_SHORT).show();

}

mHandler.postDelayed(sRunnable, 600000);

}

private static class MyHandler extends Handler

{

private final WeakReference<ActivityMCU> mActivity;

public MyHandler(ActivityMCU activity) {

mActivity = new WeakReference<ActivityMCU>(activity);

}

@Override

public void handleMessage(Message msg)

{

ActivityMCU activity = mActivity.get();

if (activity != null)

{

switch (msg.what)

{

case cBluetooth.BL_NOT_AVAILABLE:

Log.d(cBluetooth.TAG, "Bluetooth is not available. Exit");

Toast.makeText(activity.getBaseContext(), "Bluetooth is not available", Toast.LENGTH_SHORT).show();

activity.finish();

break;

case cBluetooth.BL_INCORRECT_ADDRESS:

Log.d(cBluetooth.TAG, "Incorrect MAC address");

Toast.makeText(activity.getBaseContext(), "Incorrect Bluetooth address", Toast.LENGTH_SHORT).show();

break;

case cBluetooth.BL_REQUEST_ENABLE:

Log.d(cBluetooth.TAG, "Request Bluetooth Enable");

BluetoothAdapter.getDefaultAdapter();

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

activity.startActivityForResult(enableBtIntent, 1);

break;

case cBluetooth.BL_SOCKET_FAILED:

Toast.makeText(activity.getBaseContext(), "Socket failed", Toast.LENGTH_SHORT).show();

activity.finish();

break;

case cBluetooth.RECIEVE_MESSAGE:

byte[] readBuf = (byte[]) msg.obj;

String strIncom = new String(readBuf, 0, msg.arg1);

sb.append(strIncom);

int FDataLineIndex = sb.indexOf("FData:");

int FWOKLineIndex = sb.indexOf("FWOK");

int endOfLineIndex = sb.indexOf("\r\n");

if (FDataLineIndex >= 0 && endOfLineIndex > 0 && endOfLineIndex > FDataLineIndex)

{

String sbprint = sb.substring("FData:".length(), endOfLineIndex);

if(sbprint.substring(0, 1).equals("1")) cb_AutoOFF.setChecked(true);

else cb_AutoOFF.setChecked(false);

Float edit_data_AutoOFF = Float.parseFloat(sbprint.substring(1, 4))/10;

edit_AutoOFF.setText(String.valueOf(edit_data_AutoOFF));

sb.delete(0, sb.length());

}

else if (FWOKLineIndex >= 0 && endOfLineIndex > 0 && endOfLineIndex > FWOKLineIndex) {

Toast.makeText(activity.getBaseContext(), flash_success, Toast.LENGTH_SHORT).show();

sb.delete(0, sb.length());

}

else if(endOfLineIndex > 0)

{

Toast.makeText(activity.getBaseContext(), error_get_data, Toast.LENGTH_SHORT).show();

sb.delete(0, sb.length());

}

break;

}

private final MyHandler mHandler = new MyHandler(this);

private final static Runnable sRunnable = new Runnable()

{

public void run() { }

};

private void loadPref()

{

SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

address = mySharedPreferences.getString("pref_MAC_address", address);

}

@Override

protected void onResume()

{

super.onResume();

if(cb_AutoOFF.isChecked()) edit_AutoOFF.setEnabled(true);

else edit_AutoOFF.setEnabled(false);

bl.BT_Connect(address, true);

}

@Override

protected void onPause()

{

super.onPause();

bl.BT_onPause();

}

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data)

{

loadPref();

}

ActivityTouch.java

package com.dum_car;

import com.dum_car.cBluetooth;

import com.dum_car.R;

import java.lang.ref.WeakReference;

import android.app.Activity;

import android.bluetooth.BluetoothAdapter;

import android.content.Context;

import android.content.Intent;

import android.content.SharedPreferences;

import android.graphics.Canvas;

import android.graphics.Color;

import android.graphics.Paint;

import android.graphics.Paint.Style;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.preference.PreferenceManager;

import android.util.Log;

import android.view.MotionEvent;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.ViewGroup.LayoutParams;

import android.widget.Toast;

import android.widget.ToggleButton;

public class ActivityTouch extends Activity {

private cBluetooth bl = null;

private final static int BIG_CIRCLE_SIZE = 120;

private final static int FINGER_CIRCLE_SIZE = 20;

private int motorLeft = 0;

private int motorRight = 0;

private String address;

private boolean show_Debug;

private boolean BT_is_connect;

private int xRperc;

private int pwmMax;

private String commandLeft;

private String commandRight;

private String commandHorn;

private String cmdSendL,cmdSendR;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

MyView v1 = new MyView(this);

setContentView(v1);

address = (String) getResources().getText(R.string.default_MAC);

xRperc = Integer.parseInt((String) getResources().getText(R.string.default_xRperc));

pwmMax = Integer.parseInt((String) getResources().getText(R.string.default_pwmMax));

commandLeft = (String) getResources().getText(R.string.default_commandLeft);

commandRight = (String) getResources().getText(R.string.default_commandRight);

commandHorn = (String) getResources().getText(R.string.default_commandHorn);

loadPref();

bl = new cBluetooth(this, mHandler);

bl.checkBTState();

final ToggleButton myLightButton = new ToggleButton(this);

addContentView(myLightButton, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

myLightButton.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

if(myLightButton.isChecked()){

if(BT_is_connect) bl.sendData(String.valueOf(commandHorn+"1\r"));

}else{

if(BT_is_connect) bl.sendData(String.valueOf(commandHorn+"0\r"));

}

mHandler.postDelayed(sRunnable, 600000);

}

private static class MyHandler extends Handler {

private final WeakReference<ActivityTouch> mActivity;

public MyHandler(ActivityTouch activity) {

mActivity = new WeakReference<ActivityTouch>(activity);

}

@Override

public void handleMessage(Message msg) {

ActivityTouch activity = mActivity.get();

if (activity != null) {

switch (msg.what) {

case cBluetooth.BL_NOT_AVAILABLE:

Log.d(cBluetooth.TAG, "Bluetooth is not available. Exit");

Toast.makeText(activity.getBaseContext(), "Bluetooth is not available", Toast.LENGTH_SHORT).show();

activity.finish();

break;

case cBluetooth.BL_INCORRECT_ADDRESS:

Log.d(cBluetooth.TAG, "Incorrect MAC address");

Toast.makeText(activity.getBaseContext(), "Incorrect Bluetooth address", Toast.LENGTH_SHORT).show();

break;

case cBluetooth.BL_REQUEST_ENABLE:

Log.d(cBluetooth.TAG, "Request Bluetooth Enable");

BluetoothAdapter.getDefaultAdapter();

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

activity.startActivityForResult(enableBtIntent, 1);

break;

case cBluetooth.BL_SOCKET_FAILED:

Toast.makeText(activity.getBaseContext(), "Socket failed", Toast.LENGTH_SHORT).show();

break;

}

private final MyHandler mHandler = new MyHandler(this);

private final static Runnable sRunnable = new Runnable() {

public void run() { }

};

class MyView extends View {

Paint fingerPaint, borderPaint, textPaint;

int dispWidth;

int dispHeight;

float x;

float y;

float xcirc;

float ycirc;

String directionL = "";

String directionR = "";

boolean drag = false;

float dragX = 0;

float dragY = 0;

public MyView(Context context) {

super(context);

fingerPaint = new Paint();

fingerPaint.setAntiAlias(true);

fingerPaint.setColor(Color.RED);

borderPaint = new Paint();

borderPaint.setColor(Color.BLUE);

borderPaint.setAntiAlias(true);

borderPaint.setStyle(Style.STROKE);

borderPaint.setStrokeWidth(3);

textPaint = new Paint();

textPaint.setColor(Color.WHITE);

textPaint.setStyle(Style.FILL);

textPaint.setColor(Color.BLACK);

textPaint.setTextSize(14);

}

protected void onDraw(Canvas canvas) {

dispWidth = (int) Math.round((this.getRight()-this.getLeft())/3.5);

dispHeight = (int) Math.round((this.getBottom()-this.getTop())/1.7);

if(!drag){

x = dispWidth;

y = dispHeight;

fingerPaint.setColor(Color.RED);

}

canvas.drawCircle(x, y, FINGER_CIRCLE_SIZE, fingerPaint);

canvas.drawCircle(dispWidth, dispHeight, BIG_CIRCLE_SIZE, borderPaint);

if(show_Debug){

canvas.drawText(String.valueOf("X:"+xcirc), 10, 75, textPaint);

canvas.drawText(String.valueOf("Y:"+(-ycirc)), 10, 95, textPaint);

canvas.drawText(String.valueOf("Motor:"+cmdSendL+cmdSendR), 10, 115, textPaint);

}

@Override

public boolean onTouchEvent(MotionEvent event) {

float evX = event.getX();

float evY = event.getY();

xcirc = event.getX() - dispWidth;

ycirc = event.getY() - dispHeight;

float radius = (float) Math.sqrt(Math.pow(Math.abs(xcirc),2)+Math.pow(Math.abs(ycirc),2));

switch (event.getAction()) {

case MotionEvent.ACTION_DOWN:

if(radius >= 0 && radius <= BIG_CIRCLE_SIZE){

x = evX;

y = evY;

fingerPaint.setColor(Color.GREEN);

CalcMotor(xcirc,ycirc);

invalidate();

drag = true;

}

break;

case MotionEvent.ACTION_MOVE:

if (drag && radius >= 0 && radius <= BIG_CIRCLE_SIZE) {

x = evX;

y = evY;

fingerPaint.setColor(Color.GREEN);

CalcMotor(xcirc,ycirc);

invalidate();

}

break;

case MotionEvent.ACTION_UP:

xcirc = 0;

ycirc = 0;

drag = false;

CalcMotor(xcirc,ycirc);

invalidate();

break;

}

return true;

}

private void CalcMotor(float calc_x, float calc_y){

String directionL = "";

String directionR = "";

calc_x = -calc_x;

int xAxis = Math.round(calc_x*pwmMax/BIG_CIRCLE_SIZE);

int yAxis = Math.round(calc_y*pwmMax/BIG_CIRCLE_SIZE);

int xR = Math.round(BIG_CIRCLE_SIZE*xRperc/100);

if(xAxis > 0) {

motorRight = yAxis;

if(Math.abs(Math.round(calc_x)) > xR){

motorLeft = Math.round((calc_x-xR)*pwmMax/(BIG_CIRCLE_SIZE-xR));

motorLeft = Math.round(-motorLeft * yAxis/pwmMax);

}

else motorLeft = yAxis - yAxis*xAxis/pwmMax;

}

else if(xAxis < 0) {

motorLeft = yAxis;

if(Math.abs(Math.round(calc_x)) > xR){

motorRight = Math.round((Math.abs(calc_x)-xR)*pwmMax/(BIG_CIRCLE_SIZE-xR));

motorRight = Math.round(-motorRight * yAxis/pwmMax);

}

else motorRight = yAxis - yAxis*Math.abs(xAxis)/pwmMax;

}

else if(xAxis == 0) {

motorLeft = yAxis;

motorRight = yAxis;

}

if(motorLeft > 0) {

directionL = "-";

}

if(motorRight > 0) {

directionR = "-";

}

motorLeft = Math.abs(motorLeft);

motorRight = Math.abs(motorRight);

if(motorLeft > pwmMax) motorLeft = pwmMax;

if(motorRight > pwmMax) motorRight = pwmMax;

cmdSendL = String.valueOf(commandLeft+directionL+motorLeft+"\r");

cmdSendR = String.valueOf(commandRight+directionR+motorRight+"\r");

if(BT_is_connect) bl.sendData(cmdSendL + cmdSendR);

}

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

loadPref();

}

@Override

protected void onResume() {

super.onResume();

BT_is_connect = bl.BT_Connect(address, false);

}

@Override

protected void onPause() {

super.onPause();

bl.BT_onPause();

}

private void loadPref(){

SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

address = mySharedPreferences.getString("pref_MAC_address", address); xRperc = Integer.parseInt(mySharedPreferences.getString("pref_xRperc", String.valueOf(xRperc)));

pwmMax = Integer.parseInt(mySharedPreferences.getString("pref_pwmMax", String.valueOf(pwmMax)));

show_Debug = mySharedPreferences.getBoolean("pref_Debug", false);

commandLeft = mySharedPreferences.getString("pref_commandLeft", commandLeft);

commandRight = mySharedPreferences.getString("pref_commandRight", commandRight);

commandHorn = mySharedPreferences.getString("pref_commandHorn", commandHorn);

}

АctivityWheel.java

package com.dum_car;

import java.lang.ref.WeakReference;

import java.util.Locale;

import com.dum_car.cBluetooth;

import com.dum_car.R;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.app.Activity;

import android.bluetooth.BluetoothAdapter;

import android.content.Context;

import android.content.Intent;

import android.hardware.Sensor;

import android.hardware.SensorEvent;

import android.hardware.SensorEventListener;

import android.hardware.SensorManager;

import android.util.Log;

import android.view.MotionEvent;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.View.OnTouchListener;

import android.widget.Button;

import android.widget.SeekBar;

import android.widget.TextView;

import android.widget.Toast;

import android.widget.ToggleButton;

import android.content.SharedPreferences;

import android.preference.PreferenceManager;

public class ActivityWheel extends Activity implements SensorEventListener {

private SensorManager mSensorManager;

private Sensor mAccel;

private cBluetooth bl = null;

private ToggleButton LightButton;

private Button btn_Rear;

private VerticalSeekBar VSeekBar;

private int xAxis = 0;

private int yAxis = 0;

private int motorLeft = 0;

private int motorRight = 0;

private float xgl = 0;

private boolean isRear = false;

private String address;

private boolean show_Debug;

private boolean BT_is_connect;

private int xMax;

private int yMax;

private int yThreshold; )

private int pwmMax;

private int xR;

private String commandLeft;

private String commandRight;

private String commandHorn;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_wheel);

address = (String) getResources().getText(R.string.default_MAC);

xMax = Integer.parseInt((String) getResources().getText(R.string.default_xMax));

xR = Integer.parseInt((String) getResources().getText(R.string.default_xR));

yMax = Integer.parseInt((String) getResources().getText(R.string.default_yMax));

yThreshold = Integer.parseInt((String) getResources().getText(R.string.default_yThreshold));

pwmMax = Integer.parseInt((String) getResources().getText(R.string.default_pwmMax));

commandLeft = (String) getResources().getText(R.string.default_commandLeft);

commandRight = (String) getResources().getText(R.string.default_commandRight);

commandHorn = (String) getResources().getText(R.string.default_commandHorn);

loadPref();

mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

mAccel = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

bl = new cBluetooth(this, mHandler);

bl.checkBTState();

VSeekBar = (VerticalSeekBar) findViewById(R.id.calcVerticalSeekBar);

VSeekBar.setMaximum(pwmMax);

LightButton = (ToggleButton) findViewById(R.id.LightButton);

btn_Rear = (Button) findViewById(R.id.btnRear);

LightButton.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

if(LightButton.isChecked()){

if(BT_is_connect) bl.sendData(String.valueOf(commandHorn+"1\r"));

}else{

if(BT_is_connect) bl.sendData(String.valueOf(commandHorn+"0\r"));

}

btn_Rear.setOnTouchListener(new OnTouchListener() {

public boolean onTouch(View v, MotionEvent event) {

if(event.getAction() == MotionEvent.ACTION_MOVE) {

isRear = true;

} else if (event.getAction() == MotionEvent.ACTION_UP) {

isRear = false;

}

return false;

VSeekBar.setOnSeekBarChangeListener(new VerticalSeekBar.OnSeekBarChangeListener() {

public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

MotionChanged(xgl,progress);

}

public void onStartTrackingTouch(SeekBar seekBar) { }

public void onStopTrackingTouch(SeekBar seekBar) {

VSeekBar.setProgressAndThumb(0);

}

mHandler.postDelayed(sRunnable, 600000);

}

private static class MyHandler extends Handler {

private final WeakReference<ActivityWheel> mActivity;

public MyHandler(ActivityWheel activity) {

mActivity = new WeakReference<ActivityWheel>(activity);

}

@Override

public void handleMessage(Message msg) {

ActivityWheel activity = mActivity.get();

if (activity != null) {

switch (msg.what) {

case cBluetooth.BL_NOT_AVAILABLE:

Log.d(cBluetooth.TAG, "Bluetooth is not available. Exit");

Toast.makeText(activity.getBaseContext(), "Bluetooth is not available", Toast.LENGTH_SHORT).show();

activity.finish();

break;

case cBluetooth.BL_INCORRECT_ADDRESS:

Log.d(cBluetooth.TAG, "Incorrect MAC address");

Toast.makeText(activity.getBaseContext(), "Incorrect Bluetooth address", Toast.LENGTH_SHORT).show();

break;

case cBluetooth.BL_REQUEST_ENABLE:

Log.d(cBluetooth.TAG, "Request Bluetooth Enable");

BluetoothAdapter.getDefaultAdapter();

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

activity.startActivityForResult(enableBtIntent, 1);

break;

case cBluetooth.BL_SOCKET_FAILED:

Toast.makeText(activity.getBaseContext(), "Socket failed", Toast.LENGTH_SHORT).show();

break;

}

private final MyHandler mHandler = new MyHandler(this);

private final static Runnable sRunnable = new Runnable() {

public void run() { }

};

public void onSensorChanged(SensorEvent e) {

MotionChanged(e.values[0],VSeekBar.getProgress());

xgl = e.values[0];

}

private void MotionChanged(float x, int y) {

String directionL = "";

String directionR = "";

String cmdSendL,cmdSendR;

Log.d(cBluetooth.TAG, Math.round(x)+" "+y);

xAxis = Math.round(x*pwmMax/xR);

if(isRear) yAxis = y;

else yAxis = -y;

if(xAxis > pwmMax) xAxis = pwmMax;

else if(xAxis < -pwmMax) xAxis = -pwmMax;

if(yAxis > pwmMax) yAxis = pwmMax;

else if(yAxis < -pwmMax) yAxis = -pwmMax;

else if(yAxis >= 0 && yAxis < yThreshold) yAxis = 0;

else if(yAxis < 0 && yAxis > -yThreshold) yAxis = 0;

if(xAxis > 0) {

motorRight = yAxis;

if(Math.abs(Math.round(x)) > xR){

motorLeft = Math.round((x-xR)*pwmMax/(xMax-xR));

motorLeft = Math.round(-motorLeft * yAxis/pwmMax);

}

else motorLeft = yAxis - yAxis*xAxis/pwmMax;

}

else if(xAxis < 0) {

motorLeft = yAxis;

if(Math.abs(Math.round(x)) > xR){

motorRight = Math.round((Math.abs(x)-xR)*pwmMax/(xMax-xR));

motorRight = Math.round(-motorRight * yAxis/pwmMax);

else motorRight = yAxis - yAxis*Math.abs(xAxis)/pwmMax;

else if(xAxis == 0) {

motorLeft = yAxis;

motorRight = yAxis;

if(motorLeft > 0) {

directionL = "-";

}

if(motorRight > 0) {

directionR = "-";

}

motorLeft = Math.abs(motorLeft);

motorRight = Math.abs(motorRight);

if(motorLeft > pwmMax) motorLeft = pwmMax;

if(motorRight > pwmMax) motorRight = pwmMax;

cmdSendL = String.valueOf(commandLeft+directionL+motorLeft+"\r");

cmdSendR = String.valueOf(commandRight+directionR+motorRight+"\r");

if(BT_is_connect) bl.sendData(cmdSendL+cmdSendR);

TextView textX = (TextView) findViewById(R.id.textViewX);

TextView textY = (TextView) findViewById(R.id.textViewY);

TextView mLeft = (TextView) findViewById(R.id.mLeft);

TextView mRight = (TextView) findViewById(R.id.mRight);

TextView textCmdSend = (TextView) findViewById(R.id.textViewCmdSend);

if(show_Debug){

textX.setText(String.valueOf("X:" + String.format("%.1f",x) + "; xPWM:"+xAxis));

textY.setText(String.valueOf("Y:" + String.valueOf(y) + "; yPWM:"+yAxis));

mLeft.setText(String.valueOf("MotorL:" + directionL + "." + motorLeft));

mRight.setText(String.valueOf("MotorR:" + directionR + "." + motorRight));

textCmdSend.setText(String.valueOf("Send:" + cmdSendL.toUpperCase(Locale.getDefault()) + cmdSendR.toUpperCase(Locale.getDefault())));

}

else{

textX.setText("");

textY.setText("");

mLeft.setText("");

mRight.setText("");

textCmdSend.setText("");

}

private void loadPref(){

SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

address = mySharedPreferences.getString("pref_MAC_address", address); xMax = Integer.parseInt(mySharedPreferences.getString("pref_xMax", String.valueOf(xMax)));

xR = Integer.parseInt(mySharedPreferences.getString("pref_xR", String.valueOf(xR)));

yMax = Integer.parseInt(mySharedPreferences.getString("pref_yMax", String.valueOf(yMax)));

yThreshold = Integer.parseInt(mySharedPreferences.getString("pref_yThreshold", String.valueOf(yThreshold)));

pwmMax = Integer.parseInt(mySharedPreferences.getString("pref_pwmMax", String.valueOf(pwmMax)));

show_Debug = mySharedPreferences.getBoolean("pref_Debug", false);

commandLeft = mySharedPreferences.getString("pref_commandLeft", commandLeft);

commandRight = mySharedPreferences.getString("pref_commandRight", commandRight);

commandHorn = mySharedPreferences.getString("pref_commandHorn", commandHorn);

}

@Override

protected void onResume() {

super.onResume();

BT_is_connect = bl.BT_Connect(address, false);

mSensorManager.registerListener(this, mAccel, SensorManager.SENSOR_DELAY_NORMAL);

}

@Override

protected void onPause() {

super.onPause();

bl.BT_onPause();

mSensorManager.unregisterListener(this);

}

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

loadPref();

}

public void onAccuracyChanged(Sensor arg0, int arg1) { }

}

cBluetooth.java

package com.dum_car;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.lang.reflect.Method;

import java.util.UUID;

import android.bluetooth.BluetoothAdapter;

import android.bluetooth.BluetoothDevice;

import android.bluetooth.BluetoothSocket;

import android.content.Context;

import android.os.Build;

import android.os.Handler;

import android.util.Log;

public class cBluetooth{

public final static String TAG = "BL_4WD";

private static BluetoothAdapter btAdapter = null;

private BluetoothSocket btSocket = null;

private OutputStream outStream = null;

private ConnectedThread mConnectedThread;

private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

private final Handler mHandler;

public final static int BL_NOT_AVAILABLE = 1;

public final static int BL_INCORRECT_ADDRESS = 2;

public final static int BL_REQUEST_ENABLE = 3;

public final static int BL_SOCKET_FAILED = 4;

public final static int RECIEVE_MESSAGE = 5;

cBluetooth(Context context, Handler handler){

btAdapter = BluetoothAdapter.getDefaultAdapter();

mHandler = handler;

if (btAdapter == null) {

mHandler.sendEmptyMessage(BL_NOT_AVAILABLE);

return;

}

public void checkBTState() {

if(btAdapter == null) {

mHandler.sendEmptyMessage(BL_NOT_AVAILABLE);

} else {

if (btAdapter.isEnabled()) {

Log.d(TAG, "Bluetooth ON");

} else {

mHandler.sendEmptyMessage(BL_REQUEST_ENABLE);

}

private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {

if(Build.VERSION.SDK_INT >= 10){

try {

final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });

return (BluetoothSocket) m.invoke(device, MY_UUID);

} catch (Exception e) {

Log.e(TAG, "Could not create Insecure RFComm Connection",e);

}

return device.createRfcommSocketToServiceRecord(MY_UUID);

public boolean BT_Connect(String address, boolean listen_InStream) {

Log.d(TAG, "...On Resume...");

boolean connected = false;

if(!BluetoothAdapter.checkBluetoothAddress(address)){

mHandler.sendEmptyMessage(BL_INCORRECT_ADDRESS);

return false;

}

else{

BluetoothDevice device = btAdapter.getRemoteDevice(address);

try {

btSocket = createBluetoothSocket(device);

} catch (IOException e1) {

Log.e(TAG, "In BT_Connect() socket create failed: " + e1.getMessage());

mHandler.sendEmptyMessage(BL_SOCKET_FAILED);

return false;

}

btAdapter.cancelDiscovery();

Log.d(TAG, "...Connecting...");

try {

btSocket.connect();

Log.d(TAG, "...Connection ok...");

} catch (IOException e) {

try {

btSocket.close();

} catch (IOException e2) {

Log.e(TAG, "In BT_Connect() unable to close socket during connection failure" + e2.getMessage());

mHandler.sendEmptyMessage(BL_SOCKET_FAILED);

return false;

}

Log.d(TAG, "...Create Socket...");

try {

outStream = btSocket.getOutputStream();

connected = true;

} catch (IOException e) {

Log.e(TAG, "In BT_Connect() output stream creation failed:" + e.getMessage());

mHandler.sendEmptyMessage(BL_SOCKET_FAILED);

return false;

}

if(listen_InStream) {

mConnectedThread = new ConnectedThread();

mConnectedThread.start();

}

return connected;

}

public void BT_onPause() {

Log.d(TAG, "...On Pause...");

if (outStream != null) {

try {

outStream.flush();

} catch (IOException e) {

Log.e(TAG, "In onPause() and failed to flush output stream: " + e.getMessage());

mHandler.sendEmptyMessage(BL_SOCKET_FAILED);

return;

}

if (btSocket != null) {

try {

btSocket.close();

} catch (IOException e2) {

Log.e(TAG, "In onPause() and failed to close socket." + e2.getMessage());

mHandler.sendEmptyMessage(BL_SOCKET_FAILED);

return;

}

public void sendData(String message) {

byte[] msgBuffer = message.getBytes();

Log.i(TAG, "Send data: " + message);

if (outStream != null) {

try {

outStream.write(msgBuffer);

} catch (IOException e) {

Log.e(TAG, "In onResume() exception occurred during write: " + e.getMessage());

mHandler.sendEmptyMessage(BL_SOCKET_FAILED);

return;

} else Log.e(TAG, "Error Send data: outStream is Null");

}

private class ConnectedThread extends Thread {

private final InputStream mmInStream;

public ConnectedThread() {

InputStream tmpIn = null;

try {

tmpIn = btSocket.getInputStream();

} catch (IOException e) {

Log.e(TAG, "In ConnectedThread() error getInputStream(): " + e.getMessage());

}

mmInStream = tmpIn;

}

public void run() {

byte[] buffer = new byte[256];

int bytes;

while (true) {

try {

bytes = mmInStream.read(buffer);

mHandler.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget();

} catch (IOException e) {

break;

}

MainActivity.java

package com.dum_car;

import android.app.Activity;

import android.content.Intent;

import android.graphics.Color;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

Button btnActAccelerometer, btnActWheel, btnActButtons, btnActMCU, btnActTouch, btnActAbout;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

TextView textv = (TextView) findViewById(R.id.textView1);

textv.setShadowLayer(1, 3, 3, Color.GRAY);

btnActAccelerometer = (Button) findViewById(R.id.button_accel);

btnActAccelerometer.setOnClickListener(this);

btnActWheel = (Button) findViewById(R.id.button_wheel);

btnActWheel.setOnClickListener(this);

btnActButtons = (Button) findViewById(R.id.button_buttons);

btnActButtons.setOnClickListener(this);

btnActMCU = (Button) findViewById(R.id.button_mcu);

btnActMCU.setOnClickListener(this);

btnActTouch = (Button) findViewById(R.id.button_touch);

btnActTouch.setOnClickListener(this);

btnActAbout = (Button) findViewById(R.id.button_about);

btnActAbout.setOnClickListener(this);

}

public void onClick(View v) {

switch (v.getId()) {

case R.id.button_accel:

Intent intent_accel = new Intent(this, ActivityAccelerometer.class);

startActivity(intent_accel);

break;

case R.id.button_wheel:

Intent intent_wheel = new Intent(this, ActivityWheel.class);

startActivity(intent_wheel);

break;

case R.id.button_buttons:

Intent intent_buttons = new Intent(this, ActivityButtons.class);

startActivity(intent_buttons);

break;

case R.id.button_mcu:

Intent intent_mcu = new Intent(this, ActivityMCU.class);

startActivity(intent_mcu);

break;

case R.id.button_touch:

Intent intent_touch = new Intent(this, ActivityTouch.class);

startActivity(intent_touch);

break;

case R.id.button_about:

Intent intent_about = new Intent(this, ActivityAbout.class);

startActivity(intent_about);

break;

default:

break;

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.activity_main, menu);

return true;

}

@Override

public boolean onOptionsItemSelected(MenuItem item) {

Intent intent = new Intent();

intent.setClass(MainActivity.this, SetPreferenceActivity.class);

startActivityForResult(intent, 0);

return true;

}

PrefsFragment.java

package com.dum_car;

import android.os.Bundle;

import android.preference.PreferenceFragment;

public class PrefsFragment extends PreferenceFragment {

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

addPreferencesFromResource(R.xml.pref);

}

SetPreferenceActivity.java

package com.dum_car;

import android.app.Activity;

import android.os.Bundle;

public class SetPreferenceActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

getFragmentManager().beginTransaction().replace(android.R.id.content,

new PrefsFragment()).commit();

}

VerticalSeekBar.java

package com.dum_car;

import android.content.Context;

import android.graphics.Canvas;

import android.util.AttributeSet;

import android.view.MotionEvent;

import android.widget.SeekBar;

public class VerticalSeekBar extends SeekBar {

public VerticalSeekBar(Context context) {

super(context);

}

public VerticalSeekBar(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

}

public VerticalSeekBar(Context context, AttributeSet attrs) {

super(context, attrs);

}

protected void onSizeChanged(int w, int h, int oldw, int oldh) {

super.onSizeChanged(h, w, oldh, oldw);

}

@Override

protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

super.onMeasure(heightMeasureSpec, widthMeasureSpec);


Подобные документы

  • Основні функціональні можливості програми для забезпечення комп'ютерної системи дистанційного управління приладами. Функція пульта дистанційного керування мартфонів. Реалізація пультів дистанційного управління на основі апаратно-програмного комплексу.

    дипломная работа [1,7 M], добавлен 09.07.2015

  • Проблема розробки інтелектуального агента. Вибір і обґрунтування аналогу. Реалізація програмної системи збору та аналізу статистичних даних про контакти користувача. Створення файлів, встановлення додатків Android (APK) з файлів скриптів на мові Python.

    дипломная работа [2,7 M], добавлен 05.10.2012

  • Ескізний проект програмного забезпечення для 3D-навігації для мобільних пристроїв під управління ОС Android. Розробка прототипу інтерфейсу. Технічний проект програмного забезпечення. Створення діаграми класів, аналізу, розгортання та кооперацій.

    курсовая работа [880,5 K], добавлен 09.01.2014

  • Представление о системе Arduino. Структура платформы Android. Выбор средств разработки. Разработка структур данных и алгоритмов. Характеристика Bluetooth модуля, блок реле, резисторов, диодов. Графический интерфейс приложения. Написание кода программы.

    дипломная работа [4,0 M], добавлен 19.01.2017

  • Розробка майбутніх програмних продуктів, управління їх вихідним кодом. Концепція та моделі надання послуг хмарних обчислень. Особливості використання системи управління версіями Git. Технологія командної роботи над проектом конфігураційного управління.

    курсовая работа [1,9 M], добавлен 24.07.2014

  • Первое устройство, работающее под управлением Android. Приложения под операционную систему Android. Формат установочных пакетов. Разработка приложений на языке Java. Шаблоны основных пакетов и компонентов Android. Сборка приложений, основанная на Gradle.

    курсовая работа [492,0 K], добавлен 08.02.2016

  • Архитектура операционной системы Android. Инструменты Android-разработчика. Установка Java Development Kit, Eclipse IDE, Android SDK. Настройка Android Development Tools. Разработка программы для работы с документами и для осуществления оперативной связи.

    курсовая работа [2,0 M], добавлен 19.10.2014

  • Архитектура и история создания операционной системы Android. Язык программирования Java. Выбор средства для реализации Android приложения. Программная реализация Android приложения. Проведение тестирования разработанного программного обеспечения.

    курсовая работа [167,8 K], добавлен 18.01.2017

  • Разработка открытой мобильной платформы Android. Первое устройство, работающее под управлением Android. Магазин приложений "Google Play". Полноценные программы навигации, редакторы офисных документов и синхронизационные утилиты. Рост вирусной активности.

    презентация [58,8 K], добавлен 29.10.2014

  • Коротка характеристика об’єктів управління "Nix Solutions". Розроблення варіантів використання, специфікація функціональних та не функціональних вимог. Проектування структури бази даних, елементи. Тестування додатку та розгортання програмного продукту.

    дипломная работа [1,5 M], добавлен 01.07.2015

Работы в архивах красиво оформлены согласно требованиям ВУЗов и содержат рисунки, диаграммы, формулы и т.д.
PPT, PPTX и PDF-файлы представлены только в архивах.
Рекомендуем скачать работу.