Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Linux 下用 C 語言實作非阻塞串口測試程式:資料讀取的關鍵細節

一、前言

網上現成的串口工具很多,但只提供功能界面,內部如何實作仍需自己摸索;網上的串口通信程式也不罕見,只是不少是直接複製而來且缺乏註釋,細節問題就被忽略了。

本文程式分為三部分:設定通信協議、讀寫字符串函數、通信測試函數。不必全部讀完,測試函數挑兩個典型的看即可。

四個要點:

  1. 本文提供串口通信的設定接口,方便複用。
  2. 發送指令後讀取模組回傳資料時,保險起見採用阻塞式讀取;串口一次只能讀取 8 位元組,注意讀取函數的呼叫方式。
  3. 注意讀寫命令中含有 0x00 時的處理方式。
  4. 通信成功但模組總回傳「操作失敗」時的排查思路。

二、程式實作

操作串口的第一步是找到設備節點,嵌入式 Linux 的串口通常位於 /dev/ 下,本例操作 /dev/ttySAC0。

本例通信協議:波特率 9600 bps、8 位資料位、1 位起始位、1 位停止位、無奇偶校驗。通信成功時回傳操作成功或失敗的代碼。

Linux 下用 C 語言實作非阻塞串口測試程式:資料讀取的關鍵細節

需要特別說明:回傳「操作失敗」並不代表通信失敗——模組已回應,證明链路是通的,只是硬體本身動作失敗。另外指令中的 CS 為校驗位,算法是 0 減去前面所有位元組之和,例如 80 06 05 01 CS,CS = 0-(0x80+0x06+0x05+0x01) = 0x74,故完整指令為 80 06 05 01 74。

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <termios.h>
#include <fcntl.h>
#include <errno.h>

#define TRUE 1
#define FALSE -1
#define BUFF_MAXSIZE 2048
#define FREQUENCY_00 0
#define FREQUENCY_05 5
#define FREQUENCY_10 10
#define FREQUENCY_20 20
#define RESOLUTION_ONE_MM 1
#define RESOLUTION_Z_P_ONE_MM 2
#define MEASURING_POWER_ON 1
#define MEASURING_POWER_OFF 0

typedef unsigned char un_char;

int OpenDev(char *dev);
int set_speed(int fd, int speed, struct termios* newtio);
int Set_Parity(int fd, int databits, int stopbits, int parity);
int Write_Data(int fd, void *buf, int len);
int Read_Data(int fd, char *buff);
int Open_LaserModule(int fd);
int Close_LaserModule(int fd);
int Set_Address(int fd);
un_char* Read_Parameter(int fd, un_char* device_parameter);
un_char* Read_Device_Num(int fd, un_char* device_num);
int Distance_Modification(int fd, int decrease_or_increase, int distance_int);
int Mea_Interval(int fd, int interval_time_int);
int Distance_StartStop(int fd, int position_int);
int Set_MeasuringRange(int fd, int range);
int Set_Frequency(int fd, int freg);
int Set_Resolution(int fd, int mode);
int Measuring_Power(int fd, int on_off);
int Single_Measurement_Broadcast(int fd);
un_char* Read_Cache(int fd, un_char* cache_data);
un_char* Single_Measurement(int fd, un_char* single_mea);
un_char* Continuous_Measurement(int fd, un_char* continuous_mea);

int speed_arr[] = {B115200, B38400, B19200, B9600, B4800, B2400, B1200, B300};
int name_arr[]  = {115200, 38400, 19200, 9600, 4800, 2400, 1200, 300};

int main(int argc, char *argv[]) {
    int fd;
    un_char Buff_data_device[BUFF_MAXSIZE] = {0};
    struct termios oldtio, newtio;

    char *dev = "/dev/ttySAC0";
    fd = OpenDev(dev);
    tcgetattr(fd, &oldtio);
    if (fd > 0) set_speed(fd, 9600, &newtio);
    else { printf("Can't Open Serial Port!\n"); exit(0); }

    if (Set_Parity(fd, 8, 1, 'S') == FALSE) {
        printf("Set Parity Error!\n");
        exit(1);
    }

    Open_LaserModule(fd);
    Set_Resolution(fd, RESOLUTION_Z_P_ONE_MM);
    Measuring_Power(fd, MEASURING_POWER_ON);
    Set_Frequency(fd, FREQUENCY_05);
    Set_MeasuringRange(fd, 80);
    sleep(5);
    Read_Parameter(fd, Buff_data_device);
    Set_Address(fd);
    Distance_Modification(fd, 1, 2);
    Mea_Interval(fd, 5);
    Distance_StartStop(fd, 0);
    sleep(5);
    Read_Cache(fd, Buff_data_device);
    sleep(5);
    Single_Measurement(fd, Buff_data_device);
    sleep(5);
    Continuous_Measurement(fd, Buff_data_device);
    Close_LaserModule(fd);
    close(fd);
}

int OpenDev(char *dev) {
    int fd = open(dev, O_RDWR | O_NOCTTY | O_NDELAY);
    if (fd == -1) { printf("Can't Open Serial Port!\n"); return FALSE; }
    return fd;
}

int set_speed(int fd, int speed, struct termios* newtio) {
    int status;
    struct termios* Opt = newtio;
    tcgetattr(fd, Opt);
    for (int i = 0; i < sizeof(speed_arr)/sizeof(int); i++) {
        if (speed == name_arr[i]) {
            tcflush(fd, TCIOFLUSH);
            cfsetispeed(Opt, speed_arr[i]);
            cfsetospeed(Opt, speed_arr[i]);
            status = tcsetattr(fd, TCSANOW, Opt);
            if (status != 0) { printf("tcsetattr failed!\n"); return FALSE; }
            tcflush(fd, TCIOFLUSH);
        }
    }
    return TRUE;
}

int Set_Parity(int fd, int databits, int stopbits, int parity) {
    struct termios options;
    if (tcgetattr(fd, &options) != 0) { printf("Setup Serial 1 error!\n"); return FALSE; }
    bzero(&options, sizeof(options));
    options.c_cflag &= ~CSIZE;
    switch (databits) {
        case 7: options.c_cflag |= CS7; break;
        case 8: options.c_cflag |= CS8; break;
        default: printf("Unsupported data size!\n"); return FALSE;
    }
    switch (parity) {
        case 'n': case 'N':
            options.c_cflag &= ~(PARENB);
            options.c_cflag &= ~(INPCK);
            break;
        case 'o': case 'O':
            options.c_cflag |= (PARODD | PARENB);
            options.c_cflag |= INPCK;
            break;
        case 'e': case 'E':
            options.c_cflag |= PARENB;
            options.c_cflag &= ~(PARODD);
            options.c_cflag |= INPCK;
            break;
        case 's': case 'S':
            options.c_cflag &= ~(PARENB);
            options.c_cflag &= ~(CSTOPB);
            break;
        default: printf("Unsupported parity!\n"); return FALSE;
    }
    switch (stopbits) {
        case 1: options.c_cflag &= ~(CSTOPB); break;
        case 2: options.c_cflag |= CSTOPB; break;
        default: printf("Unsupported stop bits!\n"); return FALSE;
    }
    if (parity != 'n') {
        options.c_cflag |= CLOCAL;
        options.c_cflag |= CREAD;
        options.c_lflag &= ~(ICANON | ECHO | ECHOE);
        options.c_iflag &= ~(IXON | IXOFF | IXANY);
        options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
        options.c_oflag &= ~OPOST;
    }
    options.c_cc[VTIME] = 0;
    options.c_cc[VMIN] = 0;
    tcflush(fd, TCIFLUSH);
    if (tcsetattr(fd, TCSANOW, &options) != 0) { printf("Setup Serial error!\n"); return FALSE; }
    return 0;
}

int Write_Data(int fd, void *buf, int len) {
    int write_count = 0, nwrite = 0;
    if (fd < 0) printf("Please Open The Device File!\n");
    while (len > 0) {
        nwrite = write(fd, (char*)buf + write_count, len);
        if (nwrite < 1) { printf("Write Data Fail!\n"); break; }
        write_count += nwrite;
        len -= nwrite;
    }
    tcflush(fd, TCIOFLUSH);
    return write_count;
}

int Read_Data(int fd, char* buff) {
    int nread = 0;
    int fd_max = fd + 1;
    fd_set readfds;
    FD_ZERO(&readfds);
    FD_SET(fd, &readfds);
    int nselect = select(fd_max, &readfds, NULL, NULL, NULL);
    memset(buff, 0, sizeof(buff));
    if (nselect <= 0) printf("select failed");
    else if (FD_ISSET(fd, &readfds) > 0) {
        nread = read(fd, buff, 8);
        buff[nread] = '\0';
    }
    for (int j = 0; buff[j] != '\0'; j++)
        printf("the readable data is 0x%x\n", buff[j]);
    return nread;
}

int Open_LaserModule(int fd) {
    un_char Buff_Open[BUFF_MAXSIZE] = {0x80, 0x06, 0x05, 0x01, 0x74};
    un_char Open_Succeeded[BUFF_MAXSIZE] = {0x80, 0x06, 0x85, 0x01, 0xF4};
    un_char Open_Failed[BUFF_MAXSIZE] = {0x80, 0x06, 0x85, 0x00, 0xF5};
    Write_Data(fd, Buff_Open, strlen(Buff_Open));
    Read_Data(fd, Buff_Open);
    if (strcmp(Buff_Open, Open_Succeeded) == 0) printf("Open_LaserModule Succeeded!\n");
    else if (strcmp(Buff_Open, Open_Failed) == 0) printf("Open_LaserModule Failed, Please Try Again!\n");
    else { printf("NG\n"); return FALSE; }
    return TRUE;
}

int Close_LaserModule(int fd) {
    un_char Buff_Close[BUFF_MAXSIZE] = {0x80, 0x06, 0x05, 0x00, 0x75};
    un_char Close_Succeeded[BUFF_MAXSIZE] = {0x80, 0x06, 0x85, 0x01, 0xF4};
    un_char Close_Failed[BUFF_MAXSIZE] = {0x80, 0x06, 0x85, 0x00, 0xF5};
    /* 資料中間有 0x00,因此指定長度為 5,不用 strlen() */
    Write_Data(fd, Buff_Close, 5);
    Read_Data(fd, Buff_Close);
    if (strcmp(Buff_Close, Close_Succeeded) == 0) printf("Close_LaserModule Succeeded!\n");
    else if (strcmp(Buff_Close, Close_Failed) == 0) printf("Close_LaserModule Failed, Please Try Again!\n");
    else { printf("NG\n"); return FALSE; }
    return TRUE;
}

un_char* Read_Parameter(int fd, un_char* device_parameter) {
    un_char Buff_Read_Parameter[BUFF_MAXSIZE] = {0xFA, 0x06, 0x01, 0xFF};
    Write_Data(fd, Buff_Read_Parameter, strlen(Buff_Read_Parameter));
    Read_Data(fd, Buff_Read_Parameter);
    printf("*******The parameter have read!**********\n");
    strcpy(device_parameter, Buff_Read_Parameter);
    return device_parameter;
}

/* 串口每次只能讀 8 位元組,讀機器號需連續讀三次 */
un_char* Read_Device_Num(int fd, un_char* device_num) {
    int nread = 0;
    un_char Buff_Read_DeviceNum[BUFF_MAXSIZE] = {0xFA, 0x06, 0x04, 0xFC};
    un_char Buff_read_back[BUFF_MAXSIZE] = {0};
    un_char *Buff_bp = Buff_read_back;
    Write_Data(fd, Buff_Read_DeviceNum, strlen(Buff_Read_DeviceNum));
    nread = Read_Data(fd, Buff_Read_DeviceNum);
    memcpy(Buff_bp, Buff_Read_DeviceNum, nread); Buff_bp += nread;
    nread = Read_Data(fd, Buff_Read_DeviceNum);
    memcpy(Buff_bp, Buff_Read_DeviceNum, nread); Buff_bp += nread;
    nread = Read_Data(fd, Buff_Read_DeviceNum);
    strcpy(Buff_bp, Buff_Read_DeviceNum);
    strcpy(device_num, Buff_read_back);
    return device_num;
}

int Set_Address(int fd) {
    un_char Buff_Address[BUFF_MAXSIZE] = {0xFA, 0x04, 0x01, 0x80, 0x81};
    un_char Address_Succeeded[BUFF_MAXSIZE] = {0xFA, 0x04, 0x81, 0x81};
    un_char Address_Failed[BUFF_MAXSIZE] = {0xFA, 0x84, 0x81, 0x02, 0xFF};
    Write_Data(fd, Buff_Address, strlen(Buff_Address));
    Read_Data(fd, Buff_Address);
    if (strcmp(Buff_Address, Address_Succeeded) == 0) printf("Set_Address Succeeded!\n");
    else if (strcmp(Buff_Address, Address_Failed) == 0) printf("Set Address Error, Please Write Again!\n");
    else { printf("NG\n"); return FALSE; }
    return TRUE;
}

int Distance_Modification(int fd, int decrease_or_increase, int distance_int) {
    un_char decrease_increase = (un_char)decrease_or_increase;
    un_char distance_ch = (un_char)distance_int;
    int c_s = -250 - 4 - 6 - decrease_or_increase - distance_int;   /* 250 即 0xFA */
    un_char cs = (un_char)c_s;
    un_char Buff_Distance_Mo[BUFF_MAXSIZE] = {0};
    Buff_Distance_Mo[0] = 0xFA;
    Buff_Distance_Mo[1] = 0x04;
    Buff_Distance_Mo[2] = 0x06;
    Buff_Distance_Mo[3] = decrease_increase;
    Buff_Distance_Mo[4] = distance_ch;
    Buff_Distance_Mo[5] = cs;
    un_char Distance_ModificationSd[BUFF_MAXSIZE] = {0xFA, 0x04, 0x8B, 0x77};
    un_char Distance_ModificationFd[BUFF_MAXSIZE] = {0xFA, 0x84, 0x8B, 0x01, 0xF6};
    Write_Data(fd, Buff_Distance_Mo, strlen(Buff_Distance_Mo));
    Read_Data(fd, Buff_Distance_Mo);
    if (strcmp(Buff_Distance_Mo, Distance_ModificationSd) == 0) {
        if (decrease_or_increase == 43) printf("Distance_Increase_Modification_Succeeded\n");
        else printf("Distance_Decrease_Modification_Succeeded\n");
    } else if (strcmp(Buff_Distance_Mo, Distance_ModificationFd) == 0) {
        if (decrease_or_increase == 43) printf("Distance_Increase_Modification_Failed\n");
        else printf("Distance_Decrease_Modification_Failed\n");
    } else { printf("NG\n"); return FALSE; }
    return TRUE;
}

int Mea_Interval(int fd, int interval_time_int) {
    int c_s = -250 - 4 - 5 - interval_time_int;
    un_char cs = (un_char)c_s;
    un_char interval_ch = (un_char)interval_time_int;
    un_char Buff_Mea_Interval[BUFF_MAXSIZE] = {0};
    Buff_Mea_Interval[0] = 0xFA;
    Buff_Mea_Interval[1] = 0x04;
    Buff_Mea_Interval[2] = 0x05;
    Buff_Mea_Interval[3] = interval_ch;
    Buff_Mea_Interval[4] = cs;
    un_char Mea_IntervalSd[BUFF_MAXSIZE] = {0xFA, 0x04, 0x85, 0x7D};
    un_char Mea_IntervalFd[BUFF_MAXSIZE] = {0xFA, 0x84, 0x85, 0x01, 0xFC};
    un_char Write_IntervalErr[BUFF_MAXSIZE] = {0xFA, 0x84, 0x85, 0x01, 0xFA};
    Write_Data(fd, Buff_Mea_Interval, strlen(Buff_Mea_Interval));
    Read_Data(fd, Buff_Mea_Interval);
    if (strcmp(Buff_Mea_Interval, Mea_IntervalSd) == 0) printf("Mea_Interval_Succeeded\n");
    else if (strcmp(Buff_Mea_Interval, Mea_IntervalFd) == 0) printf("Mea_Interval_Failed, Please Try Again!\n");
    else if (strcmp(Buff_Mea_Interval, Write_IntervalErr) == 0) printf("Mea_Interval_Error\n");
    else { printf("NG\n"); return FALSE; }
    return TRUE;
}

int Distance_StartStop(int fd, int position_int) {
    int c_s = -250 - 4 - 8 - position_int;
    un_char cs = (un_char)c_s;
    un_char position_ch = (un_char)position_int;
    un_char Buff_StartStop[BUFF_MAXSIZE] = {0};
    Buff_StartStop[0] = 0xFA;
    Buff_StartStop[1] = 0x04;
    Buff_StartStop[2] = 0x08;
    Buff_StartStop[3] = position_ch;
    Buff_StartStop[4] = cs;
    un_char Mea_Distance_StartStopSd[BUFF_MAXSIZE] = {0xFA, 0x04, 0x88, 0x7A};
    un_char Mea_Distance_StartStopFd[BUFF_MAXSIZE] = {0xFA, 0x84, 0x88, 0x01, 0xF9};
    if (Buff_StartStop[3] == 0x00) Write_Data(fd, Buff_StartStop, 5);
    else Write_Data(fd, Buff_StartStop, strlen(Buff_StartStop));
    Read_Data(fd, Buff_StartStop);
    if (strcmp(Buff_StartStop, Mea_Distance_StartStopSd) == 0) printf("Mea_Distance_StartStop_Succeeded!\n");
    else if (strcmp(Buff_StartStop, Mea_Distance_StartStopFd) == 0) printf("Write Mea_Distance_StartStop_Failed, Please Write Again!\n");
    else { printf("NG\n"); return FALSE; }
    return TRUE;
}

int Set_MeasuringRange(int fd, int range) {
    un_char Buff_Range_05[BUFF_MAXSIZE] = {0xFA, 0x04, 0x09, 0x05, 0xF4};
    un_char Buff_Range_10[BUFF_MAXSIZE] = {0xFA, 0x04, 0x09, 0x0A, 0xEF};
    un_char Buff_Range_30[BUFF_MAXSIZE] = {0xFA, 0x04, 0x09, 0x1E, 0xDB};
    un_char Buff_Range_50[BUFF_MAXSIZE] = {0xFA, 0x04, 0x09, 0x32, 0xC7};
    un_char Buff_Range_80[BUFF_MAXSIZE] = {0xFA, 0x04, 0x09, 0x50, 0xA9};
    un_char Set_MeasuringRangeSd[BUFF_MAXSIZE] = {0xFA, 0x04, 0x89, 0x79};
    un_char Set_MeasuringRangeFd[BUFF_MAXSIZE] = {0xFA, 0x84, 0x89, 0x01, 0xF8};
    un_char *cmd = NULL;
    switch (range) {
        case 5:  cmd = Buff_Range_05; break;
        case 10: cmd = Buff_Range_10; break;
        case 30: cmd = Buff_Range_30; break;
        case 50: cmd = Buff_Range_50; break;
        case 80: cmd = Buff_Range_80; break;
        default: printf("Please Set The Correct Range Parameters!\n"); return FALSE;
    }
    Write_Data(fd, cmd, strlen(cmd));
    Read_Data(fd, cmd);
    if (strcmp(cmd, Set_MeasuringRangeSd) == 0) printf("Set_MeasuringRange_%02d_Succeeded\n", range);
    else if (strcmp(cmd, Set_MeasuringRangeFd) == 0) printf("Set_MeasuringRange_%02d_Failed, Please Try Again!\n", range);
    else { printf("NG\n"); return FALSE; }
    return TRUE;
}

int Set_Frequency(int fd, int freg) {
    un_char Buff_Frequency_00[BUFF_MAXSIZE] = {0xFA, 0x04, 0x0A, 0x00, 0xF8};
    un_char Buff_Frequency_05[BUFF_MAXSIZE] = {0xFA, 0x04, 0x0A, 0x05, 0xF3};
    un_char Buff_Frequency_10[BUFF_MAXSIZE] = {0xFA, 0x04, 0x0A, 0x0A, 0xEE};
    un_char Buff_Frequency_20[BUFF_MAXSIZE] = {0xFA, 0x04, 0x0A, 0x14, 0xE4};
    un_char Set_FrequencySd[BUFF_MAXSIZE] = {0xFA, 0x04, 0x8A, 0x78};
    un_char Set_FrequencyFd[BUFF_MAXSIZE] = {0xFA, 0x84, 0x8A, 0x01, 0xF7};
    un_char *cmd = NULL;
    int len = 0;
    switch (freg) {
        /* 資料中間有 0x00,指定 5 個位元組 */
        case 0:  cmd = Buff_Frequency_00; len = 5; break;
        case 5:  cmd = Buff_Frequency_05; break;
        case 10: cmd = Buff_Frequency_10; break;
        case 20: cmd = Buff_Frequency_20; break;
        default: printf("Please Set The Correct Frequency Parameters!\n"); return FALSE;
    }
    Write_Data(fd, cmd, len ? len : strlen(cmd));
    Read_Data(fd, cmd);
    if (strcmp(cmd, Set_FrequencySd) == 0) printf("Set_Frequency_%02d_Succeeded\n", freg);
    else if (strcmp(cmd, Set_FrequencyFd) == 0) printf("Set_Frequency_%02d_Failed, Please Try Again!\n", freg);
    else { printf("NG\n"); return FALSE; }
    return TRUE;
}

int Set_Resolution(int fd, int mode) {
    un_char Buff_Resolution_One[BUFF_MAXSIZE] = {0xFA, 0x04, 0x0C, 0x01, 0xF5};
    un_char Buff_Resolution_ZPOne[BUFF_MAXSIZE] = {0xFA, 0x04, 0x0C, 0x02, 0xF4};
    un_char Set_ResolutionSd[BUFF_MAXSIZE] = {0xFA, 0x04, 0x8C, 0x76};
    un_char Set_ResolutionFd[BUFF_MAXSIZE] = {0xFA, 0x84, 0x8C, 0x01, 0xF5};
    un_char *cmd = NULL;
    switch (mode) {
        case 1: cmd = Buff_Resolution_One; break;
        case 2: cmd = Buff_Resolution_ZPOne; break;
        default: printf("Please Set The Correct Resolution Parameters!\n"); return FALSE;
    }
    Write_Data(fd, cmd, strlen(cmd));
    Read_Data(fd, cmd);
    if (strcmp(cmd, Set_ResolutionSd) == 0)
        printf(mode == 1 ? "Set_One_mm_Resolution_Succeeded\n" : "Set_ZPOne_mm_Resolution_Succeeded\n");
    else if (strcmp(cmd, Set_ResolutionFd) == 0)
        printf(mode == 1 ? "Set_One_mm_Resolution_Failed, Please Try Again!\n" : "Set_ZPOne_mm_Resolution_Failed, Please Try Again!\n");
    else { printf("NG\n"); return FALSE; }
    return TRUE;
}

int Measuring_Power(int fd, int on_off) {
    un_char Buff_Measuring_On[BUFF_MAXSIZE] = {0xFA, 0x04, 0x0D, 0x01, 0xF4};
    un_char Buff_Measuring_Off[BUFF_MAXSIZE] = {0xFA, 0x04, 0x0D, 0x00, 0xF5};
    un_char Measuring_PowerSd[BUFF_MAXSIZE] = {0xFA, 0x04, 0x8D, 0x75};
    un_char Measuring_PowerFd[BUFF_MAXSIZE] = {0xFA, 0x84, 0x8D, 0x01, 0xF4};
    un_char *cmd = NULL;
    int len = 0;
    switch (on_off) {
        case 0: cmd = Buff_Measuring_Off; len = 5; break;   /* 含 0x00 */
        case 1: cmd = Buff_Measuring_On; break;
        default: printf("Please Set The Correct On_Off Mode Parameters!\n"); return FALSE;
    }
    Write_Data(fd, cmd, len ? len : strlen(cmd));
    Read_Data(fd, cmd);
    if (strcmp(cmd, Measuring_PowerSd) == 0)
        printf(on_off ? "Measuring_Power_On_Succeeded\n" : "Measuring_Power_Off_Succeeded\n");
    else if (strcmp(cmd, Measuring_PowerFd) == 0)
        printf(on_off ? "Measuring_Power_On_Failed, Please Try Again!\n" : "Measuring_Power_Off_Failed, Please Try Again!\n");
    else { printf("NG\n"); return FALSE; }
    return TRUE;
}

int Single_Measurement_Broadcast(int fd) {
    un_char Buff_Single_MeaBroadcast[BUFF_MAXSIZE] = {0xFA, 0x06, 0x06, 0xFA};
    Write_Data(fd, Buff_Single_MeaBroadcast, strlen(Buff_Single_MeaBroadcast));
    return TRUE;
}

un_char* Read_Cache(int fd, un_char* cache_data) {
    int nread = 0;
    un_char Buff_Read_Cache[BUFF_MAXSIZE] = {0x80, 0x06, 0x07, 0x73};
    un_char Buff_Read_Back[BUFF_MAXSIZE] = {0};
    un_char *Buff_bp = Buff_Read_Back;
    Write_Data(fd, Buff_Read_Cache, strlen(Buff_Read_Cache));
    nread = Read_Data(fd, Buff_Read_Cache);
    memcpy(Buff_bp, Buff_Read_Cache, nread); Buff_bp += nread;
    nread = Read_Data(fd, Buff_Read_Cache);
    strcpy(Buff_bp, Buff_Read_Cache);
    /* 依回傳長度與第四個位元組(下標3)判斷:3X 只能是 0x30~0x3F,E/e 為 69/101 */
    if (strlen(Buff_Read_Back) == 11 && Buff_Read_Back[3] >= 48 && Buff_Read_Back[3] <= 63)
        printf("Read_Cache_on_1mm_Succeeded!\n");
    else if (strlen(Buff_Read_Back) == 12 && Buff_Read_Back[3] >= 48 && Buff_Read_Back[3] <= 63)
        printf("Read_Cache_on_0.1mm_Succeeded!\n");
    else if (Buff_Read_Back[3] == 69 || Buff_Read_Back[3] == 101) {
        if (strlen(Buff_Read_Back) == 11) printf("Single_Measurement_on_1mm_Failed, Please Try Again!\n");
        if (strlen(Buff_Read_Back) == 12) printf("Single_Measurement_on_0.1mm_Failed, Please Try Again!\n");
    } else { printf("NG!\n"); return NULL; }
    strcpy(cache_data, Buff_Read_Back);
    return cache_data;
}

un_char* Single_Measurement(int fd, un_char* single_mea) {
    int nread = 0;
    un_char Buff_Single_Measurement[BUFF_MAXSIZE] = {0x80, 0x06, 0x02, 0x78};
    un_char Buff_Read_Back[BUFF_MAXSIZE] = {0};
    un_char *Buff_bp = Buff_Read_Back;
    Write_Data(fd, Buff_Single_Measurement, strlen(Buff_Single_Measurement));
    nread = Read_Data(fd, Buff_Single_Measurement);
    memcpy(Buff_bp, Buff_Single_Measurement, nread); Buff_bp += nread;
    nread = Read_Data(fd, Buff_Single_Measurement);
    strcpy(Buff_bp, Buff_Single_Measurement);
    if (strlen(Buff_Read_Back) == 11 && Buff_Read_Back[3] >= 48 && Buff_Read_Back[3] <= 63)
        printf("Single_Measurement_on_1mm_Succeeded!\n");
    else if (strlen(Buff_Read_Back) == 12 && Buff_Read_Back[3] >= 48 && Buff_Read_Back[3] <= 63)
        printf("Single_Measurement_on_0.1mm_Succeeded!\n");
    else if (Buff_Read_Back[3] == 69 || Buff_Read_Back[3] == 101) {
        if (strlen(Buff_Read_Back) == 11) printf("Single_Measurement_on_1mm_Failed, Please Try Again!\n");
        if (strlen(Buff_Read_Back) == 12) printf("Single_Measurement_on_0.1mm_Failed, Please Try Again!\n");
    } else { printf("NG!\n"); return NULL; }
    strcpy(single_mea, Buff_Read_Back);
    return single_mea;
}

un_char* Continuous_Measurement(int fd, un_char* continuous_mea) {
    int nread = 0;
    un_char Buff_Continuous_Measurement[BUFF_MAXSIZE] = {0x80, 0x06, 0x03, 0x77};
    un_char Buff_Read_Back[BUFF_MAXSIZE] = {0};
    un_char *Buff_bp = Buff_Read_Back;
    Write_Data(fd, Buff_Continuous_Measurement, strlen(Buff_Continuous_Measurement));
    nread = Read_Data(fd, Buff_Continuous_Measurement);
    memcpy(Buff_bp, Buff_Continuous_Measurement, nread); Buff_bp += nread;
    nread = Read_Data(fd, Buff_Continuous_Measurement);
    strcpy(Buff_bp, Buff_Continuous_Measurement);
    if (strlen(Buff_Read_Back) == 11 && Buff_Read_Back[3] >= 48 && Buff_Read_Back[3] <= 63)
        printf("Continuous_Measurement_on_1mm_Succeeded!\n");
    else if (strlen(Buff_Read_Back) == 12 && Buff_Read_Back[3] >= 48 && Buff_Read_Back[3] <= 63)
        printf("Continuous_Measurement_on_0.1mm_Succeeded!\n");
    else if (Buff_Read_Back[3] == 69 || Buff_Read_Back[3] == 101) {
        if (strlen(Buff_Read_Back) == 11) printf("Continuous_Measurement_on_1mm_Failed, Please Try Again!\n");
        if (strlen(Buff_Read_Back) == 12) printf("Continuous_Measurement_on_0.1mm_Failed, Please Try Again!\n");
    } else { printf("NG!\n"); return NULL; }
    strcpy(continuous_mea, Buff_Read_Back);
    return continuous_mea;
}

三、源碼要點說明

① 為何用阻塞式讀取。發送指令後模組未必能立刻回應,若採非阻塞讀取,很可能一次讀不到資料就返回,反而誤判為失敗。

② 一次 8 位元組的限制。串口一次只能讀取 8 個位元組,資料更長就多讀幾次:

int readtime(int bit) {
    int n = bit;
    int time = n / 8;
    if (n % 8 == 0) printf("read time is %d", time);
    else printf("read time is %d", time + 1);
}

多次讀取時,中途拼接必須用 memcpy 而非 strcpy:

nread = Read_Data(fd, Buff_Continuous_Measurement);
memcpy(Buff_bp, Buff_Continuous_Measurement, nread);
Buff_bp += nread;
nread = Read_Data(fd, Buff_Continuous_Measurement);
strcpy(Buff_bp, Buff_Continuous_Measurement);

差別在於 memcpy 複製時結尾不會自動補 \0,而 strcpy 會。若兩次都用 strcpy,資料中間會多出一個 \0,字串就在那裡被截斷了。

③ 資料含 0x00 時不要用 strlen。例如 Buff_Measuring_Off = {0xFA, 0x04, 0x0D, 0x00, 0xF5},寫入時直接指定 5 個位元組:Write_Data(fd, Buff_Measuring_Off, 5)。凡是可能出現 0x00 的指令都應該這樣處理。

④ 通信成功卻總回「操作失敗」。這個問題曾讓人哭笑不得:一段時間一直成功,過幾天又一直失敗。最後 found 出原因竟是模組供電電壓不足——屬於硬體問題。遇到類似狀況,先用示波器或電壓表確認供電,再回頭懷疑程式,能省下大量時間。

Copyright © Linux教程網 All Rights Reserved