---
title: "基于android和arduino 的小车控制"
author: "不念书的小子"
date: "2013-03-17T21:03:08Z"
tags: []
categories: ["编程语言"]
slug: "android-arduino"
draft: false
lastmod: "2013-03-17T21:03:08Z"
id: 1830857
url: "https://tompig.iteye.com/blog/1830857"
---

基于android和arduino 的小车控制，小车部分采用的是 arduino 开源硬件实现，arduino 学起来比较简单，看看文档在看几个例子基本就会了。官网是[http://arduino.cc/](http://arduino.cc/)

我是在某宝上购买的一组套件，最终发现很多都没有用上，有点眼高手低。android 和 arduino 通信 是通过蓝牙。小车控制比较简单，前、后、左、右、向左转圈、向右转圈。

以下是源码；

1：arduino 源码：

 

 

```
#include <BaseCar.h>


// log
const boolean VERBOSE = true;
const int SERIAL_SPEED = 9600;

// for Car
//1-ok
const int MOTO1_PIN = 2;
const int I11_PIN = 3;
const int I12_PIN = 4;
//2
const int MOTO2_PIN = 5;
const int I21_PIN = 6;
const int I22_PIN = 7;
//3-ok
const int MOTO3_PIN = 8;
const int I31_PIN = 9;
const int I32_PIN =10;
//4
const int MOTO4_PIN = 11;
const int I41_PIN = 12;
const int I42_PIN = 13;

 
// speed
const int SPEED_VAL =500;

// delay
const int DELAY_TIME = 300;

//bouttooth
 char RECEIVE_VALUE='q_z_1';
// car control
BaseCar car(MOTO1_PIN, MOTO2_PIN, MOTO3_PIN, MOTO4_PIN,I11_PIN, I12_PIN, I21_PIN, I22_PIN,I31_PIN, I32_PIN, I41_PIN, I42_PIN);

const int adj = 19;
 
void setup() {
  if (VERBOSE) {
    Serial.begin(SERIAL_SPEED);
  }
}

void loop() {
  // RECEIVE_VALUE=Serial.read();
  //Serial.println(RECEIVE_VALUE);
   if(RECEIVE_VALUE=='q_z_1'){   
      // 左前一度
      car.forward(SPEED_VAL, adj);
   }else if(RECEIVE_VALUE=='q_z_2'){
   // 左前二度
      car.turnLeft(SPEED_VAL, adj);
   }else if(RECEIVE_VALUE=='q_z_3'){
   // 左前三度-向左旋转
      car.rotateLeft(SPEED_VAL, adj);
   }else if(RECEIVE_VALUE=='q_y_1'){
   // 右前一度
      car.forward(SPEED_VAL, adj);
   }else if(RECEIVE_VALUE=='q_y_2'){
   // 右前二度
      car.turnRight(SPEED_VAL, adj);
   }else if(RECEIVE_VALUE=='q_y_3'){
   // 右前三度-向右旋转
      car.rotateRight(SPEED_VAL, adj);
   }else{
   // 刹车
     car.standBy();
   }
}






```

 

```
1.1 将 以下两个类放在libiriary 下 文件夹名命名为 car


```

```
#include "Arduino.h"
#include "BaseCar.h"

BaseCar::BaseCar(int left_back_speed, int left_forward_speed,int right_forward_speed, int right_back_speed, int left_back_1, int left_back_2, int left_forward_1, int left_forward_2,int right_forward_1, int right_forward_2,int right_back_1, int right_back_2){

    _left_back_speed = left_back_speed;
    _left_forward_speed = left_forward_speed;
	_right_forward_speed = right_forward_speed;
	_right_back_speed = right_back_speed;

    pinMode(left_back_speed, OUTPUT);
    pinMode(left_forward_speed, OUTPUT);
	pinMode(right_forward_speed, OUTPUT);
    pinMode(right_back_speed, OUTPUT);

    _left_back_1 = left_back_1;
    _left_back_2 = left_back_2;
    _left_forward_1 = left_forward_1;
    _left_forward_2 = left_forward_2;
	_right_forward_1 = right_forward_1;
    _right_forward_2 = right_forward_2;
    _right_back_1 = right_back_1;
    _right_back_2 = right_back_2;

    pinMode(left_back_1, OUTPUT);
    pinMode(left_back_2, OUTPUT);
    pinMode(left_forward_1, OUTPUT);
    pinMode(left_forward_2, OUTPUT);
	pinMode(right_forward_1, OUTPUT);
    pinMode(right_forward_2, OUTPUT);
    pinMode(right_back_1, OUTPUT);
    pinMode(right_back_2, OUTPUT);
}
//停止
void BaseCar::standBy() {
    _status.left_back_speed_h = 0;
    _status.left_forward_speed_h = 0;
	_status.right_forward_speed_h = 0;
    _status.right_back_speed_h = 0;
    _status.left_back_1_h = HIGH;
    _status.left_back_2_h = HIGH;
    _status.left_forward_1_h = HIGH;
    _status.left_forward_2_h = HIGH;
	//
	_status.right_forward_1_h = HIGH;
    _status.right_forward_2_h = HIGH;
    _status.right_back_1_h = HIGH;
    _status.right_back_2_h = HIGH;
    _go();
}
//向前
void BaseCar::forward(int moto_speed, int adj) {
    _status.left_back_speed_h = moto_speed + adj;
    _status.left_forward_speed_h = moto_speed + adj;
	_status.right_forward_speed_h = moto_speed + adj;
    _status.right_back_speed_h = moto_speed + adj;

    _status.left_back_1_h = LOW;
    _status.left_back_2_h = HIGH;

    _status.left_forward_1_h = LOW;
    _status.left_forward_2_h = HIGH;
	 
    _status.right_forward_1_h = LOW;
    _status.right_forward_2_h = HIGH;

    _status.right_back_1_h = LOW;
    _status.right_back_2_h = HIGH;
    _status.adj = adj;
    _go();
}
//向后
void BaseCar::backward(int moto_speed, int adj) {
    _status.left_back_speed_h = moto_speed + adj;
    _status.left_forward_speed_h = moto_speed + adj;
	_status.right_forward_speed_h = moto_speed + adj;
    _status.right_back_speed_h = moto_speed + adj;

    _status.left_back_1_h = HIGH;
    _status.left_back_2_h = LOW;

    _status.left_forward_1_h = HIGH;
    _status.left_forward_2_h = LOW;
	 
	_status.right_forward_1_h = HIGH;
    _status.right_forward_2_h = LOW;

    _status.right_back_1_h = HIGH;
    _status.right_back_2_h = LOW;

    _status.adj = adj;
    _go();
}
//左转
void BaseCar::turnLeft(int moto_speed, int adj) {
    _status.left_back_speed_h = moto_speed - adj;
    _status.left_forward_speed_h = moto_speed - adj;

	_status.right_forward_speed_h = moto_speed + adj;
    _status.right_back_speed_h = moto_speed + adj;

    _status.left_back_1_h = LOW;
    _status.left_back_2_h = HIGH;

    _status.left_forward_1_h = LOW;
    _status.left_forward_2_h = HIGH;

	_status.right_forward_1_h = LOW;
    _status.right_forward_2_h = HIGH;

    _status.right_back_1_h = LOW;
    _status.right_back_2_h = HIGH;
    _status.adj = adj;
    _go();
}
//右转
void BaseCar::turnRight(int moto_speed, int adj) {
    _status.left_back_speed_h = moto_speed + adj;
    _status.left_forward_speed_h = moto_speed + adj;

	_status.right_forward_speed_h = moto_speed - adj;
    _status.right_back_speed_h = moto_speed - adj;

    _status.left_back_1_h = LOW;
    _status.left_back_2_h = HIGH;

    _status.left_forward_1_h = LOW;
    _status.left_forward_2_h = HIGH;

	_status.right_forward_1_h = LOW;
    _status.right_forward_2_h = HIGH;

    _status.right_back_1_h = LOW;
    _status.right_back_2_h = HIGH;
    _status.adj = adj;
    _go();
}
//向左旋转(右边向前转，左边向后转)
void BaseCar::rotateLeft(int moto_speed, int adj) {
    _status.left_back_speed_h = moto_speed + adj;
    _status.left_forward_speed_h = moto_speed + adj;

	_status.right_forward_speed_h = moto_speed + adj;
    _status.right_back_speed_h = moto_speed + adj;

    _status.left_back_1_h = HIGH;
    _status.left_back_2_h = LOW;

    _status.left_forward_1_h = HIGH;
    _status.left_forward_2_h = LOW;

	_status.right_forward_1_h = LOW;
    _status.right_forward_2_h = HIGH;

    _status.right_back_1_h = LOW;
    _status.right_back_2_h = HIGH;
    _status.adj = adj;
    _go();
}
//向右旋转
void BaseCar::rotateRight(int moto_speed, int adj) {
    _status.left_back_speed_h = moto_speed + adj;
    _status.left_forward_speed_h = moto_speed + adj;

	_status.right_forward_speed_h = moto_speed + adj;
    _status.right_back_speed_h = moto_speed + adj;

    _status.left_back_1_h = LOW;
    _status.left_back_2_h = HIGH;

    _status.left_forward_1_h = LOW;
    _status.left_forward_2_h = HIGH;

	_status.right_forward_1_h = HIGH;
    _status.right_forward_2_h = LOW;

    _status.right_back_1_h = HIGH;
    _status.right_back_2_h = LOW;
    _status.adj = adj;
    _go();
}

void BaseCar::_go() {

    digitalWrite(_left_back_1, _status.left_back_1_h);
    digitalWrite(_left_back_2, _status.left_back_2_h);
    digitalWrite(_left_forward_1, _status.left_forward_1_h);
    digitalWrite(_left_forward_2, _status.left_forward_2_h);

    digitalWrite(_right_forward_1, _status.right_forward_1_h);
    digitalWrite(_right_forward_2, _status.right_forward_2_h);
    digitalWrite(_right_back_1, _status.right_back_1_h);
    digitalWrite(_right_back_2, _status.right_back_2_h);

    analogWrite(_left_back_speed, _status.left_back_speed_h);
    analogWrite(_left_forward_speed, _status.left_forward_speed_h);
	analogWrite(_right_forward_speed, _status.right_forward_speed_h);
    analogWrite(_right_back_speed, _status.right_back_speed_h);
}

CarStatus BaseCar::getStatus() {
    return _status;
}

```

```
 
```

```
#ifndef BaseCar_h
#define BaseCar_h
#include "Arduino.h"

struct CarStatus {
	 
    int left_back_1_h;
    int left_back_2_h;
    int left_forward_1_h;
    int left_forward_2_h;
	 
	int right_forward_1_h;
    int right_forward_2_h;
	int right_back_1_h;
    int right_back_2_h;
    int left_back_speed_h;
    int left_forward_speed_h;
    int right_forward_speed_h;
    int right_back_speed_h;
    int adj;
};

class BaseCar {
    public:
        BaseCar(int left_back_speed, int left_forward_speed,int right_forward_speed, int right_back_speed, int left_back_1, int left_back_2, int left_forward_1, int left_forward_2,int right_forward_1, int right_forward_2,int right_back_1, int right_back_2);
        void standBy();
        void forward(int moto_speed, int adj);
        void backward(int moto_speed, int adj);
        void turnLeft(int moto_speed, int adj);
        void turnRight(int moto_speed, int adj);
        void rotateLeft(int moto_speed, int adj);
        void rotateRight(int moto_speed, int adj);
        CarStatus getStatus();
    private:
        int _left_back_speed;
        int _left_forward_speed;
        int _right_forward_speed;
        int _right_back_speed;

        int _left_back_1;
        int _left_back_2;
        int _left_forward_1;
        int _left_forward_2;
		int _right_forward_1;
        int _right_forward_2;
        int _right_back_1;
        int _right_back_2;
        CarStatus _status;
        void _go();
};
#endif
```

```
  
 
```

 

2：android 源码如下：

```
package com.robot;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class AAActivity extends Activity {
	private TextView state;
	private ImageView forward;
	private ImageView back;
	private ImageView left_2;
	private ImageView right_2;
	boolean isStart = false;
	private static final UUID MY_UUID = UUID
			.fromString("00001101-0000-1000-8000-00805F9B34FB");
	private static String address = "00:12:02:06:01:32";
	private static final String TAG = "THINBTCLIENT";
	private static final boolean D = true;
	private BluetoothAdapter mBluetoothAdapter = null;
	private BluetoothSocket btSocket = null;
	private OutputStream outStream = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.index);
		initUI();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	public void setValue(String message, final String text) {
		if (isStart) {
			state.setText(text);
			byte[] msgBuffer;
			try {
				outStream = btSocket.getOutputStream();
			} catch (IOException e) {
				Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
			}
			msgBuffer = message.getBytes();
			try {
				outStream.write(msgBuffer);
			} catch (IOException e) {
				Log.e(TAG, "ON RESUME: Exception during write.", e);
			}
		} else {
			Toast.makeText(this, "请先选择开启！", Toast.LENGTH_SHORT).show();
		}
	}

	private void initUI() {
		state = (TextView) findViewById(R.id.state);
		CheckBox blueT = (CheckBox) findViewById(R.id.blueT);
		blueT.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				isStart = isChecked;
			}
		});
		forward = (ImageView) findViewById(R.id.forward);
		forward.setImageResource(R.drawable.forward);
		forward.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					forward.setImageResource(R.drawable.forward_r);
					setValue("1", "直走");
				}
				if (event.getAction() == MotionEvent.ACTION_UP) {
					forward.setImageResource(R.drawable.forward);
					setValue("7", "刹车");
				}
				return true;
			}
		});

		back = (ImageView) findViewById(R.id.back);
		back.setImageResource(R.drawable.back);
		back.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					back.setImageResource(R.drawable.back_r);
					setValue("6", "后退");
				}
				if (event.getAction() == MotionEvent.ACTION_UP) {
					back.setImageResource(R.drawable.back);
					setValue("7", "刹车");
				}
				return true;
			}
		});

		left_2 = (ImageView) findViewById(R.id.left_2);
		left_2.setImageResource(R.drawable.left_2);
		left_2.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					left_2.setImageResource(R.drawable.left_2_r);
					setValue("3", "左前二度");
				}
				if (event.getAction() == MotionEvent.ACTION_UP) {
					left_2.setImageResource(R.drawable.left_2);
					setValue("7", "刹车");
				}
				return true;
			}
		});

		right_2 = (ImageView) findViewById(R.id.right_2);
		right_2.setImageResource(R.drawable.right_2);
		right_2.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					right_2.setImageResource(R.drawable.right_2_r);
					setValue("5", "右前二度");
				}
				if (event.getAction() == MotionEvent.ACTION_UP) {
					right_2.setImageResource(R.drawable.right_2);
					setValue("7", "刹车");
				}
				return true;
			}
		});

		if (D)
			Log.e(TAG, "+++ ON CREATE +++");
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null) {
			Toast.makeText(this, "蓝牙设备不可用，请打开蓝牙！", Toast.LENGTH_LONG).show();
			finish();
			return;
		}
		if (!mBluetoothAdapter.isEnabled()) {
			Toast.makeText(this, "请打开蓝牙并重新运行程序！", Toast.LENGTH_LONG).show();
			finish();
			return;
		}
		if (D)
			Log.e(TAG, "+++ DONE IN ON CREATE, GOT LOCAL BT ADAPTER +++");
	}

	public void onPause() {
		if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		}
		super.onPause();
		if (D)
			Log.e(TAG, "- ON PAUSE -");
		if (outStream != null) {
			try {
				outStream.flush();
			} catch (IOException e) {
				Log.e(TAG, "ON PAUSE: Couldn't flush output stream.", e);
			}
		}
		try {
			btSocket.close();
		} catch (IOException e2) {
			DisplayToast("套接字关闭失败！");
		}
	}

	public void onStop() {
		super.onStop();
		if (D)
			Log.e(TAG, "-- ON STOP --");
	}

	public void onDestroy() {
		super.onDestroy();
		if (D)
			Log.e(TAG, "--- ON DESTROY ---");
	}

	public void DisplayToast(String str) {
		Toast toast = Toast.makeText(this, str, Toast.LENGTH_LONG);
		toast.setGravity(Gravity.TOP, 0, 220);
		toast.show();
	}

	public void onResume() {
		super.onResume();
		if (D) {
			Log.e(TAG, "+ ON RESUME +");
			Log.e(TAG, "+ ABOUT TO ATTEMPT CLIENT CONNECT +");

		}
		DisplayToast("正在尝试连接智能小车，请稍后····");
		BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
		try {
			btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
		} catch (IOException e) {
			e.printStackTrace();
			DisplayToast("套接字创建失败！");
		}
		DisplayToast("成功连接智能小车！可以开始操控了~~~");
		mBluetoothAdapter.cancelDiscovery();
		try {
			btSocket.connect();
			DisplayToast("连接成功建立，数据连接打开！");
		} catch (IOException e) {
			try {
				btSocket.close();
			} catch (IOException e2) {
				DisplayToast("连接没有建立，无法关闭套接字！");
			}
		}
		if (D)
			Log.e(TAG, "+ ABOUT TO SAY SOMETHING TO SERVER +");

	}
}
```