今回RS485通信の受信プログラムを書いたのですが,
出力する際に―1以下の値がすべて0で扱われてしまいます.
原因がいまいち不明なのでご指導お願いします.
以下にソースコードを示します.
VC++2013を使用しています.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <windows.h>
int main(void) {
HANDLE hComm; /*シリアルポートのハンドル*/
int i = 0;
char sBuf[1];
char str[1000]; /*i=1000までの値を取得*/
unsigned long nn;
unsigned int len;
DCB dcb; /*DCB:プログラム側で通信パラメータを決める*/
COMMTIMEOUTS cto; /*cto = CommTimeOuts*/
hComm = CreateFile("COM3", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
if (hComm == INVALID_HANDLE_VALUE) {
printf("Open Error!\n");
exit(1);
}
GetCommState(hComm, &dcb); /*シリアルポートの状態を取得*/
dcb.BaudRate = 38400; /*通信速度*/
SetCommState(hComm, &dcb); /*シリアルポートの状態を設定*/
GetCommTimeouts(hComm, &cto);
cto.ReadIntervalTimeout = 0;
cto.ReadTotalTimeoutMultiplier = 0;
cto.ReadTotalTimeoutConstant = 0;
cto.WriteTotalTimeoutMultiplier = 0;
cto.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(hComm, &cto);
FILE *outputfile; /*FILEポインタ*/
outputfile = fopen("56bit.txt", "w"); /*56bit.txtを書き込み(ファイルがなければ自動で作成)*/
if (outputfile == NULL) { /*オープン処理&エラー対応*/
printf("cannot open\n");
exit(1);
}
while (1) {
len = ReadFile(hComm, sBuf, 1, &nn, 0);
if (len == 0) {
continue;
}
if (len < 0) {
printf("ERROR---\n");
exit(2);
}
for (i = 0; i < len; i++) {
str[i] = sBuf[0];
printf("%d\n", str[i]);
fprintf(outputfile, "%d\n", str[i]);
}
}
fclose(outputfile);
CloseHandle(hComm);
return 0;
}