-2

I am trying to make RS-232 communication between the PC and the PC MCU PIC. So I started making the PC program first in C++, and it was errorless, and according to the cout I made to output the status it should be working, but I wanted to be sure. So I downloaded Hyperterminal and connected Tx to Rx pin in serial com port, but whenever I try to connect the hyperterminal it gives an error, saying access denied (error 5) when I try to run my C++ program. I don't understand where the problem really is. Here's the full code, if the problem was the code's, just to make sure:

main.c:

        #include <windows.h>
        #include <winbase.h>
        #include <iostream>

        PDWORD sent;
        char buf;

        int main(){

        DCB serial;

        HANDLE hserial = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

        serial.DCBlength = sizeof(DCB);
        serial.BaudRate = CBR_9600;
        serial.fBinary = true;
        serial.fParity = false;
        serial.ByteSize = 8;
        serial.Parity = NOPARITY;
        serial.StopBits =  ONESTOPBIT;

        char result = BuildCommDCB("baud=9600 parity=N data=8 stop=1", &serial);

        if(result != 0){
            std::cout << "DCB Structure Successfully Created!" << std::endl;
        }else{
            std::cout << "DCB Structure Creation Failed!" << std::endl;
        }

        if(hserial != INVALID_HANDLE_VALUE){
            std::cout << "COM Port Handle Successfully Created!" << std::endl;

        }else{
            std::cout << "COM Port Handle Creation Failed!" << std::endl;
            std::cout << GetLastError() << std::endl;
        }

        char res = WriteFile(hserial, "0xFF", 1, sent, NULL);

        if(res != 0){
            std::cout << "Writing to COM Port Successfull!" << std::endl;
        }else{
            std::cout << "Writing to COM Port Failed!" << std::endl;
            std::cout << GetLastError() << std::endl;
        }

        CloseHandle(&hserial);

        return 0;

        }
user207421
  • 305,947
  • 44
  • 307
  • 483
user3674628
  • 29
  • 12

1 Answers1

0

Only one program at a time can open a particular COM port. You can do your test if you have two COM ports available.

ScottMcP-MVP
  • 10,337
  • 2
  • 15
  • 15