我有脉搏光度计,我想从串口读取数据。这项任务并不容易,因为我需要设置一些通信参数。我设置了波特率,但这还不够。我需要从此页面设置参数:https://www.tranzoa.net/~alex/blog/images/Communication%20protocol.pdf。 如何在C中设置这些参数?这个问题在python中实现:https://github.com/atbrask/CMS50Dplus。我需要用C / C ++。我提到我需要它用于Linux。 现在我有一个简单的C ++程序,可以从串口读取普通数据:
#include <cstdlib>
#include <iostream>
#include <cstdio>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <pthread.h>
#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <math.h>
#include <cstdio>
#include <cstdlib>
using namespace std;
char Buffer[100];
int Port_ID;
int Available() {
int n = 0;
int m;
if ((m = ioctl(Port_ID, FIONREAD, &n)) < 0) {
cout << "ioctl failed with " << m << "\r\n";
return -1;
}
cout << "ioctl read " << n << "\r\n";
return n;
}
void Receive(){
char chr;
int i = 0;
memset(Buffer, '\0', strlen(Buffer));
while (Available() > 0){
read(Port_ID, &chr, sizeof(chr));
Buffer[i++] = chr;
cout << chr;
}
}
int InitSerialPort(string portname) {
cout << "I'm serial comm!\r" << endl;
Port_ID = open(portname.c_str(), O_RDWR | O_NOCTTY);
printf("Open() PortID! %s Port ID %d\r\n", strerror(errno), Port_ID);
return Port_ID;
}
int main(int argc, char** argv) {
memset(Buffer, '\0', strlen(Buffer));
int i=1, n;
char message[50];
Port_ID = InitSerialPort("/dev/ttyPS1");
while(i++){
Receive();
if(strlen(Buffer) > 0){
cout << Buffer;
memset(Buffer, '\0', strlen(Buffer));
}
}
return 0;
}