Программирование на Blockly
Документация по RoboIntellect SDK (RI SDK)
Функциональный RI SDK API исполнительных устройств

RI_SDK_exec_RServoDrive_GetState

!!! ИНФОРМАЦИЯ

RI_SDK - библиотека Robo Intellect Software Development Kit

exec - название группы устройств исполнителей

RServoDrive - название устройства сервопривода вращения

GetState - название метода чтения состояния сервопривода

Сигнатура функции

  • Shared object
RI_SDK_exec_RServoDrive_GetState(descriptor, state, errorText):errorCode
  • Golang gRPC
RI_SDK_Exec_RServoDrive_GetState(descriptor int64) (state int64, errorText string, errorCode int64, err error)

Описание метода

Чтение состояния сервопривода.

Получает значение константы состояния сервопривода с дескриптором descriptor и записывает его в state.

Коды состояния:

0 - Сервопривод ожидает вызова действий. Сервопривод ничего не делает и готов к работе.
1 - Компонент выполняет действие. Сервопривод в данный момент осуществляет движение.

Параметры и возвращаемые значения

Параметр Тип для Shared object Тип для Golang gRPC Описание
descriptor int (тип C) int64 Дескриптор компонента сервопривода
state *int (тип C) int64 Указатель код состояния сервопривода
errorText char[1000] (тип C) string Текст ошибки (передается как параметр, если происходит ошибка метод записывает в этот параметр текст ошибки)
errorCode int (тип C) int64 Код ошибки

Примеры

Пример №1 - Получение состояния сервопривода вращения

В данном примере в переменную state записывается состояние компонента сервопривода с дескриптором, записанным в переменную d_mg996r, и последующий вывод значения переменной state.

  • Python
# Получение состояния сервопривода вращения
errCode = lib.RI_SDK_exec_RServoDrive_GetState(d_mg996r, state, errTextC)
if errCode != 0:
    print(errCode, errTextC.raw.decode())
    sys.exit(2) 

print("state: ", state.value)
    
  • C
// Получение состояния сервопривода вращения    
errCode = RI_SDK_exec_RServoDrive_GetState(d_mg996r, &state, errorText);
if (errCode != 0) {
    printf("errorText:%s\n", errorText);
    return errCode;
}

printf("state: %d\n", state);
  • C++
// Получение состояния сервопривода вращения    
errCode = RI_SDK_exec_RServoDrive_GetState(d_mg996r, &state, errorText);
if (errCode != 0) {
    printf("errorText:%s\n", errorText);
    return errCode;
}

printf("state: %d\n", state);
  • Golang
// Получение состояния сервопривода вращения
errCode = C.RI_SDK_exec_RServoDrive_GetState(d_mg996r, &state, &errorTextC[0])
if errCode != 0 {
    fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
    return
}

fmt.Println("state: ", state)
  • Golang gRPC
// Получение состояния сервопривода вращения
state, errorText, errCode, err = client.RoboSdkApi.RI_SDK_Exec_ServoDrive_GetState(d_mg996r)
if err != nil {
    fmt.Printf("gRPC Error: %v\n", err)
    return
}
if errCode != 0 {
    fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
    return
}

fmt.Println("state: ", state)
  • PHP
// Получение состояния сервопривода вращения
$errCode = $ffi->RI_SDK_exec_RServoDrive_GetState($d_mg996r->cdata, FFI::addr($state), $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

print("state: " . $state->cdata . "\n");
Полный текст примера
  • Python
from ctypes.util import find_library
import platform
import sys
import time
from ctypes import *

# Подключаем внешнюю библиотеку для работы с SDK
platform = platform.system()
if platform == "Windows":
    libName = "librisdk.dll"
if platform == "Linux":
    libName = "librisdk.so"

pathLib = find_library(libName)
lib = cdll.LoadLibrary(pathLib)


# Указываем типы аргументов для функций библиотеки RI_SDK
lib.RI_SDK_InitSDK.argtypes = [c_int, c_char_p]
lib.RI_SDK_CreateModelComponent.argtypes = [c_char_p, c_char_p, c_char_p, POINTER(c_int), c_char_p]
lib.RI_SDK_LinkPWMToController.argtypes = [c_int, c_int, c_uint8, c_char_p]
lib.RI_SDK_LinkRServodriveToController.argtypes = [c_int, c_int, c_int, c_char_p]
lib.RI_SDK_DestroySDK.argtypes = [c_bool, c_char_p]
lib.RI_SDK_exec_RServoDrive_RotateWithRelativeSpeedOverTime.argtypes = [c_int, c_int, c_int, c_int, c_bool, c_char_p]
lib.RI_SDK_exec_RServoDrive_GetState.argtypes = [c_int, POINTER(c_int), c_char_p]
lib.RI_SDK_exec_RServoDrive_Stop.argtypes = [c_int, c_char_p]

def main():
    errTextC = create_string_buffer(1000)  # Текст ошибки. C type: char*
    i2c = c_int()
    pwm = c_int()
    d_mg996r = c_int()
    state = c_int()

    # Инициализация библиотеки RI SDK с уровнем логирования 3
    errCode = lib.RI_SDK_InitSDK(3, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    # Создание компонента i2c адаптера модели ch341
    errCode = lib.RI_SDK_CreateModelComponent("connector".encode(), "i2c_adapter".encode(), "ch341".encode(), i2c, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    print("i2c: ", i2c.value)

    # Создание компонента ШИМ модели pca9685
    errCode = lib.RI_SDK_CreateModelComponent("connector".encode(), "pwm".encode(), "pca9685".encode(), pwm, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    print("pwm: ", pwm.value)

     # Создание компонента сервопривода вращения модели mg996r
    errCode = lib.RI_SDK_CreateModelComponent("executor".encode(), "servodrive_rotate".encode(), "mg996r".encode(), d_mg996r, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    print("servodrive rotate: ", d_mg996r.value)

    # Связывание i2c с ШИМ
    errCode = lib.RI_SDK_LinkPWMToController(pwm, i2c, 0x40, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    # Связывание ШИМ с сервоприводом
    errCode = lib.RI_SDK_LinkRServodriveToController(d_mg996r, pwm, 0, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    # Получение начального состояния сервопривода вращения
    errCode = lib.RI_SDK_exec_RServoDrive_GetState(d_mg996r, state, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    print("state before work: ", state.value)

    # Вращение сервопривода по часовой стрелке
    # Скорость движения - 100  градусов в секунду
    errCode = lib.RI_SDK_exec_RServoDrive_RotateWithRelativeSpeedOverTime(d_mg996r, 0, 50, 2000, True, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    time.sleep(0.1) 
    # Получение состояния сервопривода вращения во время работы
    errCode = lib.RI_SDK_exec_RServoDrive_GetState(d_mg996r, state, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    print("work state: ", state.value)

    time.sleep(1)
    
    # Остановка работы сервопривода вращения
    errCode = lib.RI_SDK_exec_RServoDrive_Stop(d_mg996r, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    time.sleep(0.1)
    # Получение состояния сервопривода вращения
    errCode = lib.RI_SDK_exec_RServoDrive_GetState(d_mg996r, state, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    print("await state: ", state.value)

    # Удаление библиотеки со всеми компонентами
    errCode = lib.RI_SDK_DestroySDK(True, errTextC)
    if errCode != 0:
        print(errCode, errTextC.raw.decode())
        sys.exit(2)

    print("Success")

main()
  • C
#include <stdbool.h>
#include <unistd.h>
#include "./librisdk.h" // Подключение библиотеки

int main(){
    char errorText[1000]; // текст ошибки. Передается как входной параметр,при возникновении ошибки в эту переменную будет записан текст ошибки
    int errCode; //код ошибки
    int i2c;
    int pwm;
    int d_mg996r;
    int state;

    // Инициализация библиотеки RI SDK с уровнем логирования 3
    errCode = RI_SDK_InitSDK(3, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    // Создание компонента i2c адаптера модели ch341
    errCode = RI_SDK_CreateModelComponent("connector", "i2c_adapter", "ch341", &i2c, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("i2c: %d\n", i2c);

    // Создание компонента ШИМ модели pca9685
    errCode = RI_SDK_CreateModelComponent("connector", "pwm", "pca9685", &pwm, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("pwm: %d\n", pwm);

    // Создание компонента сервопривода вращения модели mg996r
    errCode = RI_SDK_CreateModelComponent("executor", "servodrive_rotate", "mg996r", &d_mg996r, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("servodrive rotate: %d\n", d_mg996r);

    // Связывание i2c с ШИМ
    errCode = RI_SDK_LinkPWMToController(pwm, i2c, 0x40, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    // Связывание ШИМ с сервоприводом
    errCode = RI_SDK_LinkRServodriveToController(d_mg996r, pwm, 0, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    // Получение начального состояния сервопривода вращения
    errCode = RI_SDK_exec_RServoDrive_GetState(d_mg996r, &state, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("state before work: %d\n", state);

    // Вращение сервопривода по часовой стрелке. Скорость движения - 50% от максимальной скорости
    errCode = RI_SDK_exec_RServoDrive_RotateWithRelativeSpeedOverTime(d_mg996r, 0, 50, 2000, true, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    sleep(1);

    // Получение состояния сервопривода вращения во время работы
    errCode = RI_SDK_exec_RServoDrive_GetState(d_mg996r, &state, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("work state: %d\n", state);

    // Остановка работы сервопривода вращения
    errCode = RI_SDK_exec_RServoDrive_Stop(d_mg996r, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }
    
    sleep(1);

    // Получение состояния сервопривода вращения
    errCode = RI_SDK_exec_RServoDrive_GetState(d_mg996r, &state, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("await state: %d\n", state);

    // Удаление библиотеки со всеми компонентами
    errCode = RI_SDK_DestroySDK(true, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("Success");
    return 0;
}
  • C++
#include <stdbool.h>
#include <unistd.h>
#include "./librisdk.h" // Подключение библиотеки

int main(){
    char errorText[1000]; // текст ошибки. Передается как входной параметр,при возникновении ошибки в эту переменную будет записан текст ошибки
    int errCode; //код ошибки
    int i2c;
    int pwm;
    int d_mg996r;
    int state;

    // Инициализация библиотеки RI SDK с уровнем логирования 3
    errCode = RI_SDK_InitSDK(3, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    // Создание компонента i2c адаптера модели ch341
    char i2cGroup[] = "connector";
    char i2cDevice[] = "i2c_adapter";
    char i2cModel[] = "ch341";
    errCode = RI_SDK_CreateModelComponent(i2cGroup, i2cDevice, i2cModel, &i2c, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("i2c: %d\n", i2c);

    // Создание компонента ШИМ модели pca9685
    char pwmGroup[] = "connector";
    char pwmDevice[] = "pwm";
    char pwmModel[] = "pca9685";
    errCode = RI_SDK_CreateModelComponent(pwmGroup, pwmDevice, pwmModel, &pwm, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("pwm: %d\n", pwm);

    // Создание компонента сервопривода вращения модели mg996r
    char servoGroup[] = "executor";
    char servoDevice[] = "servodrive_rotate";
    char servoModel[] = "mg996r";
    errCode = RI_SDK_CreateModelComponent(servoGroup, servoDevice, servoModel, &d_mg996r, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("servodrive rotate: %d\n", d_mg996r);

    // Связывание i2c с ШИМ
    errCode = RI_SDK_LinkPWMToController(pwm, i2c, 0x40, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    // Связывание ШИМ с сервоприводом
    errCode = RI_SDK_LinkRServodriveToController(d_mg996r, pwm, 0, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    // Получение начального состояния сервопривода вращения
    errCode = RI_SDK_exec_RServoDrive_GetState(d_mg996r, &state, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("state before work: %d\n", state);

    // Вращение сервопривода по часовой стрелке. Скорость движения - 50% от максимальной скорости
    errCode = RI_SDK_exec_RServoDrive_RotateWithRelativeSpeedOverTime(d_mg996r, 0, 50, 2000, true, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    sleep(1);

    // Получение состояния сервопривода вращения во время работы
    errCode = RI_SDK_exec_RServoDrive_GetState(d_mg996r, &state, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("work state: %d\n", state);

    // Остановка работы сервопривода вращения
    errCode = RI_SDK_exec_RServoDrive_Stop(d_mg996r, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    sleep(1);

    // Получение состояния сервопривода вращения
    errCode = RI_SDK_exec_RServoDrive_GetState(d_mg996r, &state, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("await state: %d\n", state);

    // Удаление библиотеки со всеми компонентами
    errCode = RI_SDK_DestroySDK(true, errorText);
    if (errCode != 0) {
        printf("errorText:%s\n", errorText);
        return errCode;
    }

    printf("Success");
    return 0;
}
  • Golang
package main

/*
#cgo CFLAGS: -I.
#cgo LDFLAGS: -L. -lrisdk
#include <librisdk.h> // Подключаем внешнюю библиотеку для работы с SDK.
*/
import "C"
import (
    "fmt"
    "time"
)

var (
    errorTextC [1000]C.char // Текст ошибки. C type: char*
    errCode    C.int        // Код ошибки. C type: int
    i2c        C.int
    pwm        C.int
    d_mg996r   C.int
    state      C.int
)

func main() {

    // Инициализация библиотеки RI SDK с уровнем логирования 3
    errCode = C.RI_SDK_InitSDK(3, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    // Создание компонента i2c адаптера модели ch341
    errCode = C.RI_SDK_CreateModelComponent(C.CString("connector"), C.CString("i2c_adapter"), C.CString("ch341"), &i2c, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    fmt.Println("i2c: ", i2c)

    // Создание компонента ШИМ модели pca9685
    errCode = C.RI_SDK_CreateModelComponent(C.CString("connector"), C.CString("pwm"), C.CString("pca9685"), &pwm, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    fmt.Println("pwm: ", pwm)

    // Создание компонента сервопривода вращения модели mg996r
    errCode = C.RI_SDK_CreateModelComponent(C.CString("executor"), C.CString("servodrive_rotate"), C.CString("mg996r"), &d_mg996r, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    fmt.Println("servodrive rotate: ", d_mg996r)

    // Связывание i2c с ШИМ
    errCode = C.RI_SDK_LinkPWMToController(pwm, i2c, 0x40, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    // Связывание ШИМ с сервоприводом
    errCode = C.RI_SDK_LinkRServodriveToController(d_mg996r, pwm, 0, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    // Получение начального состояния сервопривода вращения
    errCode = C.RI_SDK_exec_RServoDrive_GetState(d_mg996r, &state, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    fmt.Println("state before work: ", state)

    // Вращение сервопривода по часовой стрелке. Скорость движения - 50% от максимальной скорости
    errCode = C.RI_SDK_exec_RServoDrive_RotateWithRelativeSpeedOverTime(d_mg996r, 0, 50, 2000, true, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    time.Sleep(time.Second)

    // Получение состояния сервопривода вращения во время работы
    errCode = C.RI_SDK_exec_RServoDrive_GetState(d_mg996r, &state, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    fmt.Println("work state: ", state)

    // Остановка работы сервопривода вращения
    errCode = C.RI_SDK_exec_RServoDrive_Stop(d_mg996r, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    time.Sleep(time.Second)

    // Получение состояния сервопривода вращения
    errCode = C.RI_SDK_exec_RServoDrive_GetState(d_mg996r, &state, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }
    
    fmt.Println("await state: ", state)
    
    // Удаление библиотеки со всеми компонентами
    errCode = C.RI_SDK_DestroySDK(true, &errorTextC[0])
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, C.GoString(&errorTextC[0]))
        return
    }

    fmt.Println("Success")
}
  • Golang gRPC
package main

import "C"
import (
    "fmt"
    "time"

    "github.com/rbs-ri/go-risdk"
)

var (
    client    *risdk.ClientRPC // Объект взяимодействия с API SDK
    errorText string           // Текст ошибки
    errCode   int64            // Код ошибки
    err       error            // Ошибка gRPC
    i2c       int64
    pwm       int64
    d_mg996r  int64
    state     int64
)

func main() {

    // Открываем соединение для работы с API SDK по RPC
    client = risdk.GetClientRPC()

    // Закрываем соединение с RPC
    defer client.Client.Kill()

    // Инициализация библиотеки RI SDK с уровнем логирования 3
    errorText, errCode, err = client.RoboSdkApi.RI_SDK_InitSDK(3)
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    // Создание компонента i2c адаптера модели ch341
    i2c, errorText, errCode, err = client.RoboSdkApi.RI_SDK_CreateModelComponent("connector", "i2c_adapter", "ch341")
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    fmt.Println("i2c: ", i2c)

    // Создание компонента ШИМ модели pca9685
    pwm, errorText, errCode, err = client.RoboSdkApi.RI_SDK_CreateModelComponent("connector", "pwm", "pca9685")
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    fmt.Println("pwm: ", pwm)

    // Создание компонента сервопривода вращения модели mg996r
    d_mg996r, errorText, errCode, err = client.RoboSdkApi.RI_SDK_CreateModelComponent("executor", "servodrive_rotate", "mg996r")
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    fmt.Println("servodrive rotate: ", d_mg996r)

    // Связывание i2c с ШИМ
    errorText, errCode, err = client.RoboSdkApi.RI_SDK_LinkPWMToController(pwm, i2c, 0x40)
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    // Связывание ШИМ с сервоприводом
    errorText, errCode, err = client.RoboSdkApi.RI_SDK_LinkRServodriveToController(d_mg996r, pwm, 0)
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    // Получение начального состояния сервопривода вращения
    state, errorText, errCode, err = client.RoboSdkApi.RI_SDK_Exec_RServoDrive_GetState(d_mg996r)
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    fmt.Println("state before work: ", state)

    // Вращение сервопривода по часовой стрелке. Скорость движения - 50% от максимальной скорости
    errorText, errCode, err = client.RoboSdkApi.RI_SDK_Exec_RServoDrive_RotateWithRelativeSpeedOverTime(d_mg996r, 0, 50, 2000, true)
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    time.Sleep(time.Second)

    // Получение состояния сервопривода вращения во время работы
    state, errorText, errCode, err = client.RoboSdkApi.RI_SDK_Exec_RServoDrive_GetState(d_mg996r)
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    fmt.Println("work state: ", state)

    // Остановка работы сервопривода вращения
    errorText, errCode, err = client.RoboSdkApi.RI_SDK_Exec_RServoDrive_Stop(d_mg996r)
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    time.Sleep(time.Second)

    // Получение состояния сервопривода вращения
    state, errorText, errCode, err = client.RoboSdkApi.RI_SDK_Exec_RServoDrive_GetState(d_mg996r)
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    fmt.Println("await state: ", state)

    // Удаление библиотеки со всеми компонентами
    errorText, errCode, err = client.RoboSdkApi.RI_SDK_DestroySDK(true)
    if err != nil {
        fmt.Printf("gRPC Error: %v\n", err)
        return
    }
    if errCode != 0 {
        fmt.Printf("errorCode:%d - errorText:%s\n", errCode, errorText)
        return
    }

    fmt.Println("Success")
}
  • PHP
<?php
// Подключаем внешнюю библиотеку для работы с SDK
$RELATIVE_PATH = '';
$headers = file_get_contents(__DIR__ . $RELATIVE_PATH . '/librisdk.h');
$headers = preg_replace(['/#ifdef __cplusplus\s*extern "C" {\s*#endif/i', '/#ifdef __cplusplus\s*}\s*#endif/i'], '', $headers);
$ffi = FFI::cdef($headers, __DIR__ . $RELATIVE_PATH . '/librisdk.dll');

$errorText = $ffi->new('char[1000]', 0); // Текст ошибки. Передается как входной параметр,при возникновении ошибки в эту переменную будет записан текст ошибки
$i2c = $ffi->new('int', 0);
$pwm = $ffi->new('int', 0);
$d_mg996r = $ffi->new('int', 0);
$state = $ffi->new('int', 0);

// Инициализация библиотеки RI SDK с уровнем логирования 3
$errCode = $ffi->RI_SDK_InitSDK(3, $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText) . " errCode: " . $errCode . " \n");
    return $errCode;
}

// Создание компонента i2c адаптера модели ch341
$errCode = $ffi->RI_SDK_CreateModelComponent("connector", "i2c_adapter", "ch341", FFI::addr($i2c), $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

print("i2c: " . $i2c->cdata . "\n");

// Создание компонента ШИМ модели pca9685
$errCode = $ffi->RI_SDK_CreateModelComponent("connector", "pwm", "pca9685", FFI::addr($pwm), $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

print("pwm: " . $pwm->cdata . "\n");

// Создание компонента сервопривода вращения модели mg996r
$errCode = $ffi->RI_SDK_CreateModelComponent("executor", "servodrive_rotate", "mg996r", FFI::addr($d_mg996r), $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

print("servodrive rotate: " . $d_mg996r->cdata . "\n");

// Связывание i2c с ШИМ
$errCode = $ffi->RI_SDK_LinkPWMToController($pwm->cdata, $i2c->cdata, 0x40, $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

// Связывание ШИМ с сервоприводом
$errCode = $ffi->RI_SDK_LinkRServodriveToController($d_mg996r->cdata, $pwm->cdata, 0, $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

// Получение начального состояния сервопривода вращения
$errCode = $ffi->RI_SDK_exec_RServoDrive_GetState($d_mg996r->cdata, FFI::addr($state), $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

print("state before work: " . $state->cdata . "\n");

// Вращение сервопривода по часовой стрелке. Скорость движения - 50% от максимальной скорости
$errCode = $ffi->RI_SDK_exec_RServoDrive_RotateWithRelativeSpeedOverTime($d_mg996r->cdata, 0, 50, 2000, true, $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

usleep(1000000);

// Получение состояния сервопривода вращения во время работы
$errCode = $ffi->RI_SDK_exec_RServoDrive_GetState($d_mg996r->cdata, FFI::addr($state), $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

print("work state: " . $state->cdata . "\n");

// Остановка работы сервопривода вращения
$errCode = $ffi->RI_SDK_exec_RServoDrive_Stop($d_mg996r->cdata, $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

usleep(100000);

// Получение состояния сервопривода вращения
$errCode = $ffi->RI_SDK_exec_RServoDrive_GetState($d_mg996r->cdata, FFI::addr($state), $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

print("await state: " . $state->cdata . "\n");

// Удаление библиотеки со всеми компонентами
$errCode = $ffi->RI_SDK_DestroySDK(true, $errorText);
if ($errCode) {
    print("errorText:" . FFI::string($errorText). " errCode: " . $errCode . " \n");
    return $errCode;
}

print("Success \n");
?>

43 просмотров0 комментариев

Комментарии (0)

Для участия в обсуждении вы должны быть авторизованным пользователем
Разделы
Программирование на Blockly
Документация по RoboIntellect SDK (RI SDK)
Функциональный RI SDK API исполнительных устройств

Навигация

ВойтиРегистрация