New function SetSerialPortBaudRate() for SerialPort

Got an idea for enhancing PureBasic? New command(s) you'd like to see?
User_Russian
Addict
Addict
Posts: 1520
Joined: Wed Nov 12, 2008 5:01 pm
Location: Russia

New function SetSerialPortBaudRate() for SerialPort

Post by User_Russian »

I propose to add a new function SetSerialPortBaudRate(), sets the speed serial port.
Here is a prototype for Windows and Linux.

Code: Select all

CompilerIf #PB_Compiler_OS = #PB_OS_Linux
  #NCCS = 32
  #TCSANOW = 0
  
  Structure termios Align #PB_Structure_AlignC
    c_iflag.l     ; .l because .i changes size with the x64 version
    c_oflag.l
    c_cflag.l
    c_lflag.l
    c_line.a
    c_cc.a[#NCCS]
    c_ispeed.l
    c_ospeed.l
  EndStructure
CompilerEndIf

Procedure SetSerialPortBaudRate(Port, Rate)
  Protected Result=#False, PortID

  If IsSerialPort(Port)
    
    PortID = SerialPortID(Port)
    
    CompilerIf #PB_Compiler_OS = #PB_OS_Windows
      
      Protected dcb.DCB
      If PortID
        If GetCommState_(PortID, @dcb)  
          dcb\BaudRate  = Rate ; Требуемая скорость.
          If SetCommState_(PortID, @dcb)
            Result = #True
          EndIf
        EndIf
      EndIf
      
    CompilerElse
      
      Protected options.termios, Sp
      
      If Rate=9600 Or Rate=115200
        
        Select Rate
          Case 9600   : Sp = 13
          Case 115200 : Sp = 4098
        EndSelect
        
        If tcgetattr_(PortID, @options) = 0   ; читает параметры порта.
          If cfsetispeed_(@options, Sp) = 0 ; установка скорости порта.
            If cfsetospeed_(@options, Sp) = 0 ; установка скорости порта.
              If tcsetattr_(PortID, #TCSANOW, @options) = 0 ; Записывает параметры порта.
                Result=#True
              EndIf
            EndIf
          EndIf
        EndIf
        
      EndIf
      
    CompilerEndIf
    
    If Result=#False : tLastErr=#DS_Err_BaudRate : EndIf
  EndIf
    
  ProcedureReturn Result
EndProcedure
Also suggest adding a flag #PB_SerialPort_DtrHandshake, which is similar to the flag #PB_SerialPort_RtsCtsHandshake, but DTR is set to 1