Основные команды AVR-DOS

Материал из roboforum.ru Wiki
Перейти к: навигация, поиск

Основные команды AVR-DOS — список основных функций библиотеки AVR-DOS.

Диск/Директория

InitFileSystem

Читает главную загрузочную запись (MBR), таблицу разделов (Partition Sector) диска (флэш-карты) и инициализирует файловую систему.

Эта функция должна быть вызвана перед любым другим использованием системы!

bErrorCode = InitFileSystem (bPartitionNumber)

bErrorCode(Byte) Код ошибки, возвращает 0 если система успешно запущена.
bPartitionNumber(Byte) Номер раздела диска (обычно 1, но используйте 0 для дисков без загрузочной записи)

Пример вызова:

<source lang="vb"> Dim bErrorCode as Byte bErrorCode = InitFileSystem(1) If bErrorCode > 0 then Print "Error: " ; bErrorCode Else Print "Filesystem successfully initialized" End If </source>

DiskSize

Возвращает размер диска.

lSize = DiskSize ()

lSize(Long) Объем диска в КБайтах

Пример вызова:

<source lang="vb"> Dim Gbtemp1 As Byte ' scratch byte Gbtemp1 = Initfilesystem(1) ' we must init the filesystem once If Gbtemp1 > 0 Then Print #1 , "Error " ; Gbtemp1 Else Print #1 , " OK" Print "Disksize : " ; Disksize() ' show disk size in Kbytes Print "Disk free: " ; Diskfree() ' show free space too End If </source>

DiskFree

Возвращает размер свободного пространства диска.

lFreeSize = DiskFree ()

lFreeSize(Long) Размер свободной области в КБайтах

Пример вызова:

<source lang="vb">Dim Gbtemp1 As Byte ' scratch byte Gbtemp1 = Initfilesystem(1) ' we must init the filesystem once If Gbtemp1 > 0 Then Print #1 , "Error " ; Gbtemp1 Else Print #1 , " OK" Print "Disksize : " ; Disksize() ' show disk size in Kbytes Print "Disk free: " ; Diskfree() ' show free space too End If </source>

Kill

Удаляет файл с диска.
Открытый файл не может быть удален. Специальные символы(WildCards) в имени файла, применение масок не поддерживаются. Код ошибки хранится в глобальной переменной gDOSError[1].

Kill sFileName

sFileName(String) Имя файла в текущей директории[2]

Пример вызова:

<source lang="vb"> 'We can use the KILL statement to delete a file. 'A file mask is not supported Print "Kill (delete) file demo" Kill "test.txt" </source>

Dir

Возвращает имя файла, удовлетворяющее маске.

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

sFile = Dir(mask)

sFile = Dir()

SFile(String) Имя файла[2]. Строка пуста, если больше нет файлов, удовлетворяющих маске
Mask(String) Файловая маска, удовлетворяющая требованиям обычного DOS, напр. *.TXT. Маска *.* удовлетворяет всем файлам

Пример вызова:

<source lang="vb"> 'Lets have a look at the file we created Print "Dir function demo" S = Dir( "*.*") 'The first call to the DIR() function must contain a file mask ' The * means everything. ' While Len(s) > 0 ' if there was a file found Print S ; " " ; Filedate() ; " " ; Filetime() ; " " ; Filelen() ' print file , the date the fime was created/changed , the time and the size of the file S = Dir() ' get next Wend </source>

FileLen

Возвращает размер файла.

lSize = FileLen ()

lSize = FileLen (file)

lSize(Long) Размер файла в Байтах
File(String) Имя файла в текущей директории[2][3]

Пример вызова:

<source lang="vb"> Print "File demo" Print Filelen( "josef.img") ; " length" ' length of file Print Filetime( "josef.img") ; " time" ' time file was changed Print Filedate( "josef.img") ; " date" ' file date </source>

FileDateTime

Возвращает дату и время создания или последнего изменения файла.

Var = FileDateTime ()

Var = FileDateTime (file)

Var(String) Дата и время, строка не менее 17 символов
Var(Byte array) Дата и время, размер массива не менее 6 элементов (6 Байт)
Var(Numeric) Дата и время, используется внутренний формат DOS
File(String) Имя файла в текущей директории[2][3]

Пример вызова:

<source lang="vb"> ' Read and print Directory and show Filename, Date, Time, Size ' for all files matching pStr1 and create/update younger than pDays Sub Directorylist(pstr1 As String , Byval Pdays As Word) Local lFileName as String * 12 ' hold file name for print Local lwCounter as Word , lFileSizeSum as Long ' for summary Local lwNow as Word , lwDays as Word Local lSec as Byte , lMin as Byte , lHour as byte , lDay as byte , lMonth as byte , lYear as byte print "Listing of all Files matching " ; pStr1 ; " and create/last update date within " ; pdays ; " days" lwNow = SysDay() lwCounter = 0 : lFileSizeSum = 0 lFileName = Dir(pStr1) While lFileName <> "" lsec = FileDateTime() lwDays = lwNow - SysDay(lDay) ' Days between Now and last File Update; uses lDay, lMonth, lYear if lwDays <= pDays then ' days smaller than desired with parameter print lFileName ; FileDate() ; " " ; FileTime() ; " " ; filelen() incr lwCounter : lFileSizeSum = FileLen() + lFileSizeSum end if lFileName = Dir() WEnd print lwCounter ; " File(s) found with " ; lFileSizeSum ; " Byte(s)" End Sub </source>

GetAttr

Возвращает атрибуты файла.

bAttr = GetAttr ()

bAttr = GetAttr (file)

bAttr(Byte) Атрибуты файла, совместимые с DOS-форматом. Байт расшифровывается как 00ADVSHR, где биты 5-0:

A - Архивный
D - Директория
V - Volume ID(?)
S - Системный
H - Скрытый
R - Только чтение

File(String) Имя файла в текущей директории[2][3]

Пример вызова:

<source lang="vb"> Print "File demo" Print Filelen( "josef.img") ; " length" ' length of file Print Filetime( "josef.img") ; " time" ' time file was changed Print Filedate( "josef.img") ; " date" ' file date Print Bin(GetAttr(“Josef.img”)) ; “Attributes” ‘ DOS Attributes </source>

Name

Переименовывает файл в текущей директории.
Файл с новым именем не должен существовать в текущей директории, иначе команда вернет ошибку. Код ошибки можно посмотреть в глобальной переменной gbDOSError[1].

Name <strOldFilename> As <strNewFileName>

strOldFileName(String) Старое имя файла[2]
strNewFileName(String) Новое имя файла[2]

Пример вызова:

<source lang="vb"> Dim strOldFileName as String * 12 Dim strNewFileName as String * 12

strOldFileName = "Data.txt" strNewFileName = "Data.bak" Name strOldFilename As strNewFileName </source>

ChDir

Изменяет текущую директорию.
Функции Kill, Dir, ChDir, MkDir, RmDir, Name, FileLen, FileDateTime, FileDate, FileTime, GetAttr, Open, BLoad и BSave работают только в текущей директории. Обращаться к файлу с помощью составного пути запрещается!

ChDIR (strDirectoryName)

strDirectoryName(String) Путь к новой директории[4]. Допускаются следующие спецсимволы:

"." - на директорию выше
"\" - в корень диска

Пример вызова:

<source lang="vb"> Dim strDirectory as String * 12

ChDir "SubDir" ' or strDirectory = "SubDir" ChDir strDirectory

' Change to next higher directory ChDir "." ' Change to Root Directory strDirectory = "\" ChDir strDirectory </source>

MkDir

Создает каталог в текущей директории.

MkDIR (strDirectoryName)

strDirectoryName(String) Имя новой директории[4]

Пример вызова:

<source lang="vb"> Dim strDirectory as String * 12 MkDir "NewDir" ' or strDirectory = "NewDir" MkDir strDirectory </source>

RmDir

Удаляет каталог в текущей директории.

RmDIR (strDirectoryName)

strDirectoryName(String) Имя каталога для удаления[4]

Пример вызова:

<source lang="vb"> Dim strDirectory as String * 12 MkDir "NewDir" ' or strDirectory = "NewDir" MkDir strDirectory </source>

Файлы

FreeFile

Возвращает свободный идентификатор файлового потока.

bFileNumber = FreeFile()

bFileNumber(Byte) Свободный идентификатор файлового потока принадлежит множеству 128..255, используется для открытия новых файлов OPEN. Используйте числа 1..127 для пользовательских идентификаторов, чтобы избежать конфликтов имен при использованиии функций файловой системы.

Пример вызова:

<source lang="vb"> Ff = Freefile() ' get file handle Open "test.txt" For Input As #ff ' we can use a constant for the file too Print Lof(#ff) ; " length of file" Print Fileattr(#ff) ; " file mode" ' should be 1 for input Do Line Input #ff , S ' read a line ' line input is used to read a line of text from a file Print S ' print on terminal emulator Loop Until Eof(ff) <> 0 'The EOF() function returns a non-zero number when the end of the file is reached 'This way we know that there is no more data we can read Close #ff </source>

Open

Открывает устройство.

OPEN "device" for MODE As #channel

OPEN file FOR MODE as #channel

Device The default device is COM1 and you don't need to open a channel to use INPUT/OUTPUT on this device.

With the implementation of the software UART, the compiler must know to which pin/device you will send/receive the data. So that is why the OPEN statement must be used. It tells the compiler about the pin you use for the serial input or output and the baud rate you want to use. COMB.0:9600,8,N,2 will use PORT B.0 at 9600 baud with 2 stopbits.

The format for COM1 and COM2 is : COM1: or COM2:

There is no speed/baud rate parameter since the default baud rate will be used that is specified with $BAUD or $BAUD1

The format for the software UART is: COMpin:speed,8,N,stopbits[,INVERTED] Where pin is the name of the PORT-pin. Speed must be specified and stop bits can be 1 or 2. 7 bit data or 8 bit data may be used. For parity N, O or E can be used.

An optional parameter ,INVERTED can be specified to use inverted RS-232. Open "COMD.1:9600,8,N,1,INVERTED" For Output As #1 , will use pin PORTD.1 for output with 9600 baud, 1 stop bit and with inverted RS-232.

For the AVR-DOS filesystem, Device can also be a string or filename constant like

"readme.txt" or sFileName

Mode You can use BINARY or RANDOM for COM1 and COM2, but for the software UART pins, you must specify INPUT or OUTPUT

For the AVR-DOS filesystem, MODE may be INPUT, OUTPUT, APPEND or BINARY

Channel The number of the channel to open. Must be a positive constant >0

For the AVR-DOS filesystem, the channel may be a positive constant or a numeric variable. Note that the AVD-DOS filesystem uses real filehandles. The software UART does not use real file handles.

Пример вызова:

<source lang="vb"> OPEN "com1:" for binary as #1 Call test End Sub test Print #1, "test" End Sub Close #1 </source>

Close

Освобождает открытое устройство.

The statements that support the device are PRINT , INPUT and INPUTHEX , INKEY, WAITKEY. Every opened device must be closed using the CLOSE #channel statement. Of course, you must use the same channel number. The best place for the CLOSE statement is at the end of your program. The INPUT statement in combination with the software UART, will not echo characters back because there is no default associated pin for this. For the AVR-DOS filesystem, you may place the CLOSE at any place in your program. This because the filesystem supports real file handles.

OPEN "device" for MODE As #channel
...
CLOSE #channel

Device The default device is COM1 and you don't need to open a channel to use INPUT/OUTPUT on this device.

With the implementation of the software UART, the compiler must know to which pin/device you will send/receive the data. So that is why the OPEN statement must be used. It tells the compiler about the pin you use for the serial input or output and the baud rate you want to use. COMB.0:9600,8,N,2 will use PORT B.0 at 9600 baud with 2 stop bits.

The format for COM1 is : COM1:

Some chips have 2 UARTS. You can use COM2: to open the second HW UART.

The format for the software UART is: COMpin:speed,8,N,stop bits[,INVERTED] Where pin is the name of the PORT-pin. Speed must be specified and stop bits can be 1 or 2. An optional parameter ,INVERTED can be specified to use inverted RS-232. Open "COMD.1:9600,8,N,1,INVERTED" For Output As #1 , will use pin PORTD.1 for output with 9600 baud, 1 stop bit and with inverted RS-232

MODE You can use BINARY or RANDOM for COM1 and COM2, but for the software UART pins, you must specify INPUT or OUTPUT
Channel The number of the channel to open. Must be a positive constant >0

Пример вызова:

<source lang="vb"> $crystal = 10000000 'change to the value of the XTAL you have installed

Dim B As Byte

'Optional you can fine tune the calculated bit delay 'Why would you want to do that? 'Because chips that have an internal oscillator may not 'run at the speed specified. This depends on the voltage, temp etc. 'You can either change $CRYSTAL or you can use 'BAUD #1,9610

'In this example file we use the DT006 from www.simmstick.com 'This allows easy testing with the existing serial port 'The MAX232 is fitted for this example. 'Because we use the hardware UART pins we MAY NOT use the hardware UART 'The hardware UART is used when you use PRINT, INPUT or other related statements 'We will use the software UART. Waitms 100

'open channel for output Open "comd.1:19200,8,n,1" For Output As #1 Print #1 , "serial output"


'Now open a pin for input Open "comd.0:19200,8,n,1" For Input As #2 'since there is no relation between the input and output pin 'there is NO ECHO while keys are typed Print #1 , "Number" 'get a number Input #2 , B 'print the number Print #1 , B

'now loop until ESC is pressed 'With INKEY() we can check if there is data available 'To use it with the software UART you must provide the channel Do 'store in byte B = Inkey(#2) 'when the value > 0 we got something If B > 0 Then Print #1 , Chr(b) 'print the character End If Loop Until B = 27


Close #2 Close #1


'OPTIONAL you may use the HARDWARE UART 'The software UART will not work on the hardware UART pins 'so you must choose other pins 'use normal hardware UART for printing 'Print B


'When you dont want to use a level inverter such as the MAX-232 'You can specify ,INVERTED : 'Open "comd.0:300,8,n,1,inverted" For Input As #2 'Now the logic is inverted and there is no need for a level converter 'But the distance of the wires must be shorter with this End </source>


Print

Выводит параметр в RS-232 порт, также может записать строку в файл.

Используйте разделитель (;) для вывода более одного параметра. Если вы заканчиваете вывод разделителем, новая строка после вывода не создается. Процедура может использоваться только если микроконтроллер имеет железную реализацию RS-232 «(The PRINT routine can be used when you have a RS-232 interface on your uP)». RS-232 интерфейс может быть подключен к COM-порту компьютера через преобразователь уровней TTL(подробнее), в этом случае вы можете использовать встроенный терминал, чтобы следить за сообщениями устройства. AVR-DOS также поддерживает PRINT процедуру, но на диск могут быть записаны только строки «(The AVR-DOS filesystem also supports PRINT. But in that case, only strings can be written to disk)».


PRINT var ; " constant"

Var(...) Переменные или константы для вывода

Пример вызова:

<source lang="vb"> Dim A As Byte , B1 As Byte , C As Integer , S As String * 4 A = 1 Print "print variable a " ; A Print 'new line Print "Text to print." 'constant to print


B1 = 10 Print Hex(b1) 'print in hexa notation C = &HA000 'assign value to c% Print Hex(c) 'print in hex notation Print C 'print in decimal notation

C = -32000 Print C Print Hex(c) Rem Note That Integers Range From -32767 To 32768 End </source>

Write

Записывает параметры в открытый файловый поток.

Для записи переменной используется ASCII представление, т.е. файл будет выглядеть как текст. Вы можете записывать переменные в бинарном представлении используя команду PUT, в этом случае файлы не будут содержать неотображаемых символов. Строки обособляются символом (").

Write #ch , data [,data1]

Data , data1 Переменные или константы для вывода
Ch(Byte) Идентификационный номер открытого файлового потока[5]

Множественные переменные разделяются запятыми, например: <source lang="vb"> Dim S as String * 10 , W as Word S="hello" : W = 100 OPEN "test.txt" For OUTPUT as #1 WRITE #1, S , W CLOSE #1</source> Файл будет выглядеть как: "hello",100. Используйте команду INPUT чтобы прочитать переменные из файла.

Пример вызова:

<source lang="vb"> Dim S As string * 10 , W As Word ,L As Long S = "write" Open "write.dmo" For Output As #2 Write #2 , S , W , L ' write is also supported Close #2 Open "write.dmo" For Input As #2 Input #2 , S , W , L ' write is also supported Close #2 Print S ; " " ; W ; " " ; L </source>

Input

Считывает данные из RS-232, также может считывать данные из файла.

Считывание данных из RS-232 может использоваться только если микроконтроллер имеет аппаратную реализацию интерфейса. «(ещё пачка материала из write)». Вы можете использовать директиву prompt для вывода сообщения перед запросом переменной. Данные в файле должны иметь ASCII представление (команда write). Данные автоматически конвертируются из строкового формата в формат данных аргумента. Директива prompt при чтении зи файла не поддерживается.

INPUT [" prompt" ] , var [ , varn ]

INPUT #ch, var [ , varn ]

Prompt(String) Опциональная строковая константа, выводимая перед запросом данных по RS-232
Var,varn(...) Переменные, в которые записываются данные из файла или RS-232
Ch(Byte) Идентификационный номер открытого файлового потока[5]

Пример вызова:

<source lang="vb">'To use another baudrate and crystalfrequency use the 'metastatements $BAUD = and $CRYSTAL = $baud = 9600 'try 1200 baud for example

$crystal = 4000000 '12 MHz Dim V As Byte , B1 As Byte Dim C As Integer , D As Byte Dim S As String * 15

Input "Use this to ask a question " , V Input B1 'leave out for no question

Input "Enter integer " , C Print C

Inputhex "Enter hex number (4 bytes) " , C Print C Inputhex "Enter hex byte (2 bytes) " , D Print D

Input "More variables " , C , D Print C ; " " ; D

Input C Noecho 'supress echo

Input "Enter your name " , S Print "Hello " ; S

Input S Noecho 'without echo Print S End

Dim X As Byte Echo On Inputhex "Enter a number " , X 'ask for input Echo Off Inputhex "Enter a number " , X 'ask for input Echo On End </source>

Line Input

Читает строку из открытого файлового потока.

Вызов доступен только если файл открыт в режиме открытия INPUT. Процедура работает только со строками, рекомендуется применять для работы с текстовыми файлами.

LineInput #bFileNumber, sLineText

BfileNumber(Byte) Идентификационный номер открытого файлового потока[5]
SlineText(String) Переменная для прочитанной строки.

Пример вызова:

<source lang="vb">'Ok we want to check if the file contains the written lines Ff = Freefile() ' get file handle Open "test.txt" For Input As #ff ' we can use a constant for the file too Print Lof(#ff) ; " length of file" Print Fileattr(#ff) ; " file mode" ' should be 1 for input Do Line Input #ff , S ' read a line ' line input is used to read a line of text from a file Print S ' print on terminal emulator Loop Until Eof(ff) <> 0 'The EOF() function returns a non-zero number when the end of the file is reached 'This way we know that there is no more data we can read Close #ff </source>

Свойства файла

EOF

Возвращает статус конца файла.

bFileEOFStatus = EOF(#bFileNumber)

bFileEOFStatus(Byte) Состояние конца файла:

0 - Конец файла не достигнут
1..255 - Конец файла достигнут
В случае ошибки (например, неверный идентификатор файлового потока) функция также возвращает 1..255 (конец файла достигнут)

bFileNumber(Byte) Идентификационный номер открытого файлового потока[5]

Пример вызова:

<source lang="vb"> Ff = Freefile() ' get file handle Open "test.txt" For Input As #ff ' we can use a constant for the file too Print Lof(#ff) ; " length of file" Print Fileattr(#ff) ; " file mode" ' should be 1 for input Do Line Input #ff , S ' read a line ' line input is used to read a line of text from a file Print S ' print on terminal emulator Loop Until Eof(ff) <> 0 'The EOF() function returns a non-zero number when the end of the file is reached 'This way we know that there is no more data we can read Close #ff </source>

LOF

Возвращает размер открытого файла в Байтах.

lFileLength = LOF (#bFileNumber)

bFileNumber(Byte) Идентификационный номер открытого файлового потока[5]
LFileLength(Long) Длина файла в Байтах (нумерация с 1), если возникла ошибка, то возвращает 0, код ошибки содержит глобальная переменная gbDOSError[1].

Пример вызова:

<source lang="vb"> 'open the file in BINARY mode Open "test.biN" For Binary As #2 Put #2 , B ' write a byte Put #2 , W ' write a word Put #2 , L ' write a long Ltemp = Loc(#2) + 1 ' get the position of the next byte Print Ltemp ; " LOC" ' store the location of the file pointer Print Lof(#2) ; " length of file" Print Fileattr(#2) ; " file mode" ' should be 32 for binary Put #2 , Sn ' write a single Put #2 , Stxt ' write a string

Flush #2 ' flush to disk Close #2 </source>


Сноски

  1. 1 2 3 Коды ошибок
  2. 1 2 3 4 5 6 7 8.3: имя - 8 символов, расширение - 3 символа, разделитель(точка) - 1 символ, всего не более 12 символов
  3. 1 2 3 Если не указано, параметром считается последний файл, выбранный с помощью DIR
  4. 1 2 3 Не более 8 символов
  5. 1 2 3 4 5 Принадлежит целому множеству 0..255, может быть переменной или константой. Используйте числа 1..127 для пользовательских идентификаторов. Для получения свободного идентификатора используйте функцию FreeFile(возвращает 128..255)

См. также