2014-12-27 25 views
1

在一個基於unix的軟件上,它必須發送一個介於0到179之間的數字給arduino,並且arduino會將該數字作爲一個角度應用於伺服電機,但我不知道參數是什麼必須在terminos結構中更改以允許串行通信。struct termios設置與arduino的串行通信

這是C++代碼:

#include <iostream> 
#include <unistd.h> 
#include <fstream> 
#include <termios.h> 

using namespace std; 

int main() 
{ 
    unsigned int angle; 
    ofstream arduino; 
    struct termios ttable; 

    //cout<<"test-1"; 

    arduino.open("/dev/tty.usbmodem3a21"); 

    //cout<<"test-2"; 

    if(!arduino) 
    { 
     cout<<"\n\nERR: could not open port\n\n"; 
    } 
    else 
    { 

     if(tcgetattr(arduino,&ttable)<0) 
     { 
      cout<<"\n\nERR: could not get terminal options\n\n"; 
     } 
     else 
     { 

      //there goes the terminal options setting for the output; 

      ttable.c_cflag = -hupcl //to prevent the reset of arduino 

      cfsetospeed(&ttable,9600); 

      if(tcsetattr(arduino,TCSANOW,&ttable)<0) 
      { 
       cout<<"\n\nERR: could not set new terminal options\n\n"; 
      } 
      else 
      { 
       do 
       { 
        cout<<"\n\ninsert a number between 0 and 179"; 
        cin>>angle; 
        arduino<<angle; 
       }while(angle<=179); 

       arduino.close(); 
      } 
     } 
    } 

} 

,這是Arduino的公司:

#include <Servo.h> 

Servo servo; 
const int pinServo = 2; 
unsigned int angle; 

void setup() 
{ 
    Serial.begin(9600); 
    servo.attach(pinServo); 

    servo.write(0); 

} 

void loop() 
{ 
    if(Serial.available()>0) 
    { 
     angle = Serial.read(); 

     if(angle <= 179) 
     { 
     servo.write(angle); 
     } 
    } 
} 

所以就請你告訴我我有什麼改變 「的TTable」?

回答

0

一些東西一樣,對termios的是最好的選擇

options.c_cflag &= ~CRTSCTS;  
options.c_cflag |= (CLOCAL | CREAD);     
options.c_iflag |= (IGNPAR | IGNCR);     
options.c_iflag &= ~(IXON | IXOFF | IXANY);   
options.c_oflag &= ~OPOST; 

options.c_cflag &= ~CSIZE;    
options.c_cflag |= CS8;    
options.c_cflag &= ~PARENB;   
options.c_iflag &= ~INPCK;   
options.c_iflag &= ~(ICRNL|IGNCR); 
options.c_cflag &= ~CSTOPB;  
options.c_iflag |= INPCK;  
options.c_cc[VTIME] = 0.001; // 1s=10 0.1s=1 * 
options.c_cc[VMIN] = 0;