Форум программистов, компьютерный форум, киберфорум
C++ Builder
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.84/45: Рейтинг темы: голосов - 45, средняя оценка - 4.84
D'Kard Kain

Работа с COM портом и вообще...

02.02.2009, 21:01. Показов 9156. Ответов 5
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Друзья спасайте!

Для обмена необходимо выдать сигналы DTR = 1(+) и RTS = 0(-).

Как это сделать? Я знаю регистры в которые нужно подлезть но под виндоус ХП обращаться к регистрам напрямую нельзя, а как сделать это иначе на Билдере я не знаю

И второй вопрос: как сделать так что бы программа после компиляции запускалась на всех компьютерах, а не только на тех где есть билдер..
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
02.02.2009, 21:01
Ответы с готовыми решениями:

Работа с Com портом
Привет всем! У меня собственно такая ситуация, есть bluetooth и телефон Nokia устанавливаю соединение через виртуальный com порт, мне...

Работа с COM-портом
Подскажите, какие компоненты нужны для работы с ком-портами? а именно (хотя бы для начала) отправка шестнадцатиричного кода на порт, к...

Работа с COM портом
Здравствуйте! В процессе написания программы работы с устройством, подключенным к ПК через преобразователь интерфейсов RS485 - USB,...

5
Эксперт С++
 Аватар для XuTPbIu_MuHTAu
2256 / 771 / 25
Регистрация: 27.05.2008
Сообщений: 1,496
02.02.2009, 21:11
GetCommState, SetCommState,EscapeCommFunction, CreateFile,WriteFile,ReadFile - Все это средства винапи,которые можно использовать для работы с ком портом. Я билдером не -увлекаюсь-, так что про его средства ничего сказать не могу. Описание функций,параметров и использования есть в MSDN.Первые три нужны непосредственно для сигналов DTR &RTS
0
D'Kard Kain
02.02.2009, 23:30
Цитата Сообщение от XuTPbIu_MuHTAu Посмотреть сообщение
GetCommState, SetCommState,EscapeCommFunction, CreateFile,WriteFile,ReadFile - Все это средства винапи,которые можно использовать для работы с ком портом.
Вот после безуспешных попыток найти эти параметры в структуре с которой общаются эти функции я на форум ваш и пришел.

Цитата Сообщение от XuTPbIu_MuHTAu Посмотреть сообщение
Я билдером не -увлекаюсь-, так что про его средства ничего сказать не могу. Описание функций,параметров и использования есть в MSDN.Первые три нужны непосредственно для сигналов DTR &RTS
Поясните пожалуйста неучу что такое MSDN ?
Эксперт С++
 Аватар для XuTPbIu_MuHTAu
2256 / 771 / 25
Регистрация: 27.05.2008
Сообщений: 1,496
02.02.2009, 23:49
MSDN - справка от майкрософта,на их же сайте доступна в онлайне. Что интересно - сайт их сейчас лежит. ) Поэтому, в виде исключения, скопирую сюда инфу. Вообще говоря, пользуйтесь поисковиками для поиска прототипов ф-й и структур.

SetCommState
The SetCommState function configures a communications device according to the specifications in a device-control block (a DCB structure). The function reinitializes all hardware and control settings, but it does not empty output or input queues.

BOOL SetCommState(

HANDLE hFile, // handle of communications device
LPDCB lpDCB // address of device-control block structure
);


Parameters

hFile

Identifies the communications device. The CreateFile function returns this handle.

lpDCB

Points to a DCB structure containing the configuration information for the specified communications device.



Return Values

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The SetCommState function uses a DCB structure to specify the desired configuration. The GetCommState function returns the current configuration.
To set only a few members of the DCB structure, you should modify a DCB structure that has been filled in by a call to GetCommState. This ensures that the other members of the DCB structure have appropriate values.
The SetCommState function fails if the XonChar member of the DCB structure is equal to the XoffChar member.

When SetCommState is used to configure the 8250, the following restrictions apply to the values for the DCB structure's ByteSize and StopBits members:

· The number of data bits must be 5 to 8 bits.
· The use of 5 data bits with 2 stop bits is an invalid combination, as are 6, 7, or 8 data bits with 1.5 stop bits.

DCB
typedef struct _DCB { // dcb
DWORD DCBlength; // sizeof(DCB)
DWORD BaudRate; // current baud rate
DWORD fBinary: 1; // binary mode, no EOF check
DWORD fParity: 1; // enable parity checking
DWORD fOutxCtsFlow:1; // CTS output flow control
DWORD fOutxDsrFlow:1; // DSR output flow control
DWORD fDtrControl:2; // DTR flow control type
DWORD fDsrSensitivity:1; // DSR sensitivity

DWORD fTXContinueOnXoff:1; // XOFF continues Tx
DWORD fOutX: 1; // XON/XOFF out flow control
DWORD fInX: 1; // XON/XOFF in flow control
DWORD fErrorChar: 1; // enable error replacement
DWORD fNull: 1; // enable null stripping
DWORD fRtsControl:2; // RTS flow control
DWORD fAbortOnError:1; // abort reads/writes on error
DWORD fDummy2:17; // reserved
WORD wReserved; // not currently used

WORD XonLim; // transmit XON threshold
WORD XoffLim; // transmit XOFF threshold
BYTE ByteSize; // number of bits/byte, 4-8
BYTE Parity; // 0-4=no,odd,even,mark,space
BYTE StopBits; // 0,1,2 = 1, 1.5, 2
char XonChar; // Tx and Rx XON character
char XoffChar; // Tx and Rx XOFF character
char ErrorChar; // error replacement character

char EofChar; // end of input character
char EvtChar; // received event character
WORD wReserved1; // reserved; do not use
} DCB;


Members

DCBlength

Specifies the length, in bytes, of the DCB structure.

BaudRate

Specifies the baud rate at which the communications device operates. This member can be an actual baud rate value, or one of the following baud rate indexes:

CBR_110 CBR_19200
CBR_300 CBR_38400
CBR_600 CBR_56000
CBR_1200 CBR_57600
CBR_2400 CBR_115200
CBR_4800 CBR_128000
CBR_9600 CBR_256000
CBR_14400


fBinary

Specifies whether binary mode is enabled. The Win32 API does not support nonbinary mode transfers, so this member should be TRUE. Trying to use FALSE will not work.

Under Windows 3.1, if this member is FALSE, nonbinary mode is enabled, and the character specified by the EofChar member is recognized on input and remembered as the end of data.

fParity

Specifies whether parity checking is enabled. If this member is TRUE, parity checking is performed and errors are reported.

fOutxCtsFlow

Specifies whether the CTS (clear-to-send) signal is monitored for output flow control. If this member is TRUE and CTS is turned off, output is suspended until CTS is sent again.

fOutxDsrFlow

Specifies whether the DSR (data-set-ready) signal is monitored for output flow control. If this member is TRUE and DSR is turned off, output is suspended until DSR is sent again.

fDtrControl

Specifies the DTR (data-terminal-ready) flow control. This member can be one of the following values:

Value Meaning
DTR_CONTROL_DISABLE Disables the DTR line when the device is opened and leaves it disabled.
DTR_CONTROL_ENABLE Enables the DTR line when the device is opened and leaves it on.
DTR_CONTROL_HANDSHAKE Enables DTR handshaking. If handshaking is enabled, it is an error for the application to adjust the line by using the EscapeCommFunction function.


fDsrSensitivity

Specifies whether the communications driver is sensitive to the state of the DSR signal. If this member is TRUE, the driver ignores any bytes received, unless the DSR modem input line is high.

fTXContinueOnXoff

Specifies whether transmission stops when the input buffer is full and the driver has transmitted the XoffChar character. If this member is TRUE, transmission continues after the input buffer has come within XoffLim bytes of being full and the driver has transmitted the XoffChar character to stop receiving bytes. If this member is FALSE, transmission does not continue until the input buffer is within XonLim bytes of being empty and the driver has transmitted the XonChar character to resume reception.

fOutX

Specifies whether XON/XOFF flow control is used during transmission. If this member is TRUE, transmission stops when the XoffChar character is received and starts again when the XonChar character is received.

fInX

Specifies whether XON/XOFF flow control is used during reception. If this member is TRUE, the XoffChar character is sent when the input buffer comes within XoffLim bytes of being full, and the XonChar character is sent when the input buffer comes within XonLim bytes of being empty.

fErrorChar

Specifies whether bytes received with parity errors are replaced with the character specified by the ErrorChar member. If this member is TRUE and the fParity member is TRUE, replacement occurs.

fNull

Specifies whether null bytes are discarded. If this member is TRUE, null bytes are discarded when received.

fRtsControl

Specifies the RTS (request-to-send) flow control. If this value is zero, the default is RTS_CONTROL_HANDSHAKE. This member can be one of the following values:

Value Meaning
RTS_CONTROL_DISABLE Disables the RTS line when the device is opened and leaves it disabled.
RTS_CONTROL_ENABLE Enables the RTS line when the device is opened and leaves it on.
RTS_CONTROL_HANDSHAKE Enables RTS handshaking. The driver raises the RTS line when the "type-ahead" (input) buffer is less than one-half full and lowers the RTS line when the buffer is more than three-quarters full. If handshaking is enabled, it is an error for the application to adjust the line by using the EscapeCommFunction function.
RTS_CONTROL_TOGGLE Specifies that the RTS line will be high if bytes are available for transmission. After all buffered bytes have been sent, the RTS line will be low.


fAbortOnError

Specifies whether read and write operations are terminated if an error occurs. If this member is TRUE, the driver terminates all read and write operations with an error status if an error occurs. The driver will not accept any further communications operations until the application has acknowledged the error by calling the ClearCommError function.

fDummy2

Reserved; do not use.

wReserved

Not used; must be set to zero.

XonLim

Specifies the minimum number of bytes allowed in the input buffer before the XON character is sent.

XoffLim

Specifies the maximum number of bytes allowed in the input buffer before the XOFF character is sent. The maximum number of bytes allowed is calculated by subtracting this value from the size, in bytes, of the input buffer.

ByteSize

Specifies the number of bits in the bytes transmitted and received.

Parity

Specifies the parity scheme to be used. This member can be one of the following values:

Value Meaning
EVENPARITY Even
MARKPARITY Mark
NOPARITY No parity
ODDPARITY Odd


StopBits

Specifies the number of stop bits to be used. This member can be one of the following values:

Value Meaning
ONESTOPBIT 1 stop bit
ONE5STOPBITS 1.5 stop bits
TWOSTOPBITS 2 stop bits


XonChar

Specifies the value of the XON character for both transmission and reception.

XoffChar

Specifies the value of the XOFF character for both transmission and reception.

ErrorChar

Specifies the value of the character used to replace bytes received with a parity error.

EofChar

Specifies the value of the character used to signal the end of data.

EvtChar

Specifies the value of the character used to signal an event.

wReserved1

Reserved; do not use.



Remarks

When a DCB structure is used to configure the 8250, the following restrictions apply to the values specified for the ByteSize and StopBits members:

· The number of data bits must be 5 to 8 bits.
· The use of 5 data bits with 2 stop bits is an invalid combination, as is 6, 7, or 8 data bits with 1.5 stop bits.

EscapeCommFunction
The EscapeCommFunction function directs a specified communications device to perform an extended function.

BOOL EscapeCommFunction(

HANDLE hFile, // handle to communications device
DWORD dwFunc // extended function to perform
);


Parameters

hFile

Identifies the communications device. The CreateFile function returns this handle.

dwFunc

Specifies the code of the extended function to perform. This parameter can be one of the following values:

Value Meaning
CLRDTR Clears the DTR (data-terminal-ready) signal.
CLRRTS Clears the RTS (request-to-send) signal.
SETDTR Sends the DTR (data-terminal-ready) signal.
SETRTS Sends the RTS (request-to-send) signal.
SETXOFF Causes transmission to act as if an XOFF character has been received.
SETXON Causes transmission to act as if an XON character has been received.
SETBREAK Suspends character transmission and places the transmission line in a break state until the ClearCommBreak function is called (or EscapeCommFunction is called with the CLRBREAK extended function code). The SETBREAK extended function code is identical to the SetCommBreak function. Note that this extended function does not flush data that has not been transmitted.
CLRBREAK Restores character transmission and places the transmission line in a nonbreak state. The CLRBREAK extended function code is identical to the ClearCommBreak function.


Return Values

If the function succeeds, the return value is nonzero.
If the function fails, the return value is zero. To get extended error information, call GetLastError.
1
SATANAblack
09.02.2009, 01:48
Цитата Сообщение от D'Kard Kain Посмотреть сообщение
Друзья спасайте!
И второй вопрос: как сделать так что бы программа после компиляции запускалась на всех компьютерах, а не только на тех где есть билдер..
1)Project->Options->Compiller (жми Release)
2)Project->Options->Packages(забери галку с Build with Runtime Packages)
3)Project->Options->Linker(Забери галку с Use dynamic RTL)

ехе-шники твои станут больше размером, но и запускатся будут на других компах.

Добавлено через 2 минуты 23 секунды
А еще вопрос на счет COM - портов: как мне просто подать 5В на два любых(+/-) выхода СОМ порта в нужный для меня момент
Почетный модератор
 Аватар для Lord_Voodoo
8785 / 2538 / 144
Регистрация: 07.03.2007
Сообщений: 11,873
09.02.2009, 09:41
Компиляция программы под С++ Builder, чтобы работала на других компьютерах
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
09.02.2009, 09:41
Помогаю со студенческими работами здесь

работа с COM портом
здравствуйте всем,я в форумах в первие ,и просил бы не судить очень строго. помогите пожалуйста , хочу реализовать приложение работающую с...

Работа с COM портом
по COM порту через Agilen подключается вольтметр с адресом 1. необходимо "прозвонить" все порты и автоматически сделать рабочим тот,...

Асинхронная работа с COM портом.
Здравствуйте, Как известно, в Windows с COM портом можно работать в синхронном и асинхронном режиме. Для работы в асинхронном режиме...

Работа с USB портом.
Доброго всем времени суток! Суть задачи в следующем: Есть устройство (USB принтер этикеток) и им можно управлять при помощи...

И снова работа с COM портом
Приветствую всех. Уже измучился и измаялся весь пытаясь написать функцию. Помогите, пожалуйста... Описание задачи Создается...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
6
Ответ Создать тему
Новые блоги и статьи
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Access
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru