如何在iOS应用上使用Swift将命令发送到arduino?

时间:2018-09-24 19:22:54

标签: swift xcode arduino bluetooth-lowenergy

我正在开发一个应用程序,该应用程序搜索ble设备,然后将其连接到我正在使用的arduino,并且我希望能够向arduino发送命令来转动电动机。我能够成功连接到设备并写入特征,但是当消息发送时,它不会激活arduino的代码。任何帮助都将是惊人的,谢谢。 swift的代码是

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

        print("*******************************************************")

        if ((error) != nil) {
            print("Error discovering services: \(error!.localizedDescription)")
            return
        }

        guard let characteristics = service.characteristics else {
            return
        }

        print("Found \(characteristics.count) characteristics!")

        for characteristic in characteristics {
            //looks for the right characteristic

            if characteristic.uuid.isEqual(Uuidtx){
                txCharacteristic = characteristic
                print("Tx Characteristic: \(characteristic.uuid)")
                let string = "unlock"
                let data = string.data(using: String.Encoding.utf8)
                print(data!)
                peripheral.writeValue(data!, for: characteristic,type: CBCharacteristicWriteType.withResponse)

            }
        }
    }**

    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        guard error == nil else {
            print("Error discovering services: error")
            return
        }
        print("Message sent")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
       centralManager = CBCentralManager(delegate: self, queue: nil)
        // Do any additional setup after loading the view.
    }




}    

我的arduino代码是

#include <Servo.h>


Servo LockMotor;        //initialize a servo object for the connected servo  
String command = "";


void setup() 
{ 
 Serial.begin(9600);
LockMotor.attach(A1); // attach the signal pin of servo to pinA1 of arduino
} 

void loop()
{
  if(Serial.available() > 0) 
  {
    command = Serial.readString();
    if(command == "unlock")
    {
    LockMotor.writeMicroseconds(1000);
    command = "";
    Serial.println("unlocked");
    } 

    if(command == "lock") 
    {
    LockMotor.writeMicroseconds(2000);
    command = "";
    Serial.println("locked");
    }
  } 
}

0 个答案:

没有答案