• Главная • Назад •








Counter

 


Осциллограф на PIC18 и TIC-32
автор Геннадий Чернов


В этом разделе описан алгоритм и приведена схемотехника построения осциллографа с применением дисплея на контроллере PCF8531.

В приведенном примере использовался контроллер PIC18F452 и дисплей TIC32.

 

За основу взят проект Audio Spectrum Monitor

 

схема для тестирования осциллографа приведена на рисунке 1.

 

рис.1

 

программа на ASM.

;******************************************************************************
;                                                                             *
;    Filename:   проект осцилограф   (обучающая программа работа с АЦП, I2C)  *
;    Date:                                                                    *
;    File Version: 09                                                         *
;                                                                             *
;    Author:   Chernov Gennadij     
Геннадий Чернов (Владимирович) 1963      *
;    Company:  IS                                                                                                                                                                                                                                            *
;              start                     11/08/08                                                                                       *

;    end                                                                      *
;******************************************************************************
;                                                                             *

;    Files required:         P18F252.INC                                      *
;                                                                             *
;******************************************************************************
;    Осцилограф на PIC18 и LCD TIC32
; резонатор 10 мГц                                                                     *
;******************************************************************************
                LIST P=18F452                                                                  ;directive to define processor
                #include <P18F452.INC>                                             ;processor specific variable definitions
               
ERRORLEVEL 2
;******************************************************************************
;Биты конфигурации

    CONFIG           OSC = HSPLL             ; Выбор Генератора:
    CONFIG           OSCS = OFF                        ; переключение генератора (разрешено/неразрешено)
    CONFIG           PWRT = ON                        ; Задежка запуска процессора при подаче питания (включена)
    CONFIG           BOR = ON                                                          ; Сброс по понижению питания
    CONFIG           BORV = 42                          ; Уровень напряжения срабатывания сброс при понижении питания 4,2В
    CONFIG           WDT = ON                          ; сторожевой таймер включен
    CONFIG           WDTPS = 128                     ; 1:128 задежка страбатывания сторожевого таймера.
    CONFIG           CCP2MUX = ON                                              ; Разрешение переключения вывода CCP2 OFF-на вывод RB3; ON-на вывод RC1
    CONFIG           STVR = ON                                                         ; сброс при переполнении стека
    CONFIG           LVP = OFF                                                          ; низковольное программирование ICSP
    CONFIG           DEBUG = OFF                                                   ; Работа отладчика
    CONFIG           CP0 = ON                                                           ; защита кода блока 0 активирована
    CONFIG           CP1 = ON                                                           ; защита кода блока 1 активирована
    CONFIG           CP2 = ON                                                           ; защита кода блока 2 активирована
    CONFIG           CP3 = ON                                                           ; защита кода блока 3 активирована
    CONFIG           CPB = ON                                                           ; защита блока загрузки активирована
    CONFIG           CPD = ON                                                           ; защита EEPROM данных активирована
    CONFIG           WRT0 = ON                                                       ; защита записи в блок 0
    CONFIG           WRT1 = ON                                                       ; защита записи в блок 1
    CONFIG           WRT2 = ON                                                       ; защита записи в блок 2
    CONFIG           WRT3 = ON                                                       ; защита записи в блок 3
    CONFIG  WRTB = ON                                                                ; Защита записи в блок загрузки
    CONFIG           WRTC = ON                                                       ; Защита записи в регистр конфирураций
    CONFIG           WRTD = OFF                                                     ; Защита записи в EEPROM память
    CONFIG           EBTR0 = OFF                                                     ; Защита от табличного чтения блока памяти 0
    CONFIG           EBTR1 = OFF                                                     ; Защита от табличного чтения блока памяти 1 
    CONFIG           EBTR2 = OFF                                                     ; Защита от табличного чтения блока памяти 2           
    CONFIG           EBTR3 = OFF                                                     ; Защита от табличного чтения блока памяти 3           
 
;******************************************************************************

                               CBLOCK               0x00A
;========================================
flag_01                                                                                                               ; флаги управления
;=============================================
; переменные программы матемaтических функций
; переменные программы сравнения, умножения, деления
Ah,Al                                                                   ; число_А
Bh,Bl                                                                    ; число_Б
Ch,Cl                                                                    ; число_C
Dh,Dl                                                                   ; число_D
;=============================================
y_cursor                                                             ;
x_cursor                                                             ;
;=============================================
urovensyn                                                         ; уровень синхронизации осцилографа
;=============================================
; регистры программы I2C
adres                                                                   ; адрес устройства обращения
adres_p                                                                             ; переменная в программе передачи с формированным 0 битом на чтение или запись
regisr                                                                   ; регистр обращения
datal                                                                    ; первый байт данных чтения или записи
datah                                                                   ; второй байт данных чтения или записи
ercode                                                                ; флаг ошибок шины I2C
;=============================================
; регистры для программы работы с LCD
sch_s1                                                     ; счетчик цикла вывода

WREG_TEMP                                                   ;variable used for context saving
STATUS_TEMP                                                ;variable used for context saving
BSR_TEMP                                                        ;variable used for context saving
                              
ENDC                    ;

;============================================================================================
; описание портов подключения дисплеев
; графический

#define                               RESIND                PORTD,5                                             ; управление сбросом индикатора

;============================================================================================
                              
#define                               FFT_N   .128                                                      ;количество измерений АЦП
#define                               LCD_W .128                                                      ;Размер дисплея LCD 128x32 точки
#define                               WAV_W              (LCD_W)                                                            ; количество точек отводимое для индикации осцилограффа .58
#define                               ADR_TIC               b'01111000'                        ; адрес индикатора TIC-32 (чип PCF8531)

                               CBLOCK               0x060                                                                   ; начало буферов данных

CaptBuf:              FFT_N*2                                                                                            ; размер 256 байт (0x060) (128*2=256)(буфер измерений АЦП)
BflyBuf:               FFT_N*4                                                                                            ; размер 512 байт          (0x160) буфер FFT


                               ENDC                                                                                                  ;
 
#define                               BNV                                      flag_01,0                             ; биты для программы сканирования АЦП
#define                               BNVs                    flag_01,1                             ; поиска точки синхронизации (необходима для синхронизации картинки осциллограмы)
#define                               ZIO                                        flag_01,2                             ; бит задерки индикайии осцилограммы
#define                               ZNAKp                 flag_01,3                             ;
#define                               RITM                     flag_01,4                             ; бит формирование ритма
#define                               MELODIY                            flag_01,5                             ; б
;============================================================================================
;Reset vector
                               ORG      0x0000
                                               goto      Main
;============================================================================================
;============================================================================================
;============================================================================================
;
прерывания
                               ORG                      0x0008
                                               movff   STATUS,STATUS_TEMP                ;save STATUS register
                                               movff   WREG,WREG_TEMP                      ;save working register
                                               movff   BSR,BSR_TEMP                                ;save BSR register
; таймером формируется тактовая частота на выходе RA5 для тактирования LCD                  
;============================================================================================

;===================================================
end_pr
                                               movff   BSR_TEMP,BSR                                ;restore BSR register
                                               movff   WREG_TEMP,WREG                      ;restore working register
                                               movff   STATUS_TEMP,STATUS                ;restore STATUS register
                              
retfie
;============================================================================================
;============================================================================================
;============================================================================================                              
Main
;============================================================================================
                                                                                                                            
;========================================
                                               ; настройка регистров портов
                                               clrf         PORTA                                                 ;
                                              
clrf         PORTB                                                 ;
                                               clrf         PORTC                                                 ;
                                               clrf         PORTD                                                 ;
                                              
clrf         PORTE                                                 ;             

                                               movlw  b'00000001'                                       ;0-аналоговый вход                                    
                                              
movwf TRISA                                                   ;
                                               movlw  b'00000000'                                       ;
                                               movwf TRISB                                                   ;
                                              
movlw  b'00011000'                                       ; настройка портов I2C
                                               movwf TRISC                                                   ;
                                              
movlw  b'00000000'                                       ;
                                               movwf TRISD                                                   ;                                             
                                               movlw  b'00000000'                                       ;
                                              
movwf TRISE                                                    ;
;============================================================================================
                ; очистка всей памяти данных
                                               lfsr         FSR0,0                                                 ; после сброса. Установить адрес 0
ClfMem                               clrf         POSTINC0                                           ; очистить регистр и увеличит указатель на 1
                                               movlw  0x06                                                     ; проверить достигнут конец памяти рег. пользователя
                                               subwf   FSR0H,w                                                             ;
                                               BNZ       ClfMem                                                              ; если нет повторить очистку следующего регистра
;============================================================================================
                                               clrwdt                                                                                 ; сброс сторожевого таймера++++++
;============================================================================================                              
;=========== настройка АЦП
                                               movlw  b'11000001'                                       ; вход 0, АЦП включен.
                                               movwf ADCON0                                                             ; внутренний RC генератор модуля АЦП                         
                                               movlw  b'01001110'                                       ; опорное AVdd и AVss. включены вход AD0
                                               movwf ADCON1                                                             ;
;============================================================================================
                                               bcf                         RESIND                                                ; формирование импульса сброса для индикатора
;============================================================================================               
                ; настройка модуля МSSP интерфейс I2C
                                               movlw  b'00011000'                                       ; настройка портов I2C
                                               movwf TRISC                                                   ;
                                               movlw  b'00101000'                                       ; включить модуль МSSP; включить режим ведущего
                                               movwf SSPCON1                                                           ;
                                               movlw  b'00000000'                                       ; (
                                               movwf SSPSTAT                                                             ; управление длительностью фронтов в стандартном режиме
                                               movlw  .25                                                                        ; 25 скрорость 400 кГц, 99 скорость 100 кГц
                                               movwf SSPADD                                                              ;
;========================================
;============================================================================================
                                               bsf                         RESIND                                                ; окончания формирование импульса сброса                              
                                               movlw  ADR_TIC                                                             ; адрес индикатора 0х78
                                               movwf adres                                                   ;                                             
;============================================================================================                                              
;                              bra         test3
                                               movlw  LOW      inittic32                               ; адрес таблицы инициализации дисплея
                                              
movwf                 TBLPTRL                                              ;
                                               movlw  HIGH inittic32                    ;
                                               movwf                 TBLPTRH                                             ;                                             
                                               call         load_tab                                             ;
загрузка таблиц
;============================================================================================
                                               call         clr_lcd                                                  ; очистка дисплея         
;============================================================================================
;============================================================================================
                                               clrwdt                                                                                 ; сброс сторожевого таймера++++++
;============================================================================================
                                               movlw  0x7F                                                     ; загрузка уровня синхронизации7F
                                               movwf urovensyn                                         ;

test
;============================================================================================
; программа обработки сигнала АЦП
                                               movlw  FFT_N                                                  ;
                                               movwf Bl                                                                           ; загрузить счетчик измерений
                                               clrwdt                                                                                 ; сброс сторожевого таймера++++++
                                               lfsr         FSR0,CaptBuf                    ; инициализация указателя буфера записи
                                               clrf         Bh                                                                                         ; инициализация счетчика ожидания сигнала
                                               bcf                         BNV                                                                                     ; бит значение ниже точки синхронизации найлено
                                               bcf                         BNVs                                                                   ; бит поиск точки синхронизации выполнен
izacp                    
                               clrwdt                                                                                                 ; сброс сторожевого таймера++++++
                               bsf                         ADCON0,GO                                                     ; запустить преобразование АЦП
                               btfsc      ADCON0,GO                                                     ; ожидать окончание
                               bra         $-.2                                                                                      ;
                              
                                               incfsz    Bh,f                                                      ;
                                               bra                         $+.4                                                      ; проверить згачение достигло 128 измерений
                                               bsf                         BNVs                                                    ; переполнение счеткика ожидания сигнала
                              
                                              
btfsc      BNVs                                                    ;
                                               bra                         zagruz                                                  ;             
                                               btfsc      BNV                                                                     ;
                                              
bra                         bol                                                                        ;                             

                                               movf     urovensyn,w                                    ;ищем значение ниже точки синхронизации
                                              
subwf   ADRESH,w                                         ;
                                               btfss      STATUS,C                                           ;
                                               bsf                         BNV                                                                     ;             
                                               bra                         izacp                                                     ;                                                            
bol
                                               movf     urovensyn,w                                    ;
затем значение выше точки синхронизации
                                               subwf   ADRESH,w                                         ;
                                               btfss      STATUS,C                                           ;
                                               bra                         izacp                                                     ;
                                               bsf                         BNVs                                                    ;             
zagruz                                 
                                              
movlw  0x80                                                     ; формирование данных в виде сигнала с нулем в середине
                                               subwf   ADRESH,f                                           ; диапазонна

                                               movff   ADRESL,POSTINC0                          ; загрузка данных
                                               movff   ADRESH,POSTINC0                         ;(младший байт с начала)
;----------------------------------------                                         
                                              
;                                              movlw  .150                                                      ; растяжка
;                                              movwf Bh                                                                         ;
;                                             
;                                              decfsz   Bh,f                                                      ;
;                                              bra         $-.2                                                                       ;
;                                              decfsz   Bh,f                                                      ; чем больше задержка тем ниже нижняя сканироваемая граница
;                                              bra         $-.2                                                                       ;
;                                              decfsz   Bh,f                                                      ;
;                                              bra         $-.2                                                                       ;
;----------------------------------------
                                               decfsz   Bl,f                                                        ; увеличить счетчик записей проверить згачение достигло 128 измерений
                               bra         izacp                                                                                    ; нет не достишло повторить измерение
;============================================================================================                                              
;----------------------------------------
; Осциллограф
;ZIO - задержка вывода на экран осцилограммы для улудшения прорисовки (для улудшения восприятия)
;                                              btfsc      ZIO                                                                       ;
;                                              bra                         propu                                                  ;
                                rcall        make_wave                                                     ;формирование сигнала графика осцилограммы
                                rcall        rfsh_wave                                                         ;вывод информации на дисплей         
;propu                  btg                         ZIO                                                                       ;
;----------------------------------------
;============================================================================================
                                                               clrwdt                                                                                 ; сброс сторожевого таймера++++++
               
                               bra         test


;============================================================================================
clr_lcd                                                                                                                                ; очистка дисплея
                                                               call         b_start_w                          ; формирования начала START               - цикл запись
                                                               movlw  b'00000000'                        ; последовательность команд
                                                               call         i2c_write                            ;
                                                               movlw  b'00000001'                        ; установить страницу команд 00
                                                              
call         i2c_write                            ;
                                                               movlw  b'01000000'                        ;
курсор по Y = 0
                                                               call         i2c_write                            ;
                                                               movlw  b'10000000'                        ;
курсор по X = 0
                                                               call         i2c_write                            ;
                                               call         b_restart_w                                     ;
                                                              
movlw  b'01000000'                        ; последовательность данных
                                                               call         i2c_write                            ;
ck_och_01                                         ; очистка банков 0-1
                                                               movlw  0x00                                      ;
                                                               call         i2c_write                            ;
                                                               decfsz   sch_s1,f                              ; уменьшения счет. циклов на 1 и проверка на 0                                                       
                                               bra                         ck_och_01                                         ; повтор
ck_och_23                                         ; очистка банков 2-3                                                   
                                                              
movlw  0x00                                      ;
                                                               call         i2c_write                            ;
                                                              
decfsz   sch_s1,f                              ; уменьшения счет. циклов на 1 и проверка на 0                                                       
                                               bra                         ck_och_23                                         ; повтор
ck_och_45                                         ; очистка банков 4-4 (иконки)                                               
                                                              
movlw  0x00                                      ;
                                                               call         i2c_write                            ;
                                                              
decfsz   sch_s1,f                              ; уменьш
ния счет. циклов на 1 и проверка на 0                                                             
                                               bra                         ck_och_45                                         ; повтор
                                                               call         b_stop                                 ; формировать бит стоп                                                                                                          
;========================================
                                                               movlw  .0                                                           ; установить курсоср в позицию 0;0
                                                              
movwf y_cursor                             ;
                                                               movlw  .0                                                           ;
                                                               movwf x_cursor                             ;
                                                               call         cursor                                  ;
                return                                                                                                                ;
;============================================================================================
;============================================================================================
load_tab                             TBLRD*+                                                            ;
Чтение TABLAT             и инкремент указателя                                           
                                                              
movff   TABLAT,sch_s1 ; загрузка счетчика количества байт в последовательности
                                                               call         b_start_w                          ; формирования начала START               - цикл запись
cikl_tab                                                                                                                             ; цикл чтения последовательности
                                                               TBLRD*+                                                            ; Чтение TABLAT и инкремент указателя         
                                                               movf     TABLAT,w                           ;                                                                            
                                                               call         i2c_write                            ; формирования передачи адреса устройства (цикл последующая запись)
                                                               decfsz   sch_s1,f                              ; уменьшения счет. циклов на 1 и проверка на 0                                                       
                                               bra                         cikl_tab                                               ; повтор
                                                               call         b_stop                                 ; формировать бит стоп
                               return                                                                                                 ;
;============================================================================================
;============================================================================================                                                              
cursor                   ; x_cursor,y_cursor        установка положения курсора
                                                               call         b_start_w                          ;
                                                               movlw  b'00000000'                        ; последовательность команд
                                                               call         i2c_write                            ;
                                                               movlw  b'00000001'                        ; установить страницу команд 00
                                                              
call         i2c_write                            ;
                                                               movlw  b'00000111'                        ;
                                                               andwf   y_cursor,w                        ;
                                                               movwf regisr                                    ;
                                                               bsf                         regisr,6                ;
                                                               movf     regisr,w                               ;
                                                               call         i2c_write                            ;
                                                               movff   x_cursor,regisr ;
                                                               bsf                         regisr,7                ;
                                                               movf     regisr,w                               ;
                                                               call         i2c_write                            ;
                                                               call         b_stop                                 ;
формировать бит стоп                            
                              
return                                                                                                 ;
;============================================================================================
;================== подпрограммы шины I2C ===================================================
;============================================================================================
i2c_idle                                ; ожидание окончания активности                     
                                                               btfsc      SSPSTAT,R_W                                  ; проверить происходит ли передача данных
                                                               goto      $-2                                                                        ; если происходит, то ожидать
                                                               movf     SSPCON2,w                                                      ; скопировать регистр в аккумулятор
                                                               andlw   0x1F                                                                     ; операцией and избавиться от 3 старших разрядов
                                                               btfss      STATUS,Z                                                           ; тестировать результат на ноль
                                                               goto      $-6                                                                        ; если не ноль, повторить тестирование
                               return
;============================================================================================
b_start_w                                          ; формирования начала START              
                                                               call         i2c_idle                                                               ; ожидание окончания активности
                                                               bsf                         SSPCON2,SEN                                                  ; формирование бита СТАРТ
                                                               btfsc      SSPCON2,SEN                                                  ; ожидание окончания формирования бита старт
                                                               goto      $-2        
; формирования передачи адреса устройства (цикл последующая запись)
                                                               call         i2c_idle                                                               ; ожидание окончания активности
                                                               bcf                         adres,0                                                               ; установить  в "0" бит 0 (признак записи)
                                                               movf     adres,w                                                                              ; загрузить адрес ведомого по шине I2C
                                                               movwf SSPBUF                                                                               ; в буфер
                                                               call         i2c_idle                                                               ; ожидание окончания активности
                                                               btfss      SSPCON2,ACKSTAT                                        ; проверка подтверждения от устройства о получении адреса
                return                                                                                                                                                ; выход если нет ошибки
                                                               bsf                         SSPCON2,PEN                                  ; нет подтвержения о приеме адреса формировать стоп
                                                               btfsc      SSPCON2,PEN                                                  ; ожидание окончания формирования бита стоп
                                                               goto      $-2                                                                                        ;
                                                               bsf                         ercode,0                                            ; выход с ошибкой "нет ответа от устройства" при попытке записи
                return
;============================================================================================
b_restart_w                      ; формирования повтоного начала
                                                               call         i2c_idle                                                               ; ожидание окончания активности
                                                               bsf                         SSPCON2,RSEN                                               ; повторный рестарт
                                                               btfsc      SSPCON2,RSEN                                               ; ожидания окончания формирования рестарта
                                                               goto      $-2        
; формирования передачи адреса устройства (цикл последующая запись)
                                                               call         i2c_idle                                                               ; ожидание окончания активности
                                                               bcf                         adres,0                                                               ; установить  в "0" бит 0 (признак записи)
                                                               movf     adres,w                                                                              ; загрузить адрес ведомого по шине I2C
                                                               movwf SSPBUF                                                                              ; в буфер
                                                               call         i2c_idle                                                               ; ожидание окончания активности
                                                               btfss      SSPCON2,ACKSTAT                                        ; проверка подтверждения от устройства о получении адреса
                return                                                                                                                                                ; выход если нет ошибки
                                                               bsf                         SSPCON2,PEN                                  ; нет подтвержения о приеме адреса формировать стоп
                                                               btfsc      SSPCON2,PEN                                                  ; ожидание окончания формирования бита стоп
                                                               goto      $-2                                                                                        ;
                                                               bsf                         ercode,0                                            ; выход с ошибкой "нет ответа от устройства" при попытке записи
                return
;============================================================================================
i2c_write                            ; формирования передачи записи данных в устройство
                                                               movwf regisr                                                                   ;
                                                               call         i2c_idle                                                               ; ожидание окончания активности
                                                               movff   regisr,SSPBUF                                  ; загрузить данные в буфер передачи              
                                                               bcf                         PIR1,SSPIF                                                         ; сброс бита окончания формирования операции шины I2C
                                                               call         i2c_idle                                                               ; ожидание окончания активности
                                                               btfss      SSPCON2,ACKSTAT                                        ; проверка подтверждения от устройства о получении адреса
                return                                                                                                                                                ; выход если нет ошибки
                                                               bsf                         SSPCON2,PEN                                  ; нет подтвержения о приеме адреса формировать стоп
                                                               btfsc      SSPCON2,PEN                                                  ; ожидание окончания формирования бита стоп
                                                               goto      $-2                                                                                        ;
                                                               bsf                         ercode,2                                            ; выход с ошибкой если нет ответа от устройства
                return
;============================================================================================
b_stop                                 ; формировать бит стоп
                                                               call         i2c_idle                                                               ; ожидание окончания активности
                                                               bsf                         SSPCON2,PEN                                                  ; формировать бит стоп
                                                               btfsc      SSPCON2,PEN                                                  ; ожидание окончания формирования бита стоп
                                                               goto      $-2                                                                                        ;
                                                               clrf         ercode                                                                ; очистить регистр ошибок
                return
;============================================================================================




;============================================================================================
;============================================================================================
;-----------------------------------------
;Осцилограф
make_wave
; загрузка 122 значений из буфера АЦП для обработки на вывод на экран
                                               lfsr         FSR2,CaptBuf                    ;Z загрузть адрес начала CaptBuf                         
                                               lfsr         FSR1,BflyBuf                     ;Y загрузть адрес начала BflyBuf
                                               movlw  LCD_W                                                ;загрузить значение счетчика (0х3A -- .58)     
                                              
movwf Cl                                                                           ;/
predA
                                               movff   POSTINC2,Al                                     ;
Чтение Z+  - > A
                                              
movff   POSTINC2,Ah                                   ;/
                 
                                               movlw  0x80                                                     ;суммировать значение А с 32768
                                               addwf   Ah,f                                                      ;преобразование в положительные значения                                           
                ;предразования данных к размеру индикатора
                ;данные в диапазоне 0-255, диапазон индикатора 0-31 (делим на 8)                             
                                              
bcf         STATUS,C                                           ;
                                               rrcf         Ah                                                                         ;AL /= 2048 (LCD Y position)
                                               bcf         STATUS,C                                           ;
                                               rrcf         Ah                                                                         ;
                                               bcf         STATUS,C                                           ;
                                               rrcf         Ah                                                                         ;/
               
                                               movff   Ah,POSTINC1                                   ;
Запись Al - > Y+
                                               decfsz   Cl,f                                                        ;Repeat times
                                               bra                         predA                                                  ;
;-----------------------------------------
                                               ;Очистка буфера для формирования рисунка осцилограммы
                                               ;очищается буфер размером 122*2, что соответствует области
                                               ;выделенной для индикации осцилограммы на LCD
                                              
movlw  (LCD_W*2)                                        ;
                                               movwf Cl                                                                           ;
                                               clrf         POSTINC1                                          ; clrf -> Y+
                                               decfsz   Cl, f                                                       ;
                                               bra         $-.4                                                                       ;/
                                               movlw  (LCD_W*2)                                        ;
                                               movwf Cl                                                                           ;
                                               clrf         POSTINC1                                          ; clrf -> Y+
                                               decfsz   Cl, f                                                       ;
                                              
bra         $-.4                                                                       ;/
;-----------------------------------------
;Вернуть указатель в начало первой строки индикатора
;указатель находиться в конце буфера очистки
                                               movlw  LCD_W                                                ; найти разницу FSR1-LCD_W -> FSR1
                                               subwf   FSR1L,f                                                ; установка указателя на начало сторки )
                                              
btfss      STATUS,C                                           ;
                                               decf       FSR1H,f                                                               ;/           
;-----------------------------------------                                       
                                               ;Преобразование данных в форму графика
                                               lfsr         FSR2,BflyBuf                     ; Z загрузть адрес начала BflyBuf
                                              
                                              
movff   INDF2,Al                                             ; Чтение Al - > Z
                                              
movff   Al,Ah                                                    ; Al->Ah
                                              
                                               movlw  .7                                                                           ; рисование положения точки
                                               andwf   Al                                                                          ; (Bl) в зависимости от данных
                                               movlw  0x80                                                     ; значение имеют только 3 младших разрядя
                                               movwf Bl                                                                           ;
                                               bra                         $+.4                                                      ; значение 128 делиться на значение Al**2
                                              
rrncf      Bl,f                                                        ;
                                               decf       Al,f                                                        ;
                                              
BC                          $-.4                                                       ;
                                              
                                               rrncf      Ah                                                                         ;определение положения строки (0 нижняя 3 верняя)
                                               rrncf      Ah                                                                         ;деление на 8
                                               rrncf      Ah                                                                         ;/
                                               movlw  .3                                                                           ;ограничение величины в диапазоне
                                               andwf   Ah                                                                         ;0-3 (количество строк в индикаторе)
                                              
                                               movlw  LCD_W                                                ;умножение текущей строки на количество точек в строке
                                               mulwf   Ah                                                                         ;для нахождения смещения первой ячейки осцилограммы
;-----------------------------------------
; нахождение кординаты первой ячейки памяти для записи
; отнимем от начала коортдинат смещение положения первой ячейки
; получаем адрес в памяти для записи данных (указатель Y)
                                              
movf     PRODL,w                                                            ; найти разницу A-D -> A
                                               subwf   FSR1L,f                                                ;
                                               movf     PRODH,w                                                           ;
                                              
subwfb                FSR1H,f                                                               ;/
; установить счетчик заисываемых ячеек (на единицу меньше)
                                              
movlw  (LCD_W-.1)                                       ;
                                               movwf Dh                                                                         ;
;-----------------------------------------
dn_l1:  
; загрузим текущее и сделующее значение для вычисления растояния между точками
; загрузка
                                               movff   POSTINC2,Cl                                     ;Z
                                               movff   INDF2,Ch                                            ;
;находим растояние
                                               movf     Ch,w                                                    ;
                                               subwf   Cl,f                                                        ;
;сохраним полученное значение в регистре Dl
                                               movff   Cl,Dl                                                      ; значение  растояния
;если величина отрицательна, преобразовать в положительную
                                               BC          $+.4                                                                      ;
                                               negf      Cl                                                                           ;
;сохранить растояние в регистре Ch и разделить на 2
                                              
movff   Cl,Ch                                                    ;
                                               bcf                         STATUS,C                                           ;
                                              
RRCF     Ch                                                                         ; значение половинного растояния
;-----------------------------------------
dn_l2:  
;Наложение полученной прорисовки точки на текущюю ячейку
                                               movff   INDF1,Al                                             ; Чтение Y  - > AL
                                              
movf     Bl,w                                                      ;
                                               iorwf     Al,f                                                        ;
                                               movff   Al,INDF1                                             ;
Чтение AL - > Y                            
;-----------------------------------------
; если Ch = 0
                                               decf       Ch,f                                                      ; уменьшить сшетчик половинного интервала
                                               btfss      STATUS,C                                           ; если выполнент перенос
                                               movf     PREINC1,w                                        ; увеличить указатель Y
;-----------------------------------------
                                               movlw  .0                                                                           ; сравнить растояние между точками равно 0
                                               cpfseq Dl                                                                          ;
                                               bra         $+.4
                               bra                         subiCL                                                                 ; если Dl=нулю
                                               btfsc      Dl,7                                                       ; если Dl отрицательно
                               bra                         lsrBL                                                                     ;
                                              
bcf                         STATUS,C                                           ;
                                               rlcf         Bl,f                                                        ;
сдвиг в лево  
                               BNZ                       subiCL                                                                 ;
                                              
                                               movlw  .1                                                                           ;
                                               movwf Bl                                                                           ;
                                              
                                               movlw  LCD_W                                                ;
                                               addwf   FSR1L,f                                                ;
                                               btfsc      STATUS,C                                           ;
                                               incf        FSR1H,f                                                               ;
                               bra                         subiCL                                                                 ;
lsrBL
                                               bcf                         STATUS,C                                           ;
                                              
rrcf         Bl,f                                                        ; сдвиг в право
                              
BNZ                       subiCL                                                                 ;
                                              
                                               movlw  0x80                                                     ;
                                               movwf Bl                                                                           ;
                                              
                                               movlw  LCD_W                                                ;
                                               subwf   FSR1L,f                                                ;
                                               btfss      STATUS,C                                           ;
                                               decf       FSR1H,f                                                               ;
subiCL
                                               decf       Cl,f                                                        ;
                                               BNC                       $+.4                                                      ;
                                               BNZ                       dn_l2                                                   ;
                                               decfsz   Dh,f                                                      ;
                                               bra                         dn_l1                                                   ;
                               return                                                                                                 ;                             
;============================================================================================
rfsh_wave                                         ;
вывод на LCD графика осцилографа
               
; настройка модуля МSSP интерфейс I2C
                                               movlw  b'00101000'                                       ; включить модуль МSSP; включить режим ведущего
                                               movwf SSPCON1                                                           ;
                                               movlw  b'10000000'                                       ; (
                                               movwf SSPSTAT                                                             ; управление длительностью фронтов в стандартном режиме
                                               movlw  .25                                                                        ; 25 скрорость 400 кГц, 99 скорость 100 кГц
                                               movwf SSPADD                                                              ;
;========================================

                                               clrf         Bl                                                                           ; инницализация счетчика цикла
                                               clrf         Bh                                                                         ;
                                               lfsr         FSR1, BflyBuf+WAV_W                                ; начало буфера осцилограммы                                          
;--------------------------------------------                                  
                                                               movlw  .0                                                                           ; установить курсоср
                                                               movwf y_cursor                                             ;
                                                              
movlw  .0                                                                           ;
                                                               movwf x_cursor                                             ;
                                                               call         cursor                                                  ;

                                                               movlw  WAV_W                              ;
                                                               movwf Cl                                                                           ;
                                                              
call         b_start_w                                          ; формирования начала START               - цикл запись
                                                               movlw  b'01000000'                                       ; команда "далее следует последовательность данных"
                                                               call         i2c_write                                            ;
;--------------------------------------------
;цикл вывода на дисплей
povt                                     
                                                               movf     POSTINC1,w                                     ;                                                                            
                                                               call         i2c_write                                            ; формирования передачи адреса устройства (цикл последующая запись)
               
;----------------------------------- коррекция курсора                                                      

                                               decfsz   Cl                                                                           ;сравнить на окончания чтения буфера                                          
                              
bra         ertwer                                
;--------------------------------------------
                                                               movlw  WAV_W                                                             ;
                                                              
movwf Cl                                                                           ;
                                                               call         b_stop                                                ; формировать бит стоп                                                                                          
                                                               incf        y_cursor,f                                          ; изменить строку
                                                               call         cursor                                                  ;
                                                              
                                                               call         b_start_w                                          ; формирования начала START               - цикл запись
                                                               movlw  b'01000000'                                       ; команда "далее следует последовательность данных"
                                                              
call         i2c_write                                            ;
;--------------------------------------------
ertwer                                                                                                                                               ;                             
                                                               incf        Bl,f                                                        ;
                                                               btfsc      STATUS,C                                           ;
                                                               incf        Bh,f                                                      ;
                                                              
movlw  HIGH (LCD_W*4)                            ;размер буфера данных 58*4=232
                                                               cpfseq  Bh                                                                         ;сравнить на окончания чтения буфера
                                               bra         povt                                                                                     ;
                                                               movlw  LOW (LCD_W*4)                             ;размер буфера данных 58*4=232
                                                               cpfseq  Bl                                                                           ;сравнить на окончания чтения буфера
                                               bra         povt                                                                                     ;
                                                               call         b_stop                                                ; формировать бит стоп
                              
return                                                                                                                ;

;============================================================================================
               
                                               ORG                      0x1200                                                 ;


inittic32
                                               db          .13,.0,0x01,b'00100000',b'00001001',b'00001100',b'00000101',b'00010010'                          
                                               db          0x01,b'00001010',b'00001000',b'00100000',b'00000101',b'11001111'       
; 13 - команд в группе
; .0 - последовательность команд
; b'00000001'(0x01) - установка страницы команд - 00
; b'00100000' - контроль настройка дисплея - режим дисплей в активном режиме, ввод – горизонтальный
; b'00001001' - выбор страницы команд - 01
; b'00001100' - режим работы дисплея - нормальный режим индикации,показ полного дисплея
; b'00000101' - режим мультиплексирования - (0;1) - 1/34
; b'00010011' система уклона 011=TIC32, 100=TIC48,120 (регулировка яркости от 0 до 4)
                                                              
; 0x01 установка страницы команд - 00
; b'00001010' выбор страницы команд - 10
; b'000010**' установка коэф. умножит. напряжения 2х
; b'00100***' температурный контроль - коэф 0 выкл
; b'00000101' режим работы умножителя диапазон низкий, умножитель включен
; b'11010000' настройка напряжения умножителя '11000100'-TIC32, '11010000'-TIC48,'11001111'-TIC120                                                                                                      

               



;============================================================================================
;End of program

                               END


За дополнительной информацией обращайтесь на Форум Invent-Systems


Для получения дополнительной информации используйте:

MAGETEX
Ukraine
Телефон: +380-50-575-98-63
Факс: +380-50-575-98-63
Интернет: invent-systems@ya.ru
 

Главная | Назад
 
Отправить сообщение для: gchernov@mail.ru с вопросами и замечаниями об этом веб-узле.
© 2007 MAGETEX
Дата изменения: 23.08.2013