sábado, 20 de agosto de 2011

Como hacer comunicacion serial: Ubuntu-Arduino

Progrma para hacer comunicacion serial entre Ubuntu y arduino, proramado en C++ con CodeBlocks IDE:


Porgrama CodeBlocks:


#include <stdio.h> // standard input / output functions
#include <string.h> // string function definitions
#include <unistd.h> // UNIX standard function definitions
#include <fcntl.h> // File control definitions
#include <errno.h> // Error number definitions
#include <termios.h> // POSIX terminal control definitionss
#include <time.h>   // time calls
#include <sys/signal.h>
#include <sys/types.h>
//#include <cv.h>


    char buf[255];
    int res;
    int open_port(void);
    int configure_port(int fd);
    int query_modem(int fd);


int main(void)
{
    int fd = open_port();
    configure_port(fd);
    while(true){
        query_modem(fd);
    }
    return(0);
}



int open_port(void)
{
    int fd; // file description for the serial port

    fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);

    if(fd == -1) // if open is unsucessful
    {
        perror("open_port: Unable to open /dev/ttyS0 - ");
    }
    else
    {
        fcntl(fd, F_SETFL, 0);
    }

    return(fd);
}

int configure_port(int fd)      // configure the port
{
    struct termios port_settings;      // structure to store the port settings in

    cfsetispeed(&port_settings, B9600);    // set baud rates
    cfsetospeed(&port_settings, B9600);

    port_settings.c_cflag &= ~PARENB;    // set no parity, stop bits, data bits
    port_settings.c_cflag &= ~CSTOPB;
    port_settings.c_cflag &= ~CSIZE;
    port_settings.c_cflag |= CS8;

    tcsetattr(fd, TCSANOW, &port_settings);    // apply the settings to the port
    return(fd);

}

int query_modem(int fd)   // query modem with an AT command
{
    int n;
    fd_set rdfs;
    struct timeval timeout;

    // initialise the timeout structure
    timeout.tv_sec = 10; // ten second timeout
    timeout.tv_usec = 0;

    write(fd, "1", 3);  // send an AT command followed by a CR

    res = read(fd,buf,255);
    buf[res]=0;
    printf("%s", buf, res);

    // do the select
    //n = select(fd + 1, &rdfs, NULL, NULL, &timeout);

    // check if an error has occured
    /*if(n < 0)
    {
        perror("select failed\n");
    }
    else if (n == 0)
    {
        puts("Timeout!");
    }
    else
    {
        printf("\nBytes detected on the port!\n");
    }
    */
}


Programa Arduino:



void setup(){
 Serial.begin(9600) ;
 
}

void loop(){
 
 word Adc = analogRead(0);
 delay(5);
 Serial.println(Adc);
 if(Serial.available()){
   int Rd = Serial.read();
   if(Rd==49){
     digitalWrite(13,HIGH);
     Serial.print("dato:" );
     Serial.println(Rd);
   }
 }

 delay(200);
}

No hay comentarios:

Publicar un comentario