Subversion Repositories Projects

Rev

Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

/*      This file is part of MoteCtrl
        http://www.mikrokopter.de/ucwiki/en/MoteCtrl
*/


//Include header files, which provide resources, pc_serial_port.c needs:
#include <windows.h>    //Windows API, to interface with the serial port
#include <stdio.h>              //Standard I/O (printf for instance)

#include "pc_serial_port.h"


/*
Compiler & Linker Porperties:
Set "Character Set"-CompilerFlag to "Not Set" or "Multi Byte Character Set" to
avoid Errors about Windows API functions that can handle Unicode paramters.
In Visual Studio: Properties of Project -> Configuration Properties -> General
*/



HANDLE hCom;    //Handle, which contains inf about the opened Device File
                                //(the opened COM-Port, returned by CreateFile function)

//Initialize & Configure COMx-Port
//return value: EXIT_FAILURE=1, EXIT_SUCCESS=0 (stdlib macros)
int init_com_port(int comNumber) {
       
        DCB dcb;                //Device Control Block, contains Configuration for COM-Port
        char comPort[5] = {'C','O','M'}; //Number and String Terminator to be added
        int fSuccess;   //Stores inf about file-actions (action succeeded or failed)
        COMMTIMEOUTS timeouts;  //Struct, which stores inf about the timeout
                                                        //behaviour of the COM-Port

        //Get the Com-Port Number:
        comPort[3] = 48 + comNumber;    //COMx (x is ASCII coded)
        comPort[4] = 0;                                 //add string Terminator 'NUL'

        //Create Device File, initialize serial Port:
        hCom = CreateFile( comPort,     //open COMx Device (pointer to comPort-String)
                                        GENERIC_READ | GENERIC_WRITE,   //write/read permisions
                                        0,    // must be opened with exclusive-access
                                        NULL, // default security
                                        OPEN_EXISTING, // must use OPEN_EXISTING
                                        0,    // no overlapping
                                        NULL  // hTemplate must be NULL for comm devices
                                        );

        //Check, if CreateFile succeeded:
        if (hCom == INVALID_HANDLE_VALUE) {
                printf ("***ERR: CreateFile failed with error %d.\n", GetLastError());
                return EXIT_FAILURE;
        }

        //Get the currently active Device Control Block (DCB) for the COMx:
        SecureZeroMemory(&dcb, sizeof(DCB)); //initialize entire dcb-struct with zeros
        dcb.DCBlength = sizeof(DCB);                   
        fSuccess = GetCommState(hCom, &dcb); //write the current configuration to
                                                                                 //our dcb-struct

        //GetCommState returns 0, if error occured while getting the DCB
        if (!fSuccess) {
                printf ("***ERR: GetCommState failed with error %d.\n", GetLastError());
                return EXIT_FAILURE;
        }

        /*Change the values of the obtained dcb-struct to match the config of the
         *Mikrokopter. Currently the FlightControl communicates at:
         *57600 Baud (bps), 8 Data bits, no parity bit, 1 stop bit */


        dcb.BaudRate = CBR_57600;     // Set Baudrate
        dcb.ByteSize = 8;             // data size, transmit and receive
        dcb.Parity = NOPARITY;        // no parity bit
        dcb.StopBits = ONESTOPBIT;    // one stop bit
       
        //Send reconfigured dcb back to COMx Device-File:
        fSuccess = SetCommState(hCom, &dcb);
       
        //SetCommState returns a 0, if error occured while setting the DCB for COMx
        if (!fSuccess) {
                printf ("***ERR: SetCommState failed with error %d.\n", GetLastError());
      return EXIT_FAILURE;
        }

        //Configure the Read-Timeout behaviour of the initialized COMx-Port:

        /* The following Read-Timeout config determines the behaviour of the
        ReadFile cmd (applied to the initialized COMx-Port):
        If a Byte is in the Hardware UART-Buffer of the initialized COM-Port and
        the ReadFile function is called, this byte is read. If theres no byte in
        the UART-InputBuffer and the ReadFile function is called, the ReadFile
        function will return *immediatly* (BytesRead parameter is zero then).
        */

        timeouts.ReadIntervalTimeout            = MAXDWORD;
        timeouts.ReadTotalTimeoutMultiplier = 0;
        timeouts.ReadTotalTimeoutConstant       = 0;
       
        //Send the Timeout-Config to the COM-Port:
        fSuccess = SetCommTimeouts (hCom, &timeouts);
       
        //Check, if setting the timeout-settings was successfull:
        if(!fSuccess) {
                printf("***ERR: SetCommTimeouts failed with error %d.\n", GetLastError());
                return EXIT_FAILURE;
        }


        //Initialization & Configuration of COMx done!
        return EXIT_SUCCESS;
}


//Function which reads 1 Byte of the Rx-Buffer of the initialized COM-Port:
//Return value: Number of the bytes read (should be 0 or 1)
int getCharFromCom (char* inputBuffer) {

        int numOfBytesRead;
        ReadFile (hCom, inputBuffer, 1, &numOfBytesRead, NULL);
        //read char is stored in the passed char-buffer

        return numOfBytesRead;
       
}


//Function which writes [length] Byte to the Tx-Buffer of the initialized COM-Port:
//Returns something>0 if write failed, 0 if successfull
int sendStringToCom (char* toSend, int length) {
       
        int numOfBytesWritten;

        //write char to which the passed char-pointer points to
        return WriteFile (hCom, toSend, length, &numOfBytesWritten, NULL);
}