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

linux環境下C語言實現非阻塞方式讀取字符串數據的串口測試程序,即串口工具的編寫

一、前言

1.1 關於串口測試工具,網上已經有集成好的應用程序提供大家使用,但其只提供功能接口,內部具體怎麼實現的還需要自己去探索; 1.2 關於串口通信的測試程序在網上已經是數見不鮮,但也不排除很多是直接“參考”別人的(ctrl+c),而且很多代碼沒有相關注釋,從而某些細節性的問題就被忽略;

1.3 本例程序不需全部讀完,分為3大部分,設置通信協議、讀寫字符串函數編寫、通信的測試函數,測試函數自己選取看兩個典型的就OK;如果哪有說的有誤,希望大家指正,多交流共同進步;

1.4 要點:①本文提供了設置串口通訊的接口,方便大家對程序的復用,感覺還是面向對象的語言更方便呀;②在給模塊發送指令後需要讀取模塊返回的數據時,保險起見采用阻塞式讀取,且串口一次只能讀取8位byte數據,注意讀取數據的調用函數;③注意在讀寫命令中存在0x00(零)的16進制的數據時的方式;④通信成功,但恰遇到模塊總返回操作失敗的代碼的問題。

二、串口測試程序的實現

2.1 要實現串口通信的操作,首先是找到需要操作的對象,即具體的串口設備,一般都在linux嵌入式設備的/dev/路徑下有很多串口設備,找到自己所要操作的串口設備,例如本例程所操作的是/dev/ttySAC0, ttySAC0為串口設備名稱; 2.2 模塊的串口通信協議,不同的模塊之間有細微差別,自己作相應的改動就好。本例程的通信協議:波特率9600bps, 8位數據位,1位起始位,一位停止位,無奇偶校驗。通信成功時,返回的是操作成功或者操作失敗的代碼,

PS:操作失敗並不是說的是通信失敗,因為去訪問模塊時,模塊給了應答,表明通信是成功的,只能說明是硬件本身操作失敗。發送的指令中存在CS,其值為0減去前面CS前面所有16進制的相加-例:80 06 05 01 CS, CS為:0-(80+06+05+01)=74 ,即需要發送的代碼為80 06 05 01 74;

2.3 源碼如下:

[code]#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      //設定的頻率為0
#define FREQUENCY_05 5      //設定的頻率為5
#define FREQUENCY_10 10     //設定的頻率為10
#define FREQUENCY_20 20     //設定的頻率為20
#define RESOLUTION_ONE_MM 1 //1表示選擇設定的分辨率為1mm
#define RESOLUTION_Z_P_ONE_MM 2 //2表示選擇設定的分辨率為0.1mm
#define MEASURING_POWER_ON 1    //1表示上電即測開啟 
#define MEASURING_POWER_OFF 0   //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);//距離修改,參數decrease_or_increase表示修正可選為取負或者取正,參數distance表示要修正的距離
int Mea_Interval(int fd, int interval_time_int);//連續測量時設置數據返回時間間隔,參數interval_time_int表示要設定的時間間隔為interval_time_int秒
int Distance_StartStop(int fd, int position_int);//設置距離起止點,參數position_int的值(1頂端算起;0加上模塊長度+上面的距離修正)
int Set_MeasuringRange(int fd, int range);//設定量程,range表示要設定的量程大小05, 10, 30, 50, 80
int Set_Frequency(int fd, int freg);//設定頻率,freg表示要設定的頻率大小,00,05,10,20
int Set_Resolution(int fd, int mode);//設定分辨率,當mode=1表示設定的分辨率為1mm,當mode=2表示設定的分辨率為0.1mm
int Measuring_Power(int fd, int on_off);//設定上電即測,on_off=1表示開啟該功能,on_off=0表示關閉該功能
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, B38400, B19200, B9600, B4800, B2400, B1200, B300};
int name_arr[]={115200, 38400, 19200, 9600, 4800, 2400, 1200, 300, 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);//設置9600bps波特率
        }else
    {
                printf("Can't Open Serial Port!/n");
                exit(0);
        }

    if(Set_Parity(fd, 8, 1, 'S') == FALSE)//調用設置8位數據位,1位停止位及無校驗位
    {
                printf("Set Parityu 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, RANGE_80);

    sleep(5);
    Read_Parameter(fd, Buff_data_device);
    Set_Address(fd);
    Distance_Modification(fd, DISTANCE_IN, 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;
        }else
                return fd;
}

//設置波特率
int set_speed(int fd, int speed, struct termios* newtio)
{
        int i;
        int status;
        struct termios* Opt = newtio;
        tcgetattr(fd, Opt);
        for(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;
}

//設置fd的數據位、停止位、奇偶檢驗位
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;
        }
        //對options的起始地址開始的termios結構體內存置零
        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); /*Input*/
        options.c_oflag &= ~OPOST;
        }
        //有字符處理或經過TIME個0.1秒後返回       
        options.c_cc[VTIME] = 0;
        options.c_cc[VMIN] = 0;
        //如果發生數據溢出,接收數據,但是不再讀取
        tcflush(fd, TCIFLUSH);
        //激活配置 (將修改後的termios數據設置到串口中)
        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 m_fd = fd;
    int write_count = 0;
        int nwrite = 0;

    if(m_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 Datda Fail!\n");
                        break;
                }
        write_count += nwrite;
        len -= nwrite;
        }

    // 清除所有正在發生的I/O數據
        tcflush(fd, TCIOFLUSH);
        return write_count;
}

//讀取數據
int Read_Data(int fd, char* buff)
{
    int nread = 0;
    int fd_max;
    int nselect;

    fd_set readfds;
        FD_ZERO(&readfds);
        FD_SET(fd,&readfds);
        fd_max = fd+1;

        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';
        }

    int j = 0;
    while(buff[j] != '\0')
    {
        printf("the readable data is 0x%x\n", buff[j]);

        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個字節,而讀取機器號的返回代碼有20個字節,所以讀取三次數據
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;
}

//距離修改,參數decrease_or_increase表示修正可選為取負或者取正,參數distance表示要修正的距離
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;
            Buff_Distance_Mo[6] = '\0';
    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;
}

//連續測量時設置數據返回時間間隔,參數interval_time_int表示要設定的時間間隔為interval_time_int秒
int Mea_Interval(int fd, int interval_time_int)
{
    int c_s = -250 - 4 - 5 - interval_time_int;//十進制250表示十六進制0xFA
        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;
            Buff_Mea_Interval[5] = '\0';
    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;
}

//設置距離起止點,參數position_int的值(1頂端算起;0加上模塊長度+上面的距離修正)
int Distance_StartStop(int fd, int position_int)
{
    int c_s = -250 - 4 - 8 - position_int;//十進制250表示十六進制0xFA
        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;
                Buff_StartStop[5] = '\0';
        un_char Mea_Distance_StartStopSd[BUFF_MAXSIZE] = {0xFA, 0x04, 0x88, 0x7A};
        un_char Mea_Distance_StartStopFd[BUFF_MAXSIZE] = {0xFA, 0x84, 0x88, 0x01, 0xF9};

    //要寫的數據中間有0x00,因此把要的數據長度指定為5個字節,而不用strlen()函數計算長度
    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;
}

//設定量程,range表示要設定的量程大小05, 10, 30, 50, 80
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};   

    int choose = range;
    switch(choose)
    {
        case 5:
                Write_Data(fd, Buff_Range_05, strlen(Buff_Range_05));
                Read_Data(fd, Buff_Range_05);

            if(strcmp(Buff_Range_05, Set_MeasuringRangeSd) == 0)
                {
                        printf("Set_MeasuringRange_05_Succeeded\n");
                }else if(strcmp(Buff_Range_05, Set_MeasuringRangeFd) == 0)
                {   
                        printf("Set_MeasuringRange_05_Failed, Please Try Again!\n");
                }else
                {
                printf("NG\n"); 
                        return FALSE;
                }
            break;
        case 10:
                        Write_Data(fd, Buff_Range_10, strlen(Buff_Range_10));
                        Read_Data(fd, Buff_Range_10);

                        if(strcmp(Buff_Range_10, Set_MeasuringRangeSd) == 0)
                        {
                                printf("Set_MeasuringRange_10_Succeeded\n");
                        }else if(strcmp(Buff_Range_10, Set_MeasuringRangeFd) == 0)
                        {
                                printf("Set_MeasuringRange_10_Failed, Please Try Again!\n");
                        }else   
                        {
                                printf("NG\n");
                                return FALSE;
                        }
                        break;
        case 30:
                        Write_Data(fd, Buff_Range_30, strlen(Buff_Range_30));
                        Read_Data(fd, Buff_Range_30);

                        if(strcmp(Buff_Range_30, Set_MeasuringRangeSd) == 0)
                        {
                                printf("Set_MeasuringRange_30_Succeeded\n");
                        }else if(strcmp(Buff_Range_30, Set_MeasuringRangeFd) == 0)
                        {
                                printf("Set_MeasuringRange_30_Failed, Please Try Again!\n");
                        }else   
                        {
                                printf("NG\n");
                                return FALSE;
                        }
                        break;
        case 50:
                        Write_Data(fd, Buff_Range_50, strlen(Buff_Range_50));
                        Read_Data(fd, Buff_Range_50);

                        if(strcmp(Buff_Range_50, Set_MeasuringRangeSd) == 0)
                        {
                                printf("Set_MeasuringRange_50_Succeeded\n");
                        }else if(strcmp(Buff_Range_50, Set_MeasuringRangeFd) == 0)
                        {
                                printf("Set_MeasuringRange_50_Failed, Please Try Again!\n");
                        }else   
                        {
                                printf("NG\n");
                                return FALSE;
                        }
                        break;
        case 80:
                        Write_Data(fd, Buff_Range_80, strlen(Buff_Range_80));
                        Read_Data(fd, Buff_Range_80);

                        if(strcmp(Buff_Range_80, Set_MeasuringRangeSd) == 0)
                        {
                                printf("Set_MeasuringRange_80_Succeeded\n");
                        }else if(strcmp(Buff_Range_80, Set_MeasuringRangeFd) == 0)
                        {
                                printf("Set_MeasuringRange_80_Failed, Please Try Again!\n");
                        }else   
                        {
                                printf("NG\n");
                                return FALSE;
                        }
                        break;
        default:
            printf("Please Set The Correct Range Parameters!\n");
            return FALSE;
    }
        return TRUE;
}

//設定頻率,freg表示要設定的頻率大小,00,05,10,20
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 choose = freg;
    switch(choose)
    {
        case 0:
                        Write_Data(fd, Buff_Frequency_00, 5);//要寫的數據中間有0x00,因此把要的數據長度指定為5個字節,而不用strlen()函數計算長度
                        Read_Data(fd, Buff_Frequency_00);

                        if(strcmp(Buff_Frequency_00, Set_FrequencySd) == 0)
                        {
                                printf("Set_Frequency_00_Succeeded\n");
                        }else if(strcmp(Buff_Frequency_00, Set_FrequencyFd) == 0)
                        {
                                printf("Set_Frequency_00_Failed, Please Try Again!\n");
                        }else
                        {
                                printf("NG\n");
                                return FALSE;
                        }
                        break;

        case 5:
            Write_Data(fd, Buff_Frequency_05, strlen(Buff_Frequency_05));
                Read_Data(fd, Buff_Frequency_05);

                if(strcmp(Buff_Frequency_05, Set_FrequencySd) == 0)
                {
                        printf("Set_Frequency_05_Succeeded\n");
                }else if(strcmp(Buff_Frequency_05, Set_FrequencyFd) == 0)
                {
                        printf("Set_Frequency_05_Failed, Please Try Again!\n");
                }else
                {
                        printf("NG\n");
                        return FALSE;
                }
            break;
        case 10:
                        Write_Data(fd, Buff_Frequency_10, strlen(Buff_Frequency_10));
                        Read_Data(fd, Buff_Frequency_10);

                        if(strcmp(Buff_Frequency_10, Set_FrequencySd) == 0)
                        {
                                printf("Set_Frequency_10_Succeeded\n");
                        }else if(strcmp(Buff_Frequency_10, Set_FrequencyFd) == 0)
                        {
                                printf("Set_Frequency_10_Failed, Please Try Again!\n");
                        }else
                        {
                                printf("NG\n");
                                return FALSE;
                        }
            break;
        case 20:
                        Write_Data(fd, Buff_Frequency_20, strlen(Buff_Frequency_20));
                        Read_Data(fd, Buff_Frequency_20);

                        if(strcmp(Buff_Frequency_20, Set_FrequencySd) == 0)
                        {
                                printf("Set_Frequency_20_Succeeded\n");
                        }else if(strcmp(Buff_Frequency_20, Set_FrequencyFd) == 0)
                        {
                                printf("Set_Frequency_20_Failed, Please Try Again!\n");
                        }else
                        {
                                printf("NG\n");
                                return FALSE;
                        }
            break;
        default:
            printf("Please Set The Correct Frequency Parameters!\n");
            return FALSE;
    }
     return TRUE;
}

//設定分辨率,當mode=1表示設定的分辨率為1mm,當mode=2表示設定的分辨率為0.1mm;ZPOne為Zero_Point_One
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};

    int choose = mode;
    //設定分辨率為1mm或者0.1mm
        switch(choose)
        {
                case 1:
                        Write_Data(fd, Buff_Resolution_One, strlen(Buff_Resolution_One));
                        Read_Data(fd, Buff_Resolution_One);

                        if(strcmp(Buff_Resolution_One, Set_ResolutionSd) == 0)
                        {
                                printf("Set_One_mm_Resolution_Succeeded\n");
                        }else if(strcmp(Buff_Resolution_One, Set_ResolutionFd) == 0)
                        {
                                printf("Set_One_mm_Resolution_Failed, Please Try Again!\n");
                        }else
                        {
                printf("NG\n"); 
                                return FALSE;
                        }
                        break;
                case 2:
                        Write_Data(fd, Buff_Resolution_ZPOne, strlen(Buff_Resolution_ZPOne));
                        Read_Data(fd, Buff_Resolution_ZPOne);

                        if(strcmp(Buff_Resolution_ZPOne, Set_ResolutionSd) == 0)
                        {
                                printf("Set_ZPOne_mm_Resolution_Succeeded\n");
                        }else if(strcmp(Buff_Resolution_ZPOne, Set_ResolutionFd) == 0)
                        {
                                printf("Set_ZPOne_mm_Resolution_Failed, Please Try Again!\n");
                        }else
                        {
                printf("NG\n"); 
                                return FALSE;
                        }
                        break;
                default:
                        printf("Please Set The Correct Resolution Parameters!\n");
                        return FALSE;
        }
        return TRUE;
}

//設定上電即測,on_off=1表示開啟該功能,on_off=0表示關閉該功能
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};

    int choose = on_off;
    //選擇是否開啟上電即測
    switch(choose)
    {
          case 0:
                        Write_Data(fd, Buff_Measuring_Off, 5);//要寫的數據中間有0x00,因此把要的數據長度指定為5個字節,而不用strlen()函數計算長度
                        Read_Data(fd, Buff_Measuring_Off);
                        if(strcmp(Buff_Measuring_Off, Measuring_PowerSd) == 0)
                        {
                                printf("Measuring_Power_Off_Succeeded\n");
                        }else if(strcmp(Buff_Measuring_Off, Measuring_PowerFd) == 0)
                        {
                                printf("Measuring_Power_Off_Failed, Please Try Again!\n");
                        }else
                        {
                                printf("NG\n");
                                return FALSE;
                        }
                        break;
        case 1:
            Write_Data(fd, Buff_Measuring_On, strlen(Buff_Measuring_On));
                    Read_Data(fd, Buff_Measuring_On);

                if(strcmp(Buff_Measuring_On, Measuring_PowerSd) == 0)
                {
                            printf("Measuring_Power_On_Succeeded\n");
                }else if(strcmp(Buff_Measuring_On, Measuring_PowerFd) == 0)
                {
                        printf("Measuring_Power_On_Failed, Please Try Again!\n");
                }else
                {
                printf("NG\n"); 
                        return FALSE;
                }
            break;
        default:
            printf("Please Set The Correct On_Off Mode Parameters!\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(48~63), 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);

    //根據返回數據的位數及字符數組的的第四位數據(數組下標為[3])的值,3X的取值只能是0x30~0x3F(48~63), E(或者e)的大小為69(或者101),判斷模塊是否正確返回
    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);

    //根據返回數據的位數及字符數組的的第四位數據(數組下標為[3])的值,3X的取值只能是0x30~0x3F(48~63), E(或者e)的大小為69(或者101),判斷模塊是否正確返回
        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;
}
2.4 源碼說明

①對於阻塞式讀取模塊返回的數據,當用串口發送指令訪問模塊時,模塊不能及時得返回數據,如果采用非阻塞式讀取數據,不一定會成功;

②串口一次只能讀取8位數據,用串口讀取多於8位的數據,多讀幾次就OK。

[code]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);
}

在多次讀取數據時需注意,例如,

[code]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);
從Buff_Continuous_Measurement緩存讀取數據,為什麼不用strcpy函數,而采用memcpy函數;memcpy函數與strcpy函數的區別在於,前者復制內存裡的數據時結尾不會添加“\0”,而strcpy函數會自動添加;所以如果采用strcpy函數來讀取數據,兩次讀取的數據結尾都會有一個“\0“,即整個數據中間多了一個“\0”,(我記得我當時用stcpy()函數是失敗的)~

③對數據不存在非零情況,寫的數據用strlen()函數;對於寫數據中間有0x00(零)的情況時,直接采用指定的字節數讀寫,例如BBuff_Measuring_Off[BUFF_MAXSIZE] = {0xFA, 0x04, 0x0D, 0x00, 0xF5}; 寫數據時指定5個字節Write_Data(fd, Buff_Measuring_Off, 5); ④對於通信成功,但恰遇到模塊總返回操作失敗的代碼的問題,這個問題弄得我哭笑不得,時好時壞(某天操作一直成功,過幾天操作一直失敗),最後是因為模塊的供電電壓問題,這個就屬於硬件問題了,只是告訴大家以後遇到這個問題該怎麼去處理。

Copyright © Linux教程網 All Rights Reserved