You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
2.4 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. #include "motor_drive.h"
  2. #include "driver/uart.h"
  3. #include "esp_log.h"
  4. #define MOTOR_DRIVE "MOTOR_DRIVE"
  5. #define uart_num UART_NUM_2
  6. #define tx_io_num 4
  7. #define rx_io_num 5
  8. #define buffer_size 128
  9. void motor_drive_uart_init() {
  10. uart_config_t uart_config = {
  11. .baud_rate = 115200,
  12. .data_bits = UART_DATA_8_BITS,
  13. .parity = UART_PARITY_DISABLE,
  14. .stop_bits = UART_STOP_BITS_1,
  15. .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
  16. .source_clk = UART_SCLK_APB,
  17. };
  18. ESP_ERROR_CHECK(uart_driver_install(uart_num, buffer_size * 2, 0, 0, NULL, 0));
  19. ESP_ERROR_CHECK(uart_param_config(uart_num, &uart_config));
  20. ESP_ERROR_CHECK(uart_set_pin(uart_num, tx_io_num, rx_io_num, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));
  21. }
  22. void motor_drive_turn(int direction, int speed_level, double position) {
  23. if ((direction > 2) || (direction < 0)) {
  24. ESP_LOGW(MOTOR_DRIVE, "Direction out of range");
  25. }
  26. if ((speed_level > 9) || (speed_level < 0)) {
  27. ESP_LOGW(MOTOR_DRIVE, "Speed level out of range");
  28. }
  29. if ((position > 360) || (position <= 0)) {
  30. ESP_LOGW(MOTOR_DRIVE, "Position out of range");
  31. }
  32. motor_drive_set_packages_ctr(position);
  33. uart_write_bytes(uart_num, "test", strlen("test"));
  34. }
  35. double motor_drive_read_encoder() { return 0.0; }
  36. void motor_drive_set_packages() {}
  37. void motor_drive_set_packages_ctr(double position) {
  38. int position_int = 0;
  39. uint8_t position_remainder = 0;
  40. uint8_t position_buffer_size = 5; //从第五位开始(低位)
  41. uint8_t checksum = 0;
  42. uint8_t buffer[10] = {0x3E, 0XA7, 0X01, 0X04, 0XEA, 0X00, 0X00, 0X00, 0X00, 0X00};
  43. uint8_t strbuffer[20] = {0};
  44. position_int = position * 100;
  45. if (position_int != 0) {
  46. while ((position_int / 256) > 0) {
  47. position_remainder = position_int % 256;
  48. buffer[position_buffer_size] = position_remainder;
  49. position_buffer_size += 1;
  50. position_int = position_int / 256;
  51. checksum += position_remainder;
  52. }
  53. buffer[position_buffer_size] = position_int;
  54. checksum += position_int;
  55. checksum %= 256;
  56. buffer[9] = checksum;
  57. }
  58. for (int i = 0; i < 10; i++) {
  59. ESP_LOGI(MOTOR_DRIVE, "%d", buffer[i]);
  60. }
  61. motor_drive_hex_to_str((char *)buffer, 10, (char *)strbuffer);
  62. ESP_LOGI(MOTOR_DRIVE, "%s", strbuffer);
  63. }
  64. void motor_drive_hex_to_str(char *hex, int hex_len, char *str) {
  65. int i, pos = 0;
  66. for (i = 0; i < hex_len; i++)
  67. {
  68. sprintf(str + pos, "%02x", hex[i]);
  69. pos += 2;
  70. }
  71. }