OpenHarmony开源社区
直播中

jf_25674040

2年用户 109经验值
擅长:可编程逻辑 MEMS/传感技术 接口/总线/驱动 控制/MCU
私信 关注

【九联科技Unionpi Tiger开发板试用体验】ros noetic 实时读取adc值

1. 硬件连接

adc.jpg

2. 部分软件代码

void Adc::update(const ros::TimerEvent& e)
{
  int value = 0;
  double voltage = 0.0;
  if (get_adc_data(ADC_2, &value) >= 0)
  {
    voltage = ((double)value) * TEMP_CONST;
    std_msgs::Float64 msg;
    msg.data = voltage;
    voltage_pub_.publish(msg);
  }
  else
  {
    int max_count = output_hz_ * 5;
    open_count_++;
    if (open_count_ >= max_count)
    {
      open_count_ = 0;
    }
  }
  updateDiagnostics();
}

void Adc::updateDiagnostics()
{
  int max_count = output_hz_;
  diag_count_++;
  if (diag_count_ >= max_count)
  {
    diag_count_ = 0;
    diagnostic_updater_.update();
  }
}

int Adc::get_adc_data(int adc_channel, int *value)
{
    if (value == NULL) {
        printf("value pointer error\n");
        return ADC_ERROR;
    }

    char adc_path[128];
    (void)memset(adc_path, 0, sizeof(adc_path));

    if (adc_channel == ADC_1) {
        (void)sprintf(adc_path, "%s", ADC_CHANNEL_1);
    } else if (adc_channel == ADC_2) {
        (void)sprintf(adc_path, "%s", ADC_CHANNEL_2);
    } else {
        printf("no such a adc_channel\n");
        return ADC_ERROR;
    }

    FILE *fp = NULL;
    char buffer[sizeof(int)];
    fp = fopen(adc_path, "r");
    if (!fp) {
        perror("fopen");
        return ADC_ERROR;
    }
    (void)fread(buffer, sizeof(buffer), 1, fp);
    (void)fclose(fp);
    fp = NULL;

    *value = atoi(buffer);

    return 0;
}

3. 实际效果

adc

更多回帖

发帖
×
20
完善资料,
赚取积分