ESP32连接蓝牙小票打印机


做项目要用打印机,使用了ESP32,试验用蓝牙连接看能不能完成打印的工作。在网上找资料可能是因为太容易了,对于我这样的小白太难了,一点头绪都没有。

  1. 没有说单片机与打印机实现的例子,选择打印机就是一个难题。
  2. 选择蓝牙打印机,使用单片机和蓝牙实现的介绍文章很少,反正我没有找到。
  3. 打印机是用串口协议还是其他的通讯方式,看到用串口方式的,但买了个打印机不是很好用。上电打印测试页都有时成功有时失败。可能是我没买到好用的。
  4. 蓝牙打印机不熟悉,第一次使用,问一些销售,基本没有技术支持。

只好硬着头皮开始了。

1. 打印机

打印机从网上购买,选择了一家的产品,产品介绍中很少涉及单片机的使用。都是在手机上使用和在windows下使用。其实蓝牙打印机也是用ESC+ascii代码的方式设置打印,直接接收字符串的形式打印。我选择的是58mm的热敏打印机,打印小票。
在这里插入图片描述

2. 单片机

单片机选择了ESP32,因为集成了蓝牙,实现方便。

3. 软件

软件选择了Arduino,比较丰富的库能够快速实现。我就是用ESP32中的例子程序稍作改变来试验打印机的。在软件实现中,使用BLE Utility帮助很大。

3.1 BLE通讯

BLE通讯是低功耗蓝牙通讯,新的蓝牙支持,比如手环等,鼠标等蓝牙好像就不支持了。我选择的打印机支持BLE通讯,很幸运。蓝牙通讯分两种角色:

  • Central,中心设备,其实是BLE中的客户端。
  • Peripheral, 外设,BLE中的服务器。

Central作为主设备一般是需要数据的一方,比如主机需要外部的温度信号等。Peripheral是提供数据的外部设备,比如LED指示灯等。场景一般是外部设备开始广告自己,报告的内容包括:

  • Generic Access
    • Device Name
    • Appearance
    • Peripheral Preferred Connection
  • Generic Attribute
    • Service Changed
  • Device Information
    • Model Number String
    • Software Reversion String
    • etc
  • Unknown Service
    -UUID: 000018f0-0000-1000-8000-00805f9b34fb
    • Unknown Characteristic
      • UUID: 00002af1-0000-1000-8000-00805f9b34fb

还有一些是读取的UUID。打印机不用。或者现在不用。每个UUID还会有数字比较大的,在BLE Utility中可以使用,但在程序中没有用。

3.2 软件编制

用ESP32的例子程序,例子程序中有BLE_Client项目。打开项目,将ServiceUUID改成打印机的UUID,将CharacteristicUUID改成write操作的UUID。定时发送的命令改成当有串口输入信息了再打印,就可以完成打印试验工作了。下面是例子程序。

3.3 例子程序

#include "BLEDevice.h"
//static BLEUUID serviceUUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b");
static BLEUUID serviceUUID("000018f0-0000-1000-8000-00805f9b34fb");
//static BLEUUID    charUUID("beb5483e-36e1-4688-b7f5-ea07361b26a8");
static BLEUUID    charUUID("00002af1-0000-1000-8000-00805f9b34fb");

static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static BLERemoteCharacteristic* pRemoteCharacteristic;
static BLEAdvertisedDevice* myDevice;

static void notifyCallback(
  BLERemoteCharacteristic* pBLERemoteCharacteristic,
  uint8_t* pData,
  size_t length,
  bool isNotify) 
{
    
    
    Serial.print("Notify callback for characteristic ");
    Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
    Serial.print(" of data length ");
    Serial.println(length);
    Serial.print("data: ");
    Serial.println((char*)pData);
}

class MyClientCallback : public BLEClientCallbacks
{
    
    
	void onConnect(BLEClient* pclient) 
   	 {
    
    
    	}
    void onDisconnect(BLEClient* pclient) 
    {
    
    
      connected = false;
      Serial.println("onDisconnect");
    }
  };

bool connectToServer() 
{
    
    
    Serial.print("Forming a connection to ");
    Serial.println(myDevice->getAddress().toString().c_str());
    
   BLEClient * pClient = BLEDevice::createClient();
   Serial.println(" - Created client");

   pClient->setClientCallbacks(new MyClientCallback());
// Connect to the remove BLE Server
	pClient->connect(myDevice);
// if you pass BLEAdvertisedDevice instead of address, 
    //it will be recognized type of peer device address (public or private)
    Serial.println(" - Connected to server");
// Obtain a reference to the service we are after in the remote BLE server.
    
    BLERemoteService* pRemoteService = pClient->>getService(serviceUUID);
    if (pRemoteService == nullptr) 
    {
    
    
      Serial.print("Failed to find our service UUID: ");
      Serial.println(serviceUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our service");

// 读取characteristic的值
    if(pRemoteCharacteristic->canRead()) 
    {
    
    
      std::string value = pRemoteCharacteristic->readValue();
      Serial.print("The characteristic value was: ");
      Serial.println(value.c_str());
    }
  if ( pRemoteCharacteristc->canNotify())
  	pRemoteCharacteristc->registerForNotify(notifyCallback);
  
  connected = true;
  return true;
}

/**
 * Scan for BLE servers and find the first one that advertises 
 * the service we are looking for.
 */


  class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks
  {
    
    
  	void onResult(BLEAdvertisedDevice advertisedDevice)
  	{
    
    
    		Serial.print("BLE Advertised Device found: ");
    		Serial.println(advertisedDevice.toString().c_str());  	
    // We have found a device, let us now see 
    // if it contains the service we are looking for.
       if (advertisedDevice.haveServiceUUID() && 
        advertisedDevice.isAdvertisingService(serviceUUID)) 
    {
    
    
      BLEDevice::getScan()->stop();
      myDevice = new BLEAdvertisedDevice(advertisedDevice);
      doConnect = true;
      doScan = true;
     } // Found our server
    } // onResult
}; // MyAdvertisedDeviceCallbacks

void setup() 
{
    
    
  Serial.begin(115200);
  Serial.println("Starting Arduino BLE Client application...");
  BLEDevice::init("");
  // Retrieve a Scanner and set the callback we want to use to be informed when we
  // have detected a new device.  Specify that we want active scanning and start the
  // scan to run for 5 seconds. 这里我增加了时间,成功找到了打印机
  BLEScan* pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setInterval(1349);
  pBLEScan->setWindow(449);
  pBLEScan->setActiveScan(true);
  pBLEScan->start(10, false);
 }

// This is the Arduino main loop function.
void loop() 
{
    
    
  // If the flag "doConnect" is true then we have scanned for and found the desired
  // BLE Server with which we wish to connect.  Now we connect to it.  Once we are 
  // connected we set the connected flag to be true.
   if (doConnect == true) 
  {
    
    
    if (connectToServer()) {
    
    
      Serial.println("We are now connected to the BLE Server.");
    } else {
    
    
      Serial.println("We have failed to connect to the server; there is nothin more we will do.");
    }
    doConnect = false;
  }
  // If we are connected to a peer BLE Server, update the characteristic each time we are reached
  // with the current time since boot.
  if (connected) 
  {
    
    
    String newValue = "Time since boot: " + String(millis()/1000);
    Serial.println("Setting new characteristic value to \"" + newValue + "\"");
    // Set the characteristic's value to be the array of bytes that is actually a string.
 //   pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length());
 // 在这里进行了更改。当有外部的串口输入时,打印数据到打印机
    if ( Serial.available())
    {
    
    
      String xStr = Serial.readString();
      //int x = length(xStr);
      pRemoteCharacteristic->writeValue(xStr.c_str(), xStr.length());     
    }
 }else if(doScan)
  {
    
    
    BLEDevice::getScan()->start(0);  
    // this is just eample to start scan after disconnect, 
    // most likely there is better way to do it in arduino
  }
delay(1000); // delay a second between loop
}

这是整个的程序,注意2个地方:

  1. 更改了serviceUUID和CharacteristicUUID
  2. 更改了每次打印为有串口输入时才打印。

猜你喜欢

转载自blog.csdn.net/weixin_44481398/article/details/104081540