带Arduino的BLE-HM10 SWIFT4

时间:2017-11-11 19:53:41

标签: swift bluetooth bluetooth-lowenergy

我正在构建一个将数据发送到蓝牙HM-10的iPhone应用程序。

当我尝试开关按钮时,LED不工作。但是当我在LightBlue应用程序中测试它时,它运行正常,我不知道我哪里出错了。 我非常感谢你的帮助。

-edited -

“什么不能正常工作?”在引脚13中灯不亮,这是由Arduino Uno内置的。在Swift应用程序中,打开按钮,将“R”发送到蓝牙,触发导致打开,同样当我关闭按钮时它会发送“r”,led关闭。

“什么在起作用?”我可以连接蓝牙,我发现它的写特性uuid,writevalue函数不会给我任何错误。

“我不知道的是什么?”是否真的发送了什么。

- 更新 -

从写“withResponse”更改为“withoutResponse”解决了问题。 这是我正在使用的Arduino代码:

int message = 0;     //  This will hold one byte of the serial message
int redLEDPin = 13;   //  What pin is the red LED connected to?
int redLED = 0;          //  The value/brightness of the LED, can be 0-255

void setup() {  
  Serial.println("Setup Started");
  Serial.begin(9600);  //set serial to 9600 baud rate
}

void loop(){
    if (Serial.available() > 0) { //  Check if there is a new message
      message = Serial.read(); //  Put the serial input into the message
Serial.println(message);
   if (message == 'R'){  //  If a capitol R is received...
     redLED = 255;       //  Set redLED to 255 (on)
   }
   if (message == 'r'){  //  If a lowercase r is received...
     redLED = 0;         //  Set redLED to 0 (off)
   }

 }   
analogWrite(redLEDPin, redLED);  //  Write an analog value between 0-255
}

这是快速的代码:

import UIKit
import CoreBluetooth

class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {


    //references to central manager
    let hmBleService = "FFE0"
    let writeCHAR = "FFE1"

    var centralManager: CBCentralManager!
    var connectedPeripheral: CBPeripheral!
    var writeCharacteristic: CBCharacteristic!


    //OUTLETS

    @IBOutlet weak var shadowView: UIView!

    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

    @IBOutlet weak var uiSwitch: UISwitch!

    @IBAction func uiSwitchValueChanged(_ sender: UISwitch) {

        if(sender.isOn){

            print("Switch is ON")
            let dataA = "R".data(using: .utf8)
            connectedPeripheral.writeValue(dataA!, for: writeCharacteristic, type: CBCharacteristicWriteType.withResponse)
            //writeBLEData(string: "R")
        }
        else{
            print("Switch is OFF")
            let dataB = "r".data(using: .utf8)
            connectedPeripheral.writeValue(dataB!, for: writeCharacteristic, type: CBCharacteristicWriteType.withResponse)
         //   writeBLEData(string: "r")
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        centralManager = CBCentralManager(delegate: self, queue:nil)

    }
//Functions added


    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //Attempt to make BLE Connection
        Timer.scheduledTimer(timeInterval: 1.0, target: self,selector: #selector(scanForBLEdevice), userInfo: nil, repeats: false)

        activityIndicator.startAnimating()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        //CLose BLE Connection if it exists
    }



    @objc func scanForBLEdevice(){

        centralManager.scanForPeripherals(withServices: [CBUUID(string:hmBleService)], options: nil)

    }

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        if(peripheral.name != nil){
        print("Found Peripheral name = \(peripheral.name!)")
        }
        else{
            print("Found Peripheral with unknown name")
        }

        //Save reference to the peripheral
        connectedPeripheral = peripheral

        centralManager.stopScan()

        centralManager.connect(connectedPeripheral, options: nil)

    }

    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("Connected to the device !")

        hideActivityIndicator()

        connectedPeripheral.delegate = self

        connectedPeripheral.discoverServices(nil)
    }

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        print("Service = \(String(describing: peripheral.services!.count))")
        for service in peripheral.services!{
            print("Servicee = \(service)")

            let aService = service as CBService
            if service.uuid == CBUUID(string: hmBleService){
                // Discover characteristics for our service
                peripheral.discoverCharacteristics(nil, for: aService)

            }

        }

    } 
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {

        for characteristic in service.characteristics!{
            let aCharacteristic = characteristic as CBCharacteristic

            if aCharacteristic.uuid == CBUUID(string: writeCHAR){
                print("We found our write Characteristic")
                writeCharacteristic = aCharacteristic
            }
        }
    }



    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //Central Manager Delegates




}

我在日志消息中得到的内容:

  

centralManagerDidUpdateState:已启动

     

电源开启

     

2017-11-11 22:23:14.390142 + 0300 BlueGreen [708:188886] refreshPreferences:

     

HangTracerEnabled:0 2017-11-11 22:23:14.390174 + 0300

     

BlueGreen [708:188886] refreshPreferences:HangTracerDuration:500

     

2017-11-11 22:23:14.390187 + 0300 BlueGreen [708:188886]

     

refreshPreferences:ActivationLoggingEnabled:0

     

ActivationLoggingTaskedOffByDA:0找到外围设备名称= HMSoft

     

连接到设备!服务= 1服务=

     

我们找到了写特征

     

开关打开

     

开关关闭

     

开关打开

     

开关关闭

     

开关打开

0 个答案:

没有答案