微信小程序控制STC12单片机蓝牙通信与PWM控制舵机

此项目主要用蓝牙小程序,蓝牙通信控制舵机开关灯的作用。
下面我们先看实物。机械结构是一个机械朋友(LT)设计的,十分感谢他。
在这里插入图片描述

1.1小程序

在这里插入图片描述
WXML的程序:

<button   bindtap="getDevices"  type="primary">获得周边蓝牙设备</button>

  <view wx:if="{{showFlag}}" wx:for="{{devices}}" wx:for-item="devices" wx:key="key" bindtap="create" data-index="{{index}}" >
    <view>
   {{devices.name}}: {{devices.deviceId}}  
   </view>
</view>


<view>选择蓝牙设备{{name}}: {{deviceId}} </view>


<view wx:for="{{services}}"  wx:for-item="service" bindtap="choise" wx:key="services" data-index="{{index}}">
    <view>选择服务值:{{service.uuid}}
    </view>
</view>

<view wx:for="{{characteristics}}" wx:for-item="characteristics" wx:key="characteristics" data-index="{{index}}">
特征值:{{characteristics.uuid}}</view>

<button  bindtap="startread" type="primary" >开启notisfy</button>


    <text space="&ensp">\n</text>

<button bindtap="startwrite1" type="primary">开灯</button>


    <text space="&ensp">\n</text>
    <button bindtap="startwrite2" type="primary">关灯</button>

在JS程序:

// pages/bluetooth1/bluetooth1.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    discoverFlag:false,
    devices:[],
    deviceId:'',
    serviceId:'',
    services:[],
    characteristics:[],
    characteristicId:'',
    showFlag:true,
    name:'',
    state:false,
    
    sendmsg:'hah',
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.openBluetoothAdapter({
      success (res) {
        console.log(res)
        
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  openAdapter:function(){


  },
  discoverDevices:function(){
     let that=this
   
  },
  getDevices:function(){
    let that=this
    function ab2hex(buffer) {
      var hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function(bit) {
          return ('00' + bit.toString(16)).slice(-2)
        }
      )
      return hexArr.join('');
    }
    wx.startBluetoothDevicesDiscovery({
      services: [],
      success (res) {
        console.log(res),
        that.setData({
          discoverFlag:res.isDiscovering
        })
      },
    })
      if(this.data.discoverFlag){
        // ArrayBuffer转16进度字符串示例

wx.onBluetoothDeviceFound(function(res) {
  var devices = res.devices;
  console.log('new device list has founded')
  console.dir(devices)
  console.log(ab2hex(devices[0].advertisData))
}) 
}
wx.getBluetoothDevices({
  
  success: function (res) {
    console.log(res)
    if (res.devices[0]) {
      console.log(ab2hex(res.devices[0].advertisData)),
      that.setData({
        devices:res.devices
      })
    }

  }
})


      
   },

create(e){
  let that=this
  console.log(e)
    let index=e.currentTarget.dataset.index
  wx.createBLEConnection({
    deviceId:that.data.devices[index].deviceId,
   
    success (res) {
      console.log(res)
      that.setData({deviceId:that.data.devices[index].deviceId,
        name:that.data.devices[index].name,
        showFlag:false,
      })
      wx.getBLEDeviceServices({
        // 这里的 deviceId 需要已经通过 wx.createBLEConnection 与对应设备建立连接
        deviceId:that.data.deviceId,
        success (res) {
          console.log('device services:', res.services),
          that.setData({services:res.services})
         
        },
      })
    },
  })
  },

choise(e){
  console.log(e)
  let that=this
  let index=e.currentTarget.dataset.index
  let serviceId=this.data.services[index].uuid
  this.setData({
    serviceId:serviceId
  })
  wx.getBLEDeviceCharacteristics({
    // 这里的 deviceId 需要已经通过 wx.createBLEConnection 与对应设备建立链接
    deviceId:this.data.deviceId,
    // 这里的 serviceId 需要在 wx.getBLEDeviceServices 接口中获取
    serviceId:this.data.serviceId,
    success (res) {
      console.log('device getBLEDeviceCharacteristics:', res.characteristics)
      that.setData({
        characteristics:res.characteristics,
        characteristicId:res.characteristics[0].uuid
      })
    },
  })
},
startread:function(e){
// 必须在这里的回调才能获取
console.log(e)
wx.stopBluetoothDevicesDiscovery
({
  success: function (res) 
  {
    console.log("停止搜索" + JSON.stringify(res.errMsg));

  }
})

wx.readBLECharacteristicValue({

    // 这里的 deviceId 需要已经通过 wx.createBLEConnection 与对应设备建立链接
    deviceId:this.data.deviceId,
    // 这里的 serviceId 需要在 wx.getBLEDeviceServices 接口中获取
    serviceId:this.data.serviceId,
  // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
  characteristicId:this.data.characteristics[0].uuid,
  success (res) {
    console.log('readBLECharacteristicValue:', res.errCode)
  }
})
wx.notifyBLECharacteristicValueChange({
  state: true, // 启用 notify 功能
  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  deviceId:this.data.deviceId,
  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
  serviceId:this.data.serviceId,
  // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
  characteristicId:this.data.characteristicId,
  success (res) {
    console.log('notifyBLECharacteristicValueChange success', res.errMsg)
  }
})
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
  
  new Uint8Array(buffer),
  
  function(bit) {
  return ('00' + bit.toString(16)).slice(-2)
  
  }
  
  )
  
  return hexArr.join('');
  
  }
  
  wx.onBLECharacteristicValueChange(function (res) {
  console.log('characteristic value comed:', ab2hex(res.value))

  })

},
startwrite1:function(event){
  let buffer = new ArrayBuffer(1)
let dataView = new DataView(buffer)
dataView.setUint8(0, 100)

wx.writeBLECharacteristicValue({
  // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  deviceId:this.data.deviceId,
  // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
  serviceId:this.data.serviceId,
  // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
  characteristicId:this.data.characteristicId,
  value: buffer,
  success (res) {
    console.log('writeBLECharacteristicValue success', res.errMsg),
    console.log('发送的是:',buffer)
  }
 })
  },
  startwrite2:function(event){
    let buffer = new ArrayBuffer(1)
  let dataView = new DataView(buffer)
  dataView.setUint8(0, 99)
  
  wx.writeBLECharacteristicValue({
    // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
    deviceId:this.data.deviceId,
    // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
    serviceId:this.data.serviceId,
    // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
    characteristicId:this.data.characteristicId,
    value: buffer,
    success (res) {
      console.log('writeBLECharacteristicValue success', res.errMsg),
      console.log('发送的是:',buffer)
    }
   })
    },

})

这里我找了一下别人蓝牙开发的流程图,我实在不想写流程图了
在这里插入图片描述
大致就是这样的流程,只是断开连接我没写。

2.1单片机程序

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
程序:

#include "STC12C5A60S2.H"	

#include "intrins.h"
unsigned char numdata;
unsigned int num;
unsigned int count;      //次数标识
unsigned int angle=5;         //角度标识
sbit pwm =P1^0 ;          //PWM信号输出
void delay_ms(unsigned int ms)               
{
	unsigned int a,b;
	for(a=ms;a>0;a--)
		for(b=114;b>0;b--);
}

/*定时器初始化函数*/
void Timer0_Init(void)		//100微秒@11.0592MHz
{
	TMOD |= 0x01;		//设置定时器模式
	TL0 = 0xA4;		//设置定时初值
	TH0 = 0xFF;		//设置定时初值
	TF0 = 0;		//清除TF0标志
	TR0 = 1;		//定时器0开始计时
	
}

/*串口初始化函数*/
void Uart_Init(void)		//9600bps@11.0592MHz
{
TMOD=0X20;
TH1=0XFD;
TL1=0XFD;  
TR1=1;
SM0=0;
SM1=1;
REN=1;
EA=1;
ES=1;
}

/*串口发送一字节函数*/
void Uart_SendData(unsigned char dat )
{
	SBUF = dat;
	while(TI == 0);
	TI = 0;
}

/*串口发送字符串函数*/
void Uart_SendString(char *s)
{
	while (*s)              
	{
		Uart_SendData(*s++);
	}
}
	//angle与对应角度关系
	//4   5   6   ...... 19  20
	//0   11  22  ...... 166 177
/*程序入口*/
void main(void)
{
	

	Uart_Init();
	Timer0_Init();
//	Uart_SendString("舵机正在旋转。\r\n");
//	for(angle=4;angle<10;angle++)//从0到177度,步进11度
//	{
//		delay_ms(2);
//	}
//	delay_ms(2000);
//	for(angle=10;angle>4;angle--)//从177到0度,步进11度
//	{
//		delay_ms(2);
//	}
//	Uart_SendString("舵机正在往复旋转。\r\n");
	while(1)
	{ 
		if(numdata=='d')
		{ 
			ET0 = 1;
			angle=10;	
       	delay_ms(20);
      ET0=0;			
		}
		
				if(numdata=='c')
		{ 	
			ET0=1;			
		   angle=4;		
     delay_ms(20);
     ET0=0;			
		}
	}
}

/*串口中断服务函数*/
void Uart_Isr() interrupt 4
{
	unsigned char receiveData;
		receiveData=SBUF;//出去接收到的数据
	RI = 0;//清除接收中断标志位
	SBUF=receiveData;//将接收到的数据放入到发送寄存器
	while(!TI);			 //等待发送数据完成
	TI=0;						 //清除发送完成标志位
	if(receiveData=='d')
	{SBUF=receiveData;
		numdata='d';
		
	  while(!TI);			 //等待发送数据完成
	  TI=0;						 //清除发送完成标志位
	
	}
		if(receiveData=='c')
	{SBUF=receiveData;
		numdata='c';
		
	  while(!TI);			 //等待发送数据完成
	  TI=0;						 //清除发送完成标志位
	
	}
//    if (RI)
//    {
//        RI = 0;  
//	}
}


/*定时器中断服务函数*/
void Timer0_Isr() interrupt 1
{
	TL0 = 0xA4;		//设置定时初值
	TH0 = 0xFF;		//设置定时初值
	if(count< angle)              //判断次数是否小于角度标识
      pwm=1;                  //确实小于,PWM输出高电平
    else
      pwm=0;                  //大于则输出低电平
    count=(count+1);          //0.1ms次数加1
    count=count%160;     //保持周期为20ms,普通51单片机定时100us有误差,经示波器测量约为50Hz
}


具体讲解我就不一一讲解了,里面东西太多了,可能之后我有时间可能会出一个视频讲解吧

  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜鸡联盟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值