Смекни!
smekni.com

Послідовні інтерфейси ПК (стр. 2 из 3)

Переваги програмного протоколу полягають у відсутності необхідності передачі управляючих сигналів інтерфейсу – мінімальний кабель для двостороннього обміну може мати тільки три провідники. Недоліком, крім вимого наявності буферу і більшого часу реакції, є складність реалізації повно дуплексного режиму обміну. В цьому випадку з потоку приймаючих даних повинні виділятися символи управління потоком, що обмежує набір символів, що передаються.

IBM PC може містити до чотирьох послідовних портів, які також називають адаптерами RS-232C. В PS/2 (крім моделей 25 і 30) може бути до восьми таких адаптерів. В MS-DOS послідовні порти називаються COMX, де X – номер порту. Працювати з послідовними портами можна як з використанням BIOS, так і безпосередньо через використання апаратних переривань.

В BIOS для роботи з послідовними портами виділено спеціальне переривання int14 (тут і далі числа вказуються в 16-ій системі числення). З допомогою цього переривання можна встановити параметри порту, перевірити статус порту, прийняти або передати байт даних. Але при роботі через BIOS програма повинна обробляти дані зі швидкістю не менше ніж швидкість їх поступлення, так як в IBM PC не підтримується апаратна буферизація даних, які проходять через послідовний порт. Робота з використанням int14 можлива при передачі даних зі швидкостями до 300 бод. При більших швидкостях дані губляться.

При роботі на швидкостях більше 300 бод доводиться організовувати програмну буферизацію даних, що приймаються, а в окремих випадках і даних, що передаються. Це можна зробити при використанні переривань, які можуть генеруватися послідовними портами.


1.5 Програмна частина інтерфейсу

Програмувати розробку інтерфейсу можна на нижчому рівні (наприклад із використанням мови Assembler), на середньому рівні та на мовах високого рівня (наприклад в середовищі Microsoft Visual C++.NET 2005).

Для програмування COM портів в середовищі Microsoft Visual C++.NET 2005 використовується компонент SeriesPort, в якому реалізована вся взаємодія з драйвером COM-порту.

Для роботи з COM-портом оголошуємо об’єкт:

System:IO: Ports: SerialPort^ serialPort1;

Перед записом ініціалізуємо необхідні властивості:

· PortName;

· BaudRate;

· ReadTimeout.

Після ініціалізації об’єкта віддкриваємо порт:

serialPort1->Open();

Для запису використовуються методи:

· Write (array<unsigned char>^ buffer, int offset, int size);

· WriteLine (String^ line).

Для зчитування даних з порту використовуються методи класу SerialPort:

· Read (array<unsigned char>^ buffer, int offset, int size);

· ReadLine();

· ReadChar();

· ReadByte().

1.6 Перспективи інтерфейсу RS-232C

Розроблено декілька нових стандартів, направлених на усунення нестач первинних специфікацій інтерфейсу RS-232C. Серед них можна відмітити інтерфейс RS-422 (балансна система, що допускає імпеданс лінії до 50 Ом), RS-423 (несиметрична система з мінімальним імпедансом лінії 450 Ом) і RS-449 (стандарт з високою швидкістю передачі даних, в якому декілька змінені функції схем і застосовується 37 контактний роз'єм типу D).


2. Порядок виконання роботи

Робота виконуються на комп’ютері з використанням навчального стенду.

2.1 Ознайомитись з інструкцією до лабораторної роботи.

2.2 Отримати у викладача завдання і написати програму для обміну інформацією через COM порт.

2.3 Перевірити функціонування програми на двох ПК, які з’єднані через COM порти.


3. Приклад завдання та його реалізація

3.1 Приклад завдання

1. З’єднати два комп’ютери через роз’єми COM-портів.

2. Скласти програму надсилання та прийому файлів через COM порт.

3.2 Реалізація

Програма реалізації приведена в додатку 1.


4. Зміст звіту

4.1 Мета роботи.

4.2 Короткі теоретичні відомості.

4.3 Код програми для обміну інформацією через COM порт з поясненнями і коментарями.

4.4 Висновки і порівняння.


Література

1. Гук М.Ю. Аппаратные средства IBM PC. Энциклопедия. 3-е изд. – СПб.: Питер, 2006–1072 с.: ил.

2. Гук М. Интерфейсы ПК: справочник, ЗАО «Издательство «Питер», 1999. – 416 с.: ил.

3. Парамуд Я.С. Інтерфейси периферійних пристроїв ЕОМ:

4. Навч.посбник.-к.: ІСДО, 1995,-76 с.

5. MSDN helper (http://www.msdn.com).

Додаток

Код програми написаний на мові Microsoft Visual C++.NET для обміну файлами через COM-порт з’єднання.

#pragma once

namespace COMmunicator {

using namespace System;

using namespace System: ComponentModel;

using namespace System: Collections;

using namespace System: Windows: Forms;

using namespace System: Data;

using namespace System: Drawing;

using namespace System:IO;

void readData();

/// <summary>

/// Summary for Form1

///

/// WARNING: If you change the name of this class, you will need to change the

/// 'Resource File Name' property for the managed resource compiler tool

/// associated with all.resx files this class depends on. Otherwise,

/// the designers will not be able to interact properly with localized

/// resources associated with this form.

/// </summary>

public ref class Form1: public System: Windows: Forms: Form

{

public:

Form1 (void)

{

InitializeComponent();

//

//TODO: Add the constructor code here

//

}

protected:

/// <summary>

/// Clean up any resources being used.

/// </summary>

~Form1 ()

{

if (components)

{

delete components;

}

}

private: System:IO: Ports: SerialPort^ serialPort1;

private: System: Windows: Forms: ComboBox^ comboBox1;

private: System: Windows: Forms: Button^ button1;

private: System: Windows: Forms: Button^ button2;

private: System: Windows: Forms: OpenFileDialog^ openFileDialog1;

private: System: Windows: Forms: Button^ button3;

private: System: Windows: Forms: TextBox^ textBox1;

private: System: Windows: Forms: Label^ label1;

private: System: Windows: Forms: Label^ label2;

private: System: Windows: Forms: Label^ label3;

private: System: Windows: Forms: ComboBox^ comboBox2;

private: System: Windows: Forms: Label^ label4;

private: System: Windows: Forms: ProgressBar^ progressBar1;

private: System: ComponentModel:IContainer^ components;

protected:

private:

/// <summary>

/// Required designer variable.

/// </summary>

#pragma region Windows Form Designer generated code

/// <summary>

/// Required method for Designer support – do not modify

/// the contents of this method with the code editor.

/// </summary>

void InitializeComponent(void)

{

this->components = (gcnew System: ComponentModel: Container());

this->serialPort1 = (gcnew System:IO: Ports: SerialPort (this->components));

this->comboBox1 = (gcnew System: Windows: Forms: ComboBox());

this->button1 = (gcnew System: Windows: Forms: Button());

this->button2 = (gcnew System: Windows: Forms: Button());

this->openFileDialog1 = (gcnew System: Windows: Forms: OpenFileDialog());

this->button3 = (gcnew System: Windows: Forms: Button());

this->textBox1 = (gcnew System: Windows: Forms: TextBox());

this->label1 = (gcnew System: Windows: Forms: Label());

this->label2 = (gcnew System: Windows: Forms: Label());

this->label3 = (gcnew System: Windows: Forms: Label());

this->comboBox2 = (gcnew System: Windows: Forms: ComboBox());

this->label4 = (gcnew System: Windows: Forms: Label());

this->progressBar1 = (gcnew System: Windows: Forms: ProgressBar());

this->SuspendLayout();

//

// comboBox1

//

this->comboBox1->Font = (gcnew System: Drawing: Font (L «Microsoft Sans Serif», 9.75F, System: Drawing: FontStyle: Regular, System: Drawing: GraphicsUnit: Point,

static_cast<System: Byte>(204)));

this->comboBox1->FormattingEnabled = true;

this->comboBox1->Location = System: Drawing: Point (176, 21);

this->comboBox1->Name = L «comboBox1»;

this->comboBox1->Size = System: Drawing: Size (97, 24);

this->comboBox1->TabIndex = 1;

//

// button1

//

this->button1->Font = (gcnew System: Drawing: Font (L «Microsoft Sans Serif», 9.75F, System: Drawing: FontStyle: Regular, System: Drawing: GraphicsUnit: Point,

static_cast<System: Byte>(204)));

this->button1->Location = System: Drawing: Point (323, 71);

this->button1->Name = L «button1»;

this->button1->Size = System: Drawing: Size (136, 23);

this->button1->TabIndex = 2;

this->button1->Text = L «Прийняти файл»;

this->button1->UseVisualStyleBackColor = true;

this->button1->Click += gcnew System: EventHandler (this, &Form1:button1_Click);

//

// button2

//

this->button2->Font = (gcnew System: Drawing: Font (L «Microsoft Sans Serif», 9.75F, System: Drawing: FontStyle: Regular, System: Drawing: GraphicsUnit: Point,

static_cast<System: Byte>(204)));

this->button2->Location = System: Drawing: Point (495, 70);

this->button2->Name = L «button2»;

this->button2->Size = System: Drawing: Size (127, 23);

this->button2->TabIndex = 3;

this->button2->Text = L «Надіслати файл»;

this->button2->UseVisualStyleBackColor = true;

this->button2->Click += gcnew System: EventHandler (this, &Form1:button2_Click);

//

// openFileDialog1

//

this->openFileDialog1->InitialDirectory = L «D:&bsol;»;

this->openFileDialog1->RestoreDirectory = true;

this->openFileDialog1->Title = L «Select file»;

this->openFileDialog1->FileOk += gcnew System: ComponentModel: CancelEventHandler (this, &Form1:openFileDialog1_FileOk);

//

// button3

//

this->button3->Font = (gcnew System: Drawing: Font (L «Microsoft Sans Serif», 9.75F, System: Drawing: FontStyle: Regular, System: Drawing: GraphicsUnit: Point,

static_cast<System: Byte>(204)));

this->button3->Location = System: Drawing: Point (593, 20);

this->button3->Name = L «button3»;

this->button3->Size = System: Drawing: Size (29, 24);

this->button3->TabIndex = 5;

this->button3->Text = L»…»;

this->button3->TextAlign = System: Drawing: ContentAlignment: TopCenter;

this->button3->UseVisualStyleBackColor = true;

this->button3->Click += gcnew System: EventHandler (this, &Form1:button3_Click);

//

// textBox1

//

this->textBox1->Font = (gcnew System: Drawing: Font (L «Microsoft Sans Serif», 9.75F, System: Drawing: FontStyle: Regular, System: Drawing: GraphicsUnit: Point,

static_cast<System: Byte>(204)));

this->textBox1->Location = System: Drawing: Point (372, 21);

this->textBox1->Name = L «textBox1»;

this->textBox1->Size = System: Drawing: Size (215, 22);

this->textBox1->TabIndex = 6;

//

// label1

//

this->label1->AutoSize = true;

this->label1->Font = (gcnew System: Drawing: Font (L «Microsoft Sans Serif», 9.75F, System: Drawing: FontStyle: Regular, System: Drawing: GraphicsUnit: Point,

static_cast<System: Byte>(204)));

this->label1->Location = System: Drawing: Point (26, 24);

this->label1->Name = L «label1»;

this->label1->Size = System: Drawing: Size (144, 16);

this->label1->TabIndex = 7;

this->label1->Text = L «Доступні COM порти:»;

this->label1->Click += gcnew System: EventHandler (this, &Form1:label1_Click);

//

// label2

//

this->label2->AutoSize = true;

this->label2->Font = (gcnew System: Drawing: Font (L «Microsoft Sans Serif», 9.75F, System: Drawing: FontStyle: Regular, System: Drawing: GraphicsUnit: Point,

static_cast<System: Byte>(204)));

this->label2->Location = System: Drawing: Point (320, 23);

this->label2->Name = L «label2»;

this->label2->Size = System: Drawing: Size (46, 16);

this->label2->TabIndex = 8;

this->label2->Text = L «Файл:»;

//

// label3

//

this->label3->AutoSize = true;

this->label3->Font = (gcnew System: Drawing: Font (L «Microsoft Sans Serif», 9.75F, System: Drawing: FontStyle: Regular, System: Drawing: GraphicsUnit: Point,

static_cast<System: Byte>(204)));

this->label3->Location = System: Drawing: Point (26, 73);

this->label3->Name = L «label3»;