#include<Wire.h>//#include "I2Cdev.h"#include<BLE_API.h>#include<Servo.h> Servomyservo;constintDRV8830=0x64;intpower=0;intangle=0;introt=0;#define TXRX_BUF_LEN 20BLEble;Timeouttimeout;staticuint8_trx_buf[TXRX_BUF_LEN];staticuint8_trx_buf_num;// The Nordic UART Servicestaticconstuint8_tservice1_uuid[]={0x71,0x3D,0,0,0x50,0x3E,0x4C,0x75,0xBA,0x94,0x31,0x48,0xF1,0x8D,0x94,0x1E};staticconstuint8_tservice1_tx_uuid[]={0x71,0x3D,0,3,0x50,0x3E,0x4C,0x75,0xBA,0x94,0x31,0x48,0xF1,0x8D,0x94,0x1E};staticconstuint8_tservice1_rx_uuid[]={0x71,0x3D,0,2,0x50,0x3E,0x4C,0x75,0xBA,0x94,0x31,0x48,0xF1,0x8D,0x94,0x1E};staticconstuint8_tuart_base_uuid_rev[]={0x1E,0x94,0x8D,0xF1,0x48,0x31,0x94,0xBA,0x75,0x4C,0x3E,0x50,0,0,0x3D,0x71};uint8_ttx_value[TXRX_BUF_LEN]={0,};uint8_trx_value[TXRX_BUF_LEN]={0,};intspeed1=0;intiniState=0;intangleRx_ini=35;intangleRx=angleRx_ini;GattCharacteristiccharacteristic1(service1_tx_uuid,tx_value,1,TXRX_BUF_LEN,GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE|GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE);GattCharacteristiccharacteristic2(service1_rx_uuid,rx_value,1,TXRX_BUF_LEN,GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY);GattCharacteristic*uartChars[]={&characteristic1,&characteristic2};GattServiceuartService(service1_uuid,uartChars,sizeof(uartChars)/sizeof(GattCharacteristic*));// I2C motor driver I2C//Reference//http://makers-with-myson.blog.so-net.ne.jp/2014-05-15voidwriteMotorResister(bytevset,bytedata1){intvdata=vset<<2|data1;Wire.beginTransmission(DRV8830);Wire.write(0x00);Wire.write(vdata);Wire.endTransmission(true);//delay(10);}voiddisconnectionCallBack(Gap::Handle_thandle,Gap::DisconnectionReason_treason){Serial.println("Disconnected!");Serial.println("Restarting the advertising process");iniState=0;ble.startAdvertising();}// data RxvoidwrittenHandle(constGattWriteCallbackParams*Handler){uint8_tbuf[TXRX_BUF_LEN];uint16_tbytesRead,index;//Serial.println("onDataWritten : ");if(Handler->handle==characteristic1.getValueAttribute().getHandle()){ble.readCharacteristicValue(characteristic1.getValueAttribute().getHandle(),buf,&bytesRead);if(buf[0]=='c'){iniState=1;power=buf[1];angle=buf[2];rot=buf[3];}}speed1=map(power,0,100,5,19);angleRx=map(angle,0,180,0,angleRx_ini*2);if(rot==2){Serial.print("Forward ");}if(rot==1){Serial.print("Reverse ");}Serial.print("power: ");Serial.print(power);Serial.print(" ");Serial.print("angle: ");Serial.println(angle);}//data Txvoidm_uart_rx_handle(){rx_buf_num=1;rx_buf[0]='s';ble.updateCharacteristicValue(characteristic2.getValueAttribute().getHandle(),rx_buf,rx_buf_num);memset(rx_buf,0x00,1);delay(500);Serial.println("Tx: s");}voidsetup(){Wire.begin(D3,D2,400000L);Serial.begin(250000);writeMotorResister(0x00,0x00);//writeMotorResister(0x80, 0x00);BLEset();myservo.attach(D4);myservo.write(angleRx);}voidloop(){//delay(300);if(iniState==0){m_uart_rx_handle();}if(power>=0&&power<45){angleRx=angleRx_ini;}if(power==0){writeMotorResister(0x00,0x00);}else{writeMotorResister((byte)speed1,(byte)rot);}myservo.write(angleRx);delay(15);}//BLE voidBLEset(){ble.init();ble.onDisconnection(disconnectionCallBack);ble.onDataWritten(writtenHandle);// setup adv_data and srp_datable.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED);ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME,(constuint8_t*)"motor",sizeof("motor")-1);ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS,(constuint8_t*)uart_base_uuid_rev,sizeof(uart_base_uuid_rev));// set adv_typeble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);// add serviceble.addService(uartService);// set device nameble.setDeviceName((constuint8_t*)"Simple Chat");// set tx power,valid values are -40, -20, -16, -12, -8, -4, 0, 4ble.setTxPower(4);// set adv_interval, 100ms in multiples of 0.625ms.ble.setAdvertisingInterval(160);// set adv_timeout, in secondsble.setAdvertisingTimeout(0);// start advertisingble.startAdvertising();Serial.println("Advertising Start!");}
Ctl.java
Java
packagecom.redbear.moterDrive_BLEnano02;importjava.util.HashMap;importjava.util.Map;importjava.util.UUID;importandroid.app.Activity;importandroid.bluetooth.BluetoothGattCharacteristic;importandroid.bluetooth.BluetoothGattService;importandroid.content.BroadcastReceiver;importandroid.content.ComponentName;importandroid.content.Context;importandroid.content.Intent;importandroid.content.IntentFilter;importandroid.content.ServiceConnection;importandroid.os.Bundle;importandroid.os.IBinder;importandroid.util.Log;importandroid.view.MenuItem;importandroid.widget.TextView;importcom.developwear.joystickview.JoystickView;publicclassCtlextendsActivity{privatefinalstaticStringTAG=Ctl.class.getSimpleName();publicstaticfinalStringEXTRAS_DEVICE="EXTRAS_DEVICE";privateTextViewtv=null;privateJoystickViewjsv;privateStringmDeviceName;privateStringmDeviceAddress;privateRBLServicemBluetoothLeService;privateMap<UUID,BluetoothGattCharacteristic>map=newHashMap<UUID,BluetoothGattCharacteristic>();privateintbleState=0;privatefinalServiceConnectionmServiceConnection=newServiceConnection(){@OverridepublicvoidonServiceConnected(ComponentNamecomponentName,IBinderservice){mBluetoothLeService=((RBLService.LocalBinder)service).getService();if(!mBluetoothLeService.initialize()){Log.e(TAG,"Unable to initialize Bluetooth");finish();}// Automatically connects to the device upon successful start-up// initialization.mBluetoothLeService.connect(mDeviceAddress);}@OverridepublicvoidonServiceDisconnected(ComponentNamecomponentName){mBluetoothLeService=null;}};privatefinalBroadcastReceivermGattUpdateReceiver=newBroadcastReceiver(){@OverridepublicvoidonReceive(Contextcontext,Intentintent){finalStringaction=intent.getAction();if(RBLService.ACTION_GATT_DISCONNECTED.equals(action)){tv.setText("Ready..");bleState=0;}elseif(RBLService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)){getGattService(mBluetoothLeService.getSupportedGattService());}elseif(RBLService.ACTION_DATA_AVAILABLE.equals(action)){//Data Rxbyte[]RxData=intent.getByteArrayExtra(RBLService.EXTRA_DATA);if(RxData[0]=='s'){tv.setText("Start!!");bleState=1;}}}};@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.second);tv=(TextView)findViewById(R.id.textView);//Joy Stick//https://github.com/clkasd/JoystickViewjsv=(JoystickView)findViewById(R.id.joystickview);jsv.setJoystickChangeListener(newJoystickView.JoystickChangeListener(){@OverridepublicvoidonJoystickChanged(intpower,intdegree){Log.v("power",String.valueOf(String.valueOf(power)));Log.v("degree",String.valueOf(String.valueOf(degree)));sendJoyStick(power,degree);}});Intentintent=getIntent();mDeviceAddress=intent.getStringExtra(Device.EXTRA_DEVICE_ADDRESS);mDeviceName=intent.getStringExtra(Device.EXTRA_DEVICE_NAME);getActionBar().setTitle(mDeviceName);getActionBar().setDisplayHomeAsUpEnabled(true);IntentgattServiceIntent=newIntent(this,RBLService.class);bindService(gattServiceIntent,mServiceConnection,BIND_AUTO_CREATE);}@OverrideprotectedvoidonResume(){super.onResume();registerReceiver(mGattUpdateReceiver,makeGattUpdateIntentFilter());}@OverridepublicbooleanonOptionsItemSelected(MenuItemitem){if(item.getItemId()==android.R.id.home){mBluetoothLeService.disconnect();mBluetoothLeService.close();System.exit(0);}returnsuper.onOptionsItemSelected(item);}@OverrideprotectedvoidonStop(){super.onStop();unregisterReceiver(mGattUpdateReceiver);}@OverrideprotectedvoidonDestroy(){super.onDestroy();mBluetoothLeService.disconnect();mBluetoothLeService.close();System.exit(0);}privatevoidgetGattService(BluetoothGattServicegattService){if(gattService==null)return;BluetoothGattCharacteristiccharacteristic=gattService.getCharacteristic(RBLService.UUID_BLE_SHIELD_TX);map.put(characteristic.getUuid(),characteristic);BluetoothGattCharacteristiccharacteristicRx=gattService.getCharacteristic(RBLService.UUID_BLE_SHIELD_RX);mBluetoothLeService.setCharacteristicNotification(characteristicRx,true);mBluetoothLeService.readCharacteristic(characteristicRx);}privatestaticIntentFiltermakeGattUpdateIntentFilter(){finalIntentFilterintentFilter=newIntentFilter();intentFilter.addAction(RBLService.ACTION_GATT_CONNECTED);intentFilter.addAction(RBLService.ACTION_GATT_DISCONNECTED);intentFilter.addAction(RBLService.ACTION_GATT_SERVICES_DISCOVERED);intentFilter.addAction(RBLService.ACTION_DATA_AVAILABLE);returnintentFilter;}//Data TxpublicvoidsendJoyStick(intpow,intdeg){BluetoothGattCharacteristiccharacteristic=map.get(RBLService.UUID_BLE_SHIELD_TX);byte[]bytes=newbyte[4];bytes[0]='c';bytes[1]=(byte)pow;bytes[2]=(byte)(Math.abs(deg));//if(deg<0){bytes[3]=1;//}else{bytes[3]=2;//}characteristic.setValue(bytes);if(bleState==1){mBluetoothLeService.writeCharacteristic(characteristic);}}}
Comments
Please log in or sign up to comment.