Реклама на сайте DatasheetsDatasheets

KAZUS.RUN - Электронный портал. Принципиальные схемы, Datasheets, Форум по электронике

Новости электроники Новости Литература, электронные книги Литература Документация, даташиты Документация Поиск даташитов (datasheets)Поиск PDF
  От производителей
Новости поставщиков
В мире электроники

  Сборник статей
Книги и журналы
FAQ по электронике

  Datasheets
Поиск SMD
Онлайн справочник

Принципиальные схемы Схемы Каталоги программ, сайтов Каталоги Общение, форум Общение Ваш аккаунтАккаунт
  Каталог схем
Схемы и проекты
Принципиальные схемы
  Программы
Каталог сайтов
Калькуляторы
  Форумы по электронике
Помощь проекту

Микроконтроллеры, АЦП, память и т.д Темы касающиеся микроконтроллеров разных производителей, памяти, АЦП/ЦАП, периферийных модулей...

 
Опции темы

Народ, помогите, плиз! 2й USART в PIC

Непрочитано 23.12.2004, 19:30  
mxsimus
Прохожий
 
Регистрация: 23.12.2004
Сообщений: 3
Сказал спасибо: 0
Сказали Спасибо 0 раз(а) в 0 сообщении(ях)
mxsimus на пути к лучшему
По умолчанию Народ, помогите, плиз! 2й USART в PIC

Мне нужна программа (или ссылка, может, кто где видел) на ASM, чтобы реализовать программно дополнительный USART в контроллере типа PIC16 (конкретно PIC16F877). Спасибо!
Реклама:
mxsimus вне форума  
Непрочитано 23.12.2004, 22:34  
TsAN
Частый гость
 
Регистрация: 06.11.2004
Сообщений: 29
Сказал спасибо: 0
Сказали Спасибо 0 раз(а) в 0 сообщении(ях)
TsAN на пути к лучшему
По умолчанию Re: Народ, помогите, плиз! 2й USART в PIC

Алгоритм приема одной посылки сравнительно простой:
  • 1. ждать появления старт-бита;
    2. отсчитать интервал времени, соответствующий половине длительности бита (T/2);
    3. Последовательно, через интервалы времени T, считать: все передаваемые биты, бит четности (если есть), стоповый бит(ы).
При необходимости можно использовать сигналы квитирования, но в uC системах обычно обходятся без них.
TsAN вне форума  
Непрочитано 24.12.2004, 01:11  
vlad
Прохожий
 
Регистрация: 06.02.2004
Сообщений: 7
Сказал спасибо: 0
Сказали Спасибо 0 раз(а) в 0 сообщении(ях)
vlad на пути к лучшему
По умолчанию rs 232

TITLE "RS232 Communications : Half Duplex : PIC16C6x/7x/8x"
SUBTITLE "Software Implementation : Interrupt Driven"

;************************************************* ************************************************** ******
; Software Implementation Of RS232 Communications Using PIC16CXX
; Half-Duplex
;
; These routines are intended to be used with PIC16C6X/7X family. These routines can be
; used with processors in the 16C6X/7X family which do not have on board Hardware Async
; Serial Port.
; MX..
;
; Description :
; Half Duplex RS-232 Mode Is implemented in Software.
; Both Reception & Transmission are Interrupt driven
; Only 1 peripheral (RTCC) used for both transmission & reception
; RTCC is used for both timing generation (for bit transmission & bit polling)
; and Start Bit Detection in reception mode.
; This is explained in more detail in the Interrupt Subroutine.
; Programmable Baud Rate (speed depnding on Input Clock Freq.), programmable
; #of bits, Parity enable/disable, odd/even parity is implemented.
; Parity & Framing errors are detected on Reception
;
; RS-232 Parameters
;
;The RS-232 Parameters are defined as shown below:
;
; _ClkIn : Input Clock Frequency of the processor
; (NOTE : RC Clock Mode Is Not Suggested due to wide variations)
; _BaudRate : Desired Baud Rate. Any valid value can be used.
; The highest Baud Rate achievable depends on Input Clock Freq.
; 300 to 4800 Baud was tested using 4 Mhz Input Clock
; 300 to 19200 Baud was tested using 10 Mhz Input Clock
; Higher rates can be obtained using higher Input Clock Frequencies.
; Once the _BaudRate & _ClkIn are specified the program
; automatically selectes all the appropiate timings
; _DataBits : Can specify 1 to 8 Bits.
; _StopBits : Limited to 1 Stop Bit. Must set it to 1.
; _PARITY_ENABLE : Parity Enable Flag. Set it to TRUE or FALSE. If PARITY
; is used, then set it to TRUE, else FALSE. See "_ODD_PARITY" flag
; description below
; _ODD_PARITY : Set it to TRUE or FALSE. If TRUE, then ODD PARITY is used, else
; EVEN Parity Scheme is used.
; This Flag is ignored if _PARITY_ENABLE is set to FALSE.
;
;
; Usage :
; An example is given in the main program on how to Receive & Transmit Data
; In the example, the processor waits until a command is received. The command is interpreted
; as the A/D Channel Number of PIC16C71. Upon reception of a command, the desired A/D channel
; is selected and after A/D conversion, the 8 Bit A/D data is transmitted back to the Host.
;
; The RS-232 Control/Status Reg's bits are explained below :
;
; "SerialStatus" : RS-232 Status/Control Register
;
; Bit 0 : _txmtProgress (1 if transmission in progress, 0 if transmission is complete)
; After a byte is transmitted by calling "PutChar" function, the
; user's code can poll this bit to check if transmission is complete.
; This bit is reset after the STOP bit has been transmitted
; Bit 1 : _txmtEnable Set this bit to 1 on initialization to enable transmission.
; This bit can be used to Abort a transmission while the transmitter
; is in progress (i.e when _txmtProgress = 1)
; Bit 2 : _rcvProgress Indicates that the receiver is in middle of reception.It is reset when
; a byte is received.
; Bit 3 : _rcvOver This bit indicates the completion of Reception of a Byte. The user's
; code can poll this bit after calling "GetChar" function. Once "GetChar"
; function is called, this bit is 1 and is set to 0 after reception of
; a complete byte (parity bit if enabled & stop bit)
; Bit 4 : _ParityErr A 1 indicates Parity Error on Reception (for both even & odd parity)
; Bit 5 : _FrameErr A 1 indicates Framing Error On Reception
;
; Bit 6 : _unused_ Unimplemented Bit
;
; Bit 7 : _parityBit The 9 th bit of transmission or reception (status of PARITY bit
; if parity is enabled)
;
; To Transmit A Byte Of Data :
; 1) Make sure _txmtProgress & _rcvOver bits are cleared
; 2) Load TxReg with data to be transmitted
; 3) CALL PutChar function
;
; To Receive A Byte Of Data :
; 1) Make sure _txmtProgress & _rcvOver bits are cleared
; 2) CALL GetChar function
; 3) The received Byte is in TxReg after _rcvOver bit is cleared
;
;
;
; Program: RS232.ASM
; Revision Date:
; May 17,1994 Scott Fink (Rev 2)
; Corrected 7 bit and parity operation, corrected stop bit generation, corrected
; receive prescaler settings. Protected against inadvertant WDT reset.
; 1-16-97 Compatibility with MPASMWIN 1.40
;
;************************************************* ************************************************** ******

Processor 16f84
Radix DEC
EXPAND

include "p16f84.inc"

_ResetVector set 0x00
_IntVector set 0x04

TRUE equ 1
FALSE equ 0

;************************************************* ************************************************** ******
; Setup RS-232 Parameters
;************************************************* ************************************************** ******

_ClkIn equ 4000000 ; Input Clock Frequency is 4 Mhz
_BaudRate set 1200 ; Baud Rate (bits per second) is 1200
_DataBits set 8 ; 8 bit data, can be 1 to 8
_StopBits set 1 ; 1 Stop Bit, 2 Stop Bits is not implemented

#define _PARITY_ENABLE FALSE ; NO Parity
#define _ODD_PARITY FALSE ; EVEN Parity, if Parity enabled

include "rs232.h"

;************************************************* ************************************************** ******
;

ORG _ResetVector
goto Start
;

ORG _IntVector
goto Interrupt

Start:
CLRF PORTB ; setting output
; data latches
BSF STATUS,RP0 ; Select Bank 1
MOVLW B'00000111'
MOVWF TRISB
MOVLW B'11000011'
MOVWF OPTION_REG
BCF STATUS,RP0

call InitSerialPort
;

WaitForNextSel:

call GetChar ; wait for a byte reception
btfsc _rcvOver ; _rcvOver Gets Cleared when a Byte Is Received (in RxReg)
goto $-1 ; USER can perform other jobs here, can poll _rcvOver bit
;
; A Byte is received

bcf STATUS,RP0 ; make sure to select Page 0
movf RxReg,W


movwf TxReg
INCF TxReg,f
call PutChar
btfsc _txmtProgress
goto $-1 ; Loop Until Transmission Over, User Can Perform Other Jobs


;
goto WaitForNextSel
;
;************************************************* ************************************************** ******
; RS-232 Routines
;;************************************************ ************************************************** *******
; Interrupt Service Routine
;
; Only RTCC Inturrupt Is used. RTCC Inturrupt is used as timing for Serial Port Receive & Transmit
; Since RS-232 is implemented only as a Half Duplex System, The RTCC is shared by both Receive &
; Transmit Modules.
; Transmission :
; RTCC is setup for Internal Clock increments and interrupt is generated when
; RTCC overflows. Prescaler is assigned, depending on The INPUT CLOCK & the
; desired BAUD RATE.
; Reception :
; When put in receive mode, RTCC is setup for external clock mode (FALLING EDGE)
; and preloaded with 0xFF. When a Falling Edge is detected on RTCC Pin, RTCC
; rolls over and an Interrupt is generated (thus Start Bit Detect). Once the start
; bit is detected, RTCC is changed to INTERNAL CLOCK mode and RTCC is preloaded
; with a certain value for regular timing interrupts to Poll RTCC Pin (i.e RX pin).
;
;************************************************* ************************************************** ******

Interrupt:
btfss INTCON,T0IF
retfie ; other interrupt, simply return & enable GIE
;
; Save Status On INT : WREG & STATUS Regs
;
movwf SaveWReg
swapf STATUS,W ; affects no STATUS bits : Only way OUT to save STATUS Reg ?????
movwf SaveStatus
;
btfsc _txmtProgress
goto _TxmtNextBit ; Txmt Next Bit
btfsc _rcvProgress
goto _RcvNextBit ; Receive Next Bit
goto _SBitDetected ; Must be start Bit
;
RestoreIntStatus:
swapf SaveStatus,W
movwf STATUS ; restore STATUS Reg
swapf SaveWReg, F ; save WREG
swapf SaveWReg,W ; restore WREG
bcf INTCON,T0IF
retfie
;
;************************************************* ************************************************** ******
;
;
;
; Configure TX Pin as output, make sure TX Pin Comes up in high state on Reset
; Configure, RX_Pin (RTCC pin) as Input, which is used to poll data on reception
;
; Program Memory : 9 locations
; Cycles : 10
;************************************************* ************************************************** ******

InitSerialPort:
clrf SerialStatus
;
bcf STATUS,RP0 ; select Page 0 for Port Access
bsf TX ; make sure TX Pin is high on powerup, use RB Port Pullup
bsf STATUS,RP0 ; Select Page 1 for TrisB access
bcf TX ; set TX Pin As Output Pin, by modifying TRIS
bsf RX_Pin ; set RX Pin As Input for reception
return
;
;************************************************* ************************************************** ******

include "txmtr.inc" ; The Transmit routines are in file "txmtr.asm"
include "rcvr.inc" ; The Receiver Routines are in File "rcvr.asm"

;************************************************* ************************************************** ******

END
vlad вне форума  
Непрочитано 24.12.2004, 01:26  
vlad
Прохожий
 
Регистрация: 06.02.2004
Сообщений: 7
Сказал спасибо: 0
Сказали Спасибо 0 раз(а) в 0 сообщении(ях)
vlad на пути к лучшему
По умолчанию

Фаилы необходимые при компиляции, необходимо их разбить по названиям и подставить inc файл нужного процесора


;************************************************* ****************************************
; GetChar Function
; Receives a Byte Of Data
; When reception is complete, _rcvOver Bit is cleared
; The received data is in RxReg
;
; Program Memory : 15 locations (17 locations if PARITY is used)
; Cycles : 16 (18 if PARITY is USED)
;
;************************************************* ****************************************
GetChar:
bcf STATUS,RP0
bsf _rcvOver ; Enable Reception, this bit gets reset on Byte Rcv Complete
LOAD_BITCOUNT
clrf RxReg
bcf _FrameErr
bcf _ParityErr ; Init Parity & Framing Errors
clrf TMR0
clrwdt
bsf STATUS,RP0
movlw 07h
movwf OPTION_REG
bcf STATUS,RP0
clrf TMR0
bsf STATUS,RP0
movlw 0Fh
movwf OPTION_REG
clrwdt
movlw _OPTION_SBIT ; Inc On Ext Clk Falling Edge
movwf OPTION_REG ; Set Option Reg Located In Page 1
bcf STATUS,RP0 ; make sure to select Page 0
movlw 0xFF
movwf TMR0 ; A Start Bit will roll over RTCC & Gen INT
bcf INTCON,T0IF
bsf INTCON,T0IE ; Enable RTCC Interrupt
retfie ; Enable Global Interrupt
;
;************************************************* ****************************************
; Internal Subroutine
; entered from Interrupt Service Routine when Start Bit Is detected.
;
; Program Memory : 14 locations
; Cycles : 12 (worst case)
;
;************************************************* ****************************************
_SBitDetected:
bcf STATUS,RP0
btfsc RX_Pin ; Make sure Start Bit Interrupt is not a Glitch
goto _FalseStartBit ; False Start Bit
bsf _rcvProgress
clrf TMR0
clrwdt
bsf STATUS,RP0
movlw 07h
movwf OPTION_REG
bcf STATUS,RP0
clrf TMR0
bsf STATUS,RP0
movlw 0Fh
movwf OPTION_REG
clrwdt
movlw (_BIT1_INIT | SBitPrescale) ; Switch Back to INT Clock
movwf OPTION_REG ; Set Option Reg Located In Page 1
bcf STATUS,RP0 ; make sure to select Page 0
LOAD_RTCC 1,(SBitRtccLoad), SBitPrescale
goto RestoreIntStatus
;
_FalseStartBit:
movlw 0xFF
movwf TMR0 ; reload RTCC with 0xFF for start bit detection
goto RestoreIntStatus
;
;************************************************* ****************************************
; Internal Subroutine
; entered from Interrupt Service Routine when Start Bit Is detected.
;
; Program Memory : 28 locations ( 43 locations with PARITY enabled)



;************************************************* ************************************************** ******
; PutChar Function
;
; Function to transmit A Byte Of Data
; Before calling this routine, load the Byte to be transmitted into TxReg
; Make sure _txmtProgress & _rcvOver bits (in Status Reg) are cleared before
; calling this routine
;
; Program Memory : 6 locations (10 locations if PARITY is Used)
; Cycles : 8 (13 if PARITY is Used)
;
;************************************************* ************************************************** ******
PutChar:
bsf _txmtEnable ; enable transmission
bsf _txmtProgress
LOAD_BITCOUNT ; Macro to load bit count
decf BitCount,1
if _DataBits == 7
bsf TxReg,7
endif
;
if _PARITY_ENABLE
movf TxReg,W
call GenParity ; If Parity is used, then Generate Parity Bit
endif
;
call _TxmtStartBit
bsf INTCON,T0IE ; Enable RTCC Overflow INT
retfie ; return with _GIE Bit Set
;
;************************************************* ************************************************** ******
; Internal Subroutine
; entered from Interrupt Service Routine when Start Bit Is detected.
;
; Program Memory : 30 locations (38 locations if PARITY is used)
; Cycles : 15 Worst Case
;
;************************************************* ************************************************** ******

_TxmtNextBit:
bcf STATUS,RP0
LOAD_RTCC 0,RtccPreLoad, RtccPrescale ; Macro to reload RTCC
;
movf BitCount, F ;done with data xmission?
btfsc STATUS,Z
goto _ParityOrStop ;yes, do parity or stop bit
;
decf BitCount, F
goto _NextTxmtBit ;no, send another
;
_ParityOrStop:
if _PARITY_ENABLE
btfsc ExtraBitCount,1 ;ready for parity bit?
goto _SendParity
endif
movf ExtraBitCount,1 ;check if sending stop bit
btfsc STATUS,Z
goto DoneTxmt
decf ExtraBitCount,1
;
_StopBit:
bsf TX ; STOP Bit is High
goto RestoreIntStatus
goto DoneTxmt
;
_NextTxmtBit:
bsf STATUS,C
rrf TxReg, F
btfss STATUS,C
bcf TX


;******************************************

NOLIST

;************************************************* ****************************************
; RS-232 Header File
; PIC16C6X/7X/8X
;************************************************* ****************************************

_ClkOut equ (_ClkIn ›› 2) ; Instruction Cycle Freq = CLKIN/4
;

_CyclesPerBit set (_ClkOut/_BaudRate)
_tempCompute set (_CyclesPerBit ››
;
;************************************************* ****************************************
; Auto Generation Of Prescaler & Rtcc Values
; Computed during Assembly Time
;************************************************* ****************************************

; At first set Default values for RtccPrescale & RtccPreLoad
;
RtccPrescale set 0
RtccPreLoad set _CyclesPerBit
UsePrescale set FALSE

if (_tempCompute ›= 1)
RtccPrescale set 0
RtccPreLoad set (_CyclesPerBit ›› 1)

UsePrescale set TRUE
endif

if (_tempCompute ›= 2)
RtccPrescale set 1
RtccPreLoad set (_CyclesPerBit ›› 2)
endif

if (_tempCompute ›= 4)
RtccPrescale set 2
RtccPreLoad set (_CyclesPerBit ›› 3)
endif

if (_tempCompute ›=
RtccPrescale set 3
RtccPreLoad set (_CyclesPerBit ›› 4)
endif


if (_tempCompute ›= 16)
RtccPrescale set 4
RtccPreLoad set (_CyclesPerBit ›› 5)
endif


if (_tempCompute ›= 32)
RtccPrescale set 5
RtccPreLoad set (_CyclesPerBit ›› 6)
endif


if (_tempCompute ›= 64)
RtccPrescale set 6
RtccPreLoad set (_CyclesPerBit ›› 7)
endif


if (_tempCompute ›= 12
RtccPrescale set 7
RtccPreLoad set (_CyclesPerBit ››
endif

;
if( (RtccPrescale == 0) && (RtccPreLoad ‹ 60))
messg "Warning : Baud Rate May Be Too High For This Input Clock"
endif
;
; Compute RTCC & Presclaer Values For 1.5 Times the Baud Rate for Start Bit Detection
;

_SBitCycles set (_ClkOut/_BaudRate) + ((_ClkOut/4)/_BaudRate)
_tempCompute set (_SBitCycles ››

_BIT1_INIT set 08
SBitPrescale set 0
SBitRtccLoad set _SBitCycles


if (_tempCompute ›= 1)
SBitPrescale set 0
SBitRtccLoad set (_SBitCycles ›› 1)
_BIT1_INIT set 0
endif

if (_tempCompute ›= 2)
SBitPrescale set 1
SBitRtccLoad set (_SBitCycles ›› 2)
endif

if (_tempCompute ›= 4)
SBitPrescale set 2
SBitRtccLoad set (_SBitCycles ›› 3)
endif

if (_tempCompute ›=
SBitPrescale set 3
SBitRtccLoad set (_SBitCycles ›› 4)
endif


if (_tempCompute ›= 16)
SBitPrescale set 4
SBitRtccLoad set (_SBitCycles ›› 5)
endif


if (_tempCompute ›= 32)
SBitPrescale set 5
SBitRtccLoad set (_SBitCycles ›› 6)
endif


if (_tempCompute ›= 64)
SBitPrescale set 6
SBitRtccLoad set (_SBitCycles ›› 7)
endif


if (_tempCompute ›= 12
SBitPrescale set 7
SBitRtccLoad set (_SBitCycles ››
endif



;
;************************************************* ****************************************
;
#define _Cycle_Offset1 24 ;account for interrupt latency, call time

LOAD_RTCC MACRO Mode, K, Prescale

if(UsePrescale == 0 && Mode == 0)
movlw -K + _Cycle_Offset1
else
movlw -K + (_Cycle_Offset1 ›› (Prescale+1)) ; Re Load RTCC init value + INT Latency Offset
endif
movwf TMR0 ; Note that Prescaler is cleared when RTCC is written

ENDM
;************************************************* ****************************************

LOAD_BITCOUNT MACRO

movlw _DataBits+1
movwf BitCount
movlw 1
movwf ExtraBitCount

if _PARITY_ENABLE
movlw 2
movwf ExtraBitCount
endif

ENDM
;
;************************************************* *************************************************
; Pin Assignements
;************************************************* *************************************************
#define RX_MASK 0x7 ; RX pin is connected to RA4, ie. bit 4
#define RX_Pin PORTB,0 ; RX Pin : RB0
#define RX RxTemp,4

#define TX PORTB,3 ; TX Pin , RB3

#define _RTS PORTB,5 ; RTS Pin, RB5, Output signal
#define _CTS PORTB,6 ; CTS Pin, RB6, Input signal


#define _txmtProgress SerialStatus,0
#define _txmtEnable SerialStatus,1

#define _rcvProgress SerialStatus,2
#define _rcvOver SerialStatus,3
#define _ParityErr SerialStatus,4
#define _FrameErr SerialStatus,5

#define _parityBit SerialStatus,7

;************************************************* **************************************************

_OPTION_SBIT set 0x38 ; Increment on Ext Clock (falling edge), for START Bit Detect

if UsePrescale
_OPTION_INIT set 0x00 ; Prescaler is used depending on Input Clock & Baud Rate
else
_OPTION_INIT set 0x0F
endif

CBLOCK 0x0C
TxReg ; Transmit Data Holding/Shift Reg
RxReg ; Rcv Data Holding Reg
RxTemp
SerialStatus ; Txmt & Rev Status/Control Reg
BitCount
ExtraBitCount ; Parity & Stop Bit Count
SaveWReg ; temp hold reg of WREG on INT
SaveStatus ; temp hold reg of STATUS Reg on INT
temp1, temp2
ENDC

;************************************************* **************************************************

LIST
vlad вне форума  
 
Опции темы

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.

Быстрый переход

Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Народ, помогите найти распиновку LCD экрана телефона 777grey Поиск схем. Делимся схемами 1 03.01.2009 21:57
USART (PIC): как сделать низкий уровень на TX после посылки? mxsimus Микроконтроллеры, АЦП, память и т.д 2 27.03.2008 13:07
USART (PIC): о чистке приемного буфера EUSART mxsimus Микроконтроллеры, АЦП, память и т.д 0 27.03.2008 11:20
Калькулятор для PIC:Timers, PWM, USART, EUSART, ADC, LCD ... fmssp Микроконтроллеры, АЦП, память и т.д 1 22.04.2007 17:23
Народ, помогите с генером!!! Van Автоматика и аппаратура связи 1 08.03.2005 13:53


Часовой пояс GMT +4, время: 21:11.


Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.