題名に書いた通りですが、シリアル通信でC言語でセンサーからの出力値を得たいです。
まずarduino側のコードを載せます。
arduino
1#define FPS 20 2unsigned long pulseWidth; 3unsigned long time0; 4int T = 1000 / FPS; 5int i = 0; 6void setup() 7{ 8 Serial.begin(9600); // Start serial communications 9 10 pinMode(2, OUTPUT); // Set pin 2 as trigger pin 11 digitalWrite(2, LOW); // Set trigger LOW for continuous read 12 13 pinMode(3, INPUT); // Set pin 3 as monitor pin 14} 15 16void loop(){ 17 time0 = millis(); 18 19 pulseWidth = pulseIn(3, HIGH); // Count how long the pulse is high in microseconds 20 // If we get a reading that isn't zero, let's print it 21 if(pulseWidth != 0){ 22 pulseWidth = pulseWidth / 10; // 10usec = 1 cm of distance 23 Serial.print(pulseWidth); // Print the distance 24 } 25 26 while((millis() - time0) < T){ 27 } 28}
この出力値をC/C++言語で読み取りたいのですが、下記のコードでは問題がありました。
c
1#include <stdio.h> 2#include <sys/types.h> 3#include <sys/stat.h> 4#include <sys/ioctl.h> 5#include <fcntl.h> 6#include <termios.h> 7#include <unistd.h> 8 9#define SERIAL_PORT "/dev/cu.usbmodem1411" 10 11int main(int argc, char *argv[]) 12{ 13 unsigned char msg[] = "serial port open...\n"; 14 unsigned char buf[255]; // バッファ 15 int fd; // ファイルディスクリプタ 16 struct termios tio; // シリアル通信設定 17 int baudRate = B9600; 18 int i; 19 int len; 20 int ret; 21 int size; 22 23 fd = open(SERIAL_PORT, O_RDWR); // デバイスをオープンする 24 if (fd < 0) { 25 printf("open error\n"); 26 return -1; 27 } 28 29 tio.c_cflag += CREAD; // 受信有効 30 tio.c_cflag += CLOCAL; // ローカルライン(モデム制御なし) 31 tio.c_cflag += CS8; // データビット:8bit 32 tio.c_cflag += 0; // ストップビット:1bit 33 tio.c_cflag += 0; // パリティ:None 34 35 cfsetispeed( &tio, baudRate ); 36 cfsetospeed( &tio, baudRate ); 37 38 cfmakeraw(&tio); // RAWモード 39 40 tcsetattr( fd, TCSANOW, &tio ); // デバイスに設定を行う 41 42 ioctl(fd, TCSETS, &tio); // ポートの設定を有効にする 43 44 // 送受信処理ループ 45 while(1) { 46 len = read(fd, buf, sizeof(buf)); 47 if (0 < len) { 48 for(i = 0; i < len; i++) { 49 printf("%02X", buf[i]); 50 } 51 printf("\n"); 52 } 53 54 // エコーバック 55 write(fd, buf, len); 56 } 57 58 close(fd); // デバイスのクローズ 59 return 0; 60}
このURLから引っ張ってきたコードですが、これではlenの値が正しく反映されません(正しい行数が出てこない)。また出力を10進数で出したいです。
かなり丸投げな質問ですが、よろしくお願いいたします。
ちなみに出力したらこんな感じに出てきます。
・出力例
313432
31
3436
31
3439
3134
・本来出て欲しい出力
143
143
142
141
143
142
環境
xcode 9.1
Arduino uno

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/11/08 05:58
2017/11/08 06:18