Дополнительные команды AVR-DOS — различия между версиями

Материал из roboforum.ru Wiki
Перейти к: навигация, поиск
(доделал секцию диск/директория)
м (См. также)
 
(не показано 89 промежуточных версий этого же участника)
Строка 1: Строка 1:
[[Категория:МиниБот]]
+
[[Категория:AVR-DOS]]
'''Список команд AVR-DOS''' — нижеследующий список команд для операционной системы [[Запускаем AVR-DOS на SD-Card МиниБота|AVR-DOS]].
+
'''Список команд AVR-DOS''' — список функций библиотеки [[AVR-DOS]].
  
 
== Диск/Директория ==
 
== Диск/Директория ==
=== InitFileSystem ===
+
=== FileDate ===
Читает Master boot record и partition boot record (Sector) диска(флэш-карты) и инициализирует файловую систему.
+
Возвращает дату создания или последнего изменения файла.
  
'''Эта функция должна быть вызвана перед любым другим использованием системы!'''
+
<code>sDate = FileDate ()</code>
  
<code>bErrorCode = InitFileSystem (bPartitionNumber)</code>
+
<code>sDate = FileDate (file)</code>
  
 
{| class="wikitable"
 
{| class="wikitable"
| bErrorCode(Byte)
+
| sDate(String)
| Код ошибки, возвращает 0 если система успешно запущена.
+
| Дата создания или изменения(?) файла
 
|-
 
|-
| bPartitionNumber(Byte)
+
| File(String)
| Partitionnumber on the Flashcard Drive (normally 1, but use 0 on mediums without Master boot record)
+
| Имя файла в текущей директории<ref name="dosnames">'''8.3''': имя - 8 символов, расширение - 3 символа, разделитель(точка) - 1 символ, всего не более 12 символов</ref><ref name="dirnames">Если не указано, параметром считается последний файл, выбранный с помощью [[Основные команды AVR-DOS#Dir|DIR]]</ref>
 
|}
 
|}
  
 
Пример вызова:
 
Пример вызова:
  
<pre>Dim bErrorCode as Byte
+
<source lang="vb"> Print "File demo"
bErrorCode = InitFileSystem(1)
+
Print Filelen( "josef.img") ; " length" ' length of file
If bErrorCode > 0 then
+
Print Filetime( "josef.img") ; " time" ' time file was changed
Print "Error: " ; bErrorCode
+
Print Filedate( "josef.img") ; " date" ' file date
Else
+
</source>
Print "Filesystem successfully initialized"
 
End If
 
</pre>
 
  
=== DiskSize ===
+
=== FileTime ===
Возвращает размер диска.
+
Возвращает время создания или последнего изменения файла.
  
<code>lSize = DiskSize ()</code>
+
<code>sTime = FileTime ()</code>
 +
 
 +
<code>sTime = FileTime (file)</code>
  
 
{| class="wikitable"
 
{| class="wikitable"
| lSize(Long)
+
| sTime(String)
| Объем диска в КБайтах
+
| Время создания или изменения(?) файла
 +
|-
 +
| File(String)
 +
| Имя файла в текущей директории<ref name="dosnames">'''8.3''': имя - 8 символов, расширение - 3 символа, разделитель(точка) - 1 символ, всего не более 12 символов</ref><ref name="dirnames">Если не указано, параметром считается последний файл, выбранный с помощью [[Основные команды AVR-DOS#Dir|DIR]]</ref>
 
|}
 
|}
  
 
Пример вызова:
 
Пример вызова:
  
<pre>Dim Gbtemp1 As Byte ' scratch byte
+
<source lang="vb"> Print "File demo"
Gbtemp1 = Initfilesystem(1) ' we must init the filesystem once
+
Print Filelen( "josef.img") ; " length" ' length of file
If Gbtemp1 > 0 Then
+
Print Filetime( "josef.img") ; " time" ' time file was changed
Print #1 , "Error " ; Gbtemp1
+
Print Filedate( "josef.img") ; " date" ' file date
Else
+
</source>
Print #1 , " OK"
+
 
Print "Disksize : " ; Disksize() ' show disk size in Kbytes
+
== Файлы ==
Print "Disk free: " ; Diskfree() ' show free space too
+
=== Flush ===
End If
+
Скидывает кеш текущего файла на диск и обновляет информацию раздела, директории.
</pre>
 
  
=== DiskFree ===
+
Процедура осуществляет запись всей несохраненной информации о/в файле на диск. Обычно запись на диск производится при закрытии файлового потока или переходе на другой сектор файла, однако вы можете поменять параметр [[Окружение AVR-DOS#Конфигурация файловой системы|cFATDirSaveAtEnd]], в этом случае вам придется принудительно сбрасывать изменения файла на диск.
Возвращает размер свободного пространства диска.
 
  
<code>lFreeSize = DiskFree ()</code>
+
<code>Flush #bFileNumber</code>
 +
 
 +
<code>Flush</code>
  
 
{| class="wikitable"
 
{| class="wikitable"
| lFreeSize(Long)
+
| BFileNumber(Byte)
| Размер свободной области в КБайтах
+
| Идентификационный номер открытого файлового потока<ref name="identnumber">Принадлежит целому множеству 0..255, может быть переменной или константой. Используйте числа 1..127 для пользовательских идентификаторов. Для получения свободного идентификатора используйте функцию [[Основные команды AVR-DOS#FreeFile|FreeFile]](возвращает 128..255)</ref>. Если не указан, то изменения всех открытых файлов сбрасываются на диск.
 
|}
 
|}
  
 
Пример вызова:
 
Пример вызова:
  
<pre>Dim Gbtemp1 As Byte ' scratch byte
+
<source lang="vb"> $include "startup.inc"
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
 
</pre>
 
  
=== Kill ===
+
'open the file in BINARY mode
Удаляет файл с диска. Открытый файл не может быть удален. Специальные символы(WildCards) в имени файла, маски не поддерживаются. Код ошибки хранится в глобальной переменной gDOSError.
+
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
  
<code>Kill sFileName</code>
+
Flush #2 ' flush to disk
 +
Close #2
 +
</source>
  
{| class="wikitable"
+
=== Get ===
| sFileName(String)
+
Reads a byte from the hardware or software UART. Reads data from a file opened in BINARY mode.
| Имя файла в текущей директории
 
|}
 
  
Пример вызова:
+
GET in combination with the software/hardware UART is provided for compatibility with BASCOM-8051. It reads one byte.
 +
GET in combination with the AVR-DOS filesystem is very flexible and versatile. It works on files opened in BINARY mode and you can reads all data types.
 +
By default you only need to provide the variable name. When the variable is a byte, 1 byte wil be read. When the variable is a word or integer, 2 bytes will be read. When the variable is a long or single, 4 bytes will be read. When the variable is a string, the number of bytes that will be read is equal to the dimensioned size of the string. DIM S as string * 10 , would read 10 bytes.
 +
Note that when you specify the length for a string, the maximum length is 255. The maximum length for a non-string array is 65535.
 +
<source lang="vb"> Example :  
 +
GET #1 , var ,,2 ‘ read 2 bytes, start at current position
 +
GET #1, var , PS ‘ start at position stored in long PS
 +
GET #1, var , PS, 2 ‘ start at position stored in long PS and read 2 bytes</source>
  
<pre>'We can use the KILL statement to delete a file.
+
<code>GET #channel, var</code>
'A file mask is not supported
 
Print "Kill (delete) file demo"
 
Kill "test.txt"
 
</pre>
 
  
=== Dir ===
+
<code>GET #channel, var , [pos] [, length]</code>
Возвращает имя файла, удовлетворяющее маске.
 
 
 
Первый вызов функции содержит маску. Все последующие вызовы совершаются без маски. Фактически, когда вы хотите получить имя следующего файла в данной директории, удовлетворяющее маске, вы должны вызывать вариант функции без параметров после первого вызова.
 
 
 
<code>sFile = Dir(mask)</code>
 
 
 
<code>sFile = Dir()</code>
 
  
 
{| class="wikitable"
 
{| class="wikitable"
| SFile(String)
+
| #channel(...)
| Имя файла. Строка пуста, если больше нет файлов, удовлетворяющих маске
+
| A channel number, which identifies an opened file. This can be a hard coded constant or a variable
 +
|-
 +
| Var(...)
 +
| The variable or variable array that will be assigned with the data from the file
 +
|-
 +
| Pos(...)
 +
| This is an optional parameter that may be used to specify the postion where the reading must start from. This must be a long variable
 
|-
 
|-
| Mask(String)
+
| Length(...)
| Файловая маска, удовлетворяющая требованиям обычного DOS, напр. *.TXT. Маска *.* удовлетворяет всем файлам
+
| This is an optional parameter that may be used to specify how many bytes must be read from the file.
 
|}
 
|}
  
 
Пример вызова:
 
Пример вызова:
  
<pre>'Lets have a look at the file we created
+
<source lang="vb"> 'for the binary file demo we need some variables of different types
Print "Dir function demo"
+
Dim B As Byte , W As Word , L As Long , Sn As Single , Ltemp As Long
S = Dir( "*.*")
+
Dim Stxt As String * 10
'The first call to the DIR() function must contain a file mask
+
B = 1 : W = 50000 : L = 12345678 : Sn = 123.45 : Stxt = "test"
' 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
 
</pre>
 
  
=== FileLen ===
+
'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 Seek(#2) ; " = LOC+1"
  
<code>lSize = FileLen ()</code>
+
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
  
<code>lSize = FileLen (file)</code>
+
Flush #2 ' flush to disk
 +
Close #2
  
{| class="wikitable"
+
'now open the file again and write only the single
| lSize(Long)
+
Open "test.bin" For Binary As #2
| Размер файла в Байтах
+
L = 1 'specify the file position
|-
+
B = Seek(#2 , L) ' reset is the same as using SEEK #2,L
| File(String)
+
Get #2 , B ' get the byte
| Имя файла в текущей директории. Если не указано, параметром считается последний файл, выбранный с помощью DIR()
+
Get #2 , W ' get the word
|}
+
Get #2 , L ' get the long
 +
Get #2 , Sn ' get the single
 +
Get #2 , Stxt ' get the string
 +
Close #2
 +
</source>
  
Пример вызова:
+
=== Put ===
 +
Writes a byte to the hardware or software UART. Writes data to a file opened in BINARY mode.
  
<pre>Print "File demo"
+
PUT in combination with the software/hardware UART is provided for compatibility with BASCOM-8051. It writes one byte
Print Filelen( "josef.img") ; " length" ' length of file
+
PUT in combination with the AVR-DOS filesystem is very flexible and versatile. It works on files opened in BINARY mode and you can write all data types.
Print Filetime( "josef.img") ; " time" ' time file was changed
+
By default you only need to provide the variable name. When the variable is a byte, 1 byte wil be written. When the variable is a word or integer, 2 bytes will be written. When the variable is a long or single, 4 bytes will be written. When the variable is a string, the number of bytes that will be written is equal to the dimensioned size of the string. DIM S as string * 10 , would write 10 bytes.
Print Filedate( "josef.img") ; " date" ' file date
+
Note that when you specify the length for a string, the maximum length is 255. The maximum length for a non-string array is 65535.
</pre>
+
Example:
 +
<source lang="vb"> PUT #1, var
 +
PUT #1, var , , 2 ‘ write 2 bytes at default position
 +
PUT #1, var ,PS, 2 ‘ write 2 bytes at location storied in variable PS</source>
  
=== FileDate ===
+
<code>PUT #channel, var</code>
Возвращает дату создания или изменения(?) файла.
 
  
<code>sDate = FileDate ()</code>
+
<code>PUT #channel, var ,[pos] [,length]</code>
 
 
<code>sDate = FileDate (file)</code>
 
  
 
{| class="wikitable"
 
{| class="wikitable"
| sDate(String)
+
| #channel(...)
| Дата создания или изменения(?) файла
+
| A channel number, which identifies an opened file. This can be a hard coded constant or a variable.
 +
|-
 +
| Var(...)
 +
| The variable or variable array that will be written to the file
 +
|-
 +
| Pos(...)
 +
| This is an optional parameter that may be used to specify the postion where the data must be written to. This must be a long variable.
 
|-
 
|-
| File(String)
+
| Length(...)
| Имя файла в текущей директории. Если не указано, параметром считается последний файл, выбранный с помощью DIR()
+
| This is an optional parameter that may be used to specify how many bytes must be written to the file.
 
|}
 
|}
  
 
Пример вызова:
 
Пример вызова:
  
<pre>Print "File demo"
+
<source lang="vb"> 'for the binary file demo we need some variables of different types
Print Filelen( "josef.img") ; " length" ' length of file
+
Dim B As Byte , W As Word , L As Long , Sn As Single , Ltemp As Long
Print Filetime( "josef.img") ; " time" ' time file was changed
+
Dim Stxt As String * 10
Print Filedate( "josef.img") ; " date" ' file date
+
B = 1 : W = 50000 : L = 12345678 : Sn = 123.45 : Stxt = "test"
</pre>
 
 
 
=== FileTime ===
 
Возвращает время создания или изменения(?) файла.
 
  
<code>sTime = FileTime ()</code>
+
'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 Seek(#2) ; " = LOC+1"
  
<code>sTime = FileTime (file)</code>
+
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
  
{| class="wikitable"
+
Flush #2 ' flush to disk
| sTime(String)
+
Close #2
| Время создания или изменения(?) файла
 
|-
 
| File(String)
 
| Имя файла в текущей директории. Если не указано, параметром считается последний файл, выбранный с помощью DIR()
 
|}
 
  
Пример вызова:
+
'now open the file again and write only the single
 +
Open "test.bin" For Binary As #2
 +
L = 1 'specify the file position
 +
B = Seek(#2 , L) ' reset is the same as using SEEK #2,L
 +
Get #2 , B ' get the byte
 +
Get #2 , W ' get the word
 +
Get #2 , L ' get the long
 +
Get #2 , Sn ' get the single
 +
Get #2 , Stxt ' get the string
 +
Close #2
 +
</source>
  
<pre>Print "File demo"
+
=== Seek ===
Print Filelen( "josef.img") ; " length" ' length of file
+
Function: Returns the position of the next Byte to be read or written.
Print Filetime( "josef.img") ; " time" ' time file was changed
+
Statement: Sets the position of the next Byte to be read or written.
Print Filedate( "josef.img") ; " date" ' file date
 
</pre>
 
  
=== FileDateTime ===
+
This function returns the position of the next Byte to be read or written. If an error occures, 0 is returned. Check DOS-Error in variable gbDOSError<ref name="OkrDOS">[[Окружение AVR-DOS#Коды ошибок|Коды ошибок]]</ref>..
Возвращает дату и время создания или изменения(?) файла.
+
The statetement also returns an error in the gbDOSerror variable in the event that an error occurs.
 +
You can for example not set the fileposition behinds the filesize.
 +
In QB/VB the file is filled with 0 bytes when you set the filepointer behind the size of the file. For embedded systems this does not seem a good idea.
 +
Seek and Loc seems to do the same function, but take care : the seek function will return the position of the next read/write, while the Loc function returns the position of the last read/write. You may say that Seek = Loc+1.
 +
'''Difference with QB'''
 +
In QB/VB you can use seek to make the file bigger. When a file is 100 bytes long, setting the filepointer to 200 will increase the file with 0 bytes. By design this is not the case in AVR-DOS.
  
<code>Var = FileDateTime ()</code>
+
<code>Function: NextReadWrite = Seek (#bFileNumber)
  
<code>Var = FileDateTime (file)</code>
+
Statement: Seek #bFileNumber, NewPos)</code>
  
 
{| class="wikitable"
 
{| class="wikitable"
| Var(String)
+
| bFileNumber(Byte)
| Время создания или изменения(?) файла
+
| Filenumber, which identifies an opened file
 
|-
 
|-
| File(String)
+
| NextReadWrite(Long)
| When the target variable is a string, it must be dimensioned with a length of at least 17 bytes.
+
| A Long Variable, which is assigned with the Position of the next Byte to be read or written (1-based)
 
|-
 
|-
| File(Byte array)
+
| NewPos(Long)
| When the target variable is a byte array, the array size must be at least 6 bytes.
+
| A Long variable that holds the new position the filepointer must be set too.
|-
 
| File(Numeric)
 
| When you use a numeric variable, the internal file date and time format will be used.
 
 
|}
 
|}
  
 
Пример вызова:
 
Пример вызова:
  
<pre>' Read and print Directory and show Filename, Date, Time, Size
+
<source lang="vb"> Open "test.biN" For Binary As #2
' for all files matching pStr1 and create/update younger than pDays
+
Put #2 , B ' write a byte
Sub Directorylist(pstr1 As String , Byval Pdays As Word)
+
Put #2 , W ' write a word
Local lFileName as String * 12 ' hold file name for print
+
Put #2 , L ' write a long
Local lwCounter as Word , lFileSizeSum as Long ' for summary
+
Ltemp = Loc(#2) + 1 ' get the position of the next byte
Local lwNow as Word , lwDays as Word
+
Print Ltemp ; " LOC" ' store the location of the file pointer
Local lSec as Byte , lMin as Byte , lHour as byte , lDay as byte , lMonth as byte , lYear as byte
+
Print Seek(#2) ; " = LOC+1"  
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
 
</pre>
 
  
=== GetAttr ===
+
Close #2
Возвращает атрибуты файла.
 
  
<code>bAttr = FileDate ()</code>
+
'now open the file again and write only the single
 +
Open "test.bin" For Binary As #2
 +
Seek #2 , Ltemp ' set the filepointer
 +
Sn = 1.23 ' change the single value so we can check it better
 +
Put #2 , Sn = 1 'specify the file position
 +
Close #2
 +
</source>
  
<code>bAttr = FileDate (file)</code>
+
== Свойства файла ==
 +
=== LOC ===
 +
Returns the position of last read or written Byte of the file.
  
{| class="wikitable"
+
This function returns the position of the last read or written Byte. If an error occurs, 0 is returned. Check DOS-Error in variable gbDOSError<ref name="OkrDOS">[[Окружение AVR-DOS#Коды ошибок|Коды ошибок]]</ref>.. If the file position pointer is changed with the command SEEK, this function can not be used till the next read/write operation.
| bAttr(Byte)
+
'''Difference with QB'''
| Атрибуты файла, совместимые с DOS-форматом. Байт расшифровывается как 00ADVSHR, где биты 5-0:<br />
+
This function differs from QB. In QB the byte position is divided by 128.
A=Archiv<br />
 
D=Directory<br />
 
V=Volume ID<br />
 
S=System<br />
 
H=Hidden<br />
 
R=Read Only<br />
 
|-
 
| File(String)
 
| Имя файла в текущей директории. Если не указано, параметром считается последний файл, выбранный с помощью DIR()
 
|}
 
  
Пример вызова:
+
<code>lLastReadWritten = Loc (#bFileNumber)</code>
 
 
<pre>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
 
</pre>
 
 
 
=== Name ===
 
Переименовывает файл в текущей директории. Файл с новым именем не должен существовать в текущей директории, иначе команда вернет ошибку. Код ошибки можно посмотреть в глобальной переменной gbDOSError.
 
 
 
<code>Name <strOldFilename> As <strNewFileName></code>
 
  
 
{| class="wikitable"
 
{| class="wikitable"
| strOldFileName(String)
+
| bFileNumber(Byte)
| Старое имя файла
+
| Filenumber, which identifies an opened file
 
|-
 
|-
| strNewFileName(String)
+
| lLastReadWritten(Long)
| Новое имя файла
+
| Variable, whichsigned with the Position of last read or written Byte (1-based)
 
|}
 
|}
  
 
Пример вызова:
 
Пример вызова:
  
<pre>Dim strOldFileName as String * 12
+
<source lang="vb"> 'open the file in BINARY mode
Dim strNewFileName as String * 12
+
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
  
strOldFileName = "Data.txt"
+
Flush #2 ' flush to disk
strNewFileName = "Data.bak"
+
Close #2
Name strOldFilename As strNewFileName
+
</source>
</pre>
 
  
=== ChDir ===
+
=== FileAttr ===
Изменяет текущую директорию.<br />
+
Возвращает [[Окружение AVR-DOS#Использование команд ввода-вывода в различных режимах|режим открытия]] файлового потока.
'''Функции Kill, Dir, ChDir, MkDir, RmDir, Name, FileLen, FileDateTime, FileDate, FileTime, GetAttr, Open, BLoad и BSave работают только в текущей директории. Обращаться к файлу с помощью составного пути запрещается'''
 
  
<code>ChDIR (strDirectoryName)</code>
+
<code>bFileAttribut = FileAttr (bFileNumber)</code>
  
 
{| class="wikitable"
 
{| class="wikitable"
| strDirectoryName(String)
+
| bFileAttribut(Long)
| Путь к новой директории, длина не более 8 символов. Допускаются следующие спецсимволы:<br />
+
| Режим:
"." - на директорию выше<br />
+
'''1''' - INPUT<br/>
"\" - в корень диска
+
'''2''' - OUTPUT<br/>
 +
'''8''' - APPEND<br/>
 +
'''32''' - BINARY
 +
|-
 +
| bFileNumber(Byte)
 +
| Идентификационный номер открытого файлового потока<ref name="identnumber">Принадлежит целому множеству 0..255, может быть переменной или константой. Используйте числа 1..127 для пользовательских идентификаторов. Для получения свободного идентификатора используйте функцию [[#FreeFile|FreeFile]](возвращает 128..255)</ref>
 
|}
 
|}
  
 
Пример вызова:
 
Пример вызова:
  
<pre>Dim strDirectory as String * 12
+
<source lang="vb"> 'open the file in BINARY mode
 +
Open "test.biN" For Binary As #2
 +
Print Fileattr(#2) ; " file mode" ' should be 32 for binary
 +
Put #2 , Sn ' write a single
 +
Put #2 , Stxt ' write a string
 +
Close #2
 +
</source>
  
ChDir "SubDir"
+
== Другие ==
' or
+
=== Bload ===
strDirectory = "SubDir"
+
Writes the Content of a File into SRAM.
ChDir strDirectory
 
  
' Change to next higher directory
+
This function writes the content of a file to a desired space in SRAM. A free handle is needed for this function.
ChDir "."
 
' Change to Root Directory
 
strDirectory = "\"
 
ChDir strDirectory
 
</pre>
 
  
=== MkDir ===
+
<code>BLoad sFileName, wSRAMPointer</code>
Создает каталог в текущей директории.
 
 
 
<code>MkDIR (strDirectoryName)</code>
 
  
 
{| class="wikitable"
 
{| class="wikitable"
| strDirectoryName(String)
+
| sFileName(Long)
| Имя новой директории, не более 8 символов
+
| Name of the File to be read
 +
|-
 +
| wSRAMPointer(Word)
 +
| Variable, which holds the SRAM Address to which the content of the file should be written
 
|}
 
|}
  
 
Пример вызова:
 
Пример вызова:
  
<pre>Dim strDirectory as String * 12
+
<source lang="vb"> 'now the good old bsave and bload
MkDir "NewDir"
+
Dim Ar(100) As Byte , I As Byte
' or
+
For I = 1 To 100
strDirectory = "NewDir"
+
Ar(i) = I ' fill the array
MkDir strDirectory
+
Next
</pre>
 
 
 
=== RmDir ===
 
Удаляет каталог в текущей директории.
 
  
<code>RmDIR (strDirectoryName)</code>
+
Wait 2
  
{| class="wikitable"
+
W = Varptr(ar(1))
| strDirectoryName(String)
+
Bsave "josef.img" , W , 100
| Имя каталога для удаления, не более 8 символов
+
For I = 1 To 100
|}
+
Ar(i) = 0 ' reset the array
 +
Next
  
Пример вызова:
+
Bload "josef.img" , W ' Josef you are amazing !
  
<pre>Dim strDirectory as String * 12
+
For I = 1 To 10
MkDir "NewDir"
+
Print Ar(i) ; " " ;
' or
+
Next
strDirectory = "NewDir"
+
Print
MkDir strDirectory
+
</source>
</pre>
 
  
== Файлы ==
+
=== Bsave ===
=== FreeFile ===
+
Save a range in SRAM to a Fileю
=== Open ===
 
Открывает устройство
 
  
<code>OPEN "device" for MODE As #channel</code>
+
This function writes a range from the SRAM to a file. A free file handle is needed for this function.
  
<code>OPEN file FOR MODE as #channel</code>
+
<code>BSave sFileName, wSRAMPointer, wLength</code>
  
 
{| class="wikitable"
 
{| class="wikitable"
| Device
+
| sFileName(Long)
| The default device is COM1 and you don't need to open a channel to use INPUT/OUTPUT on this device.
+
| Name of the File to be written
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
+
| wSRAMPointer(Word)
| You can use BINARY or RANDOM for COM1 and COM2, but for the software UART pins, you must specify INPUT or OUTPUT.
+
| Variable, which holds the SRAM Address, from where SRAM should be written to a File
 
 
For the AVR-DOS filesystem, MODE may be INPUT, OUTPUT, APPEND or BINARY.
 
 
|-
 
|-
| Channel
+
| wLength(Word)
| The number of the channel to open. Must be a positive constant >0.
+
| Count of Bytes from SRAM, which should be written to the file
 
 
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.
 
 
|}
 
|}
  
 
Пример вызова:
 
Пример вызова:
  
<pre>OPEN "com1:" for binary as #1
+
<source lang="vb">'now the good old bsave and bload
Call test
+
Dim Ar(100) As Byte , I As Byte
End
+
For I = 1 To 100
Sub test
+
Ar(i) = I ' fill the array
Print #1, "test"
+
Next
End Sub
+
 
Close #1
+
Wait 2
</pre>
 
  
=== Close ===
+
W = Varptr(ar(1))
=== Flush ===
+
Bsave "josef.img" , W , 100
=== Print ===
+
For I = 1 To 100
=== Write ===
+
Ar(i) = 0 ' reset the array
=== Input ===
+
Next
=== Line Input ===
+
 
=== Get ===
+
Bload "josef.img" , W ' Josef you are amazing !
=== Put ===
 
=== Seek ===
 
  
== Свойства файла ==
+
For I = 1 To 10
=== EOF ===
+
Print Ar(i) ; " " ;
=== LOC ===
+
Next
=== LO ===
+
Print
=== FileAttr ===
+
</source>
  
== Другие ==
+
== Сноски ==
=== Bload ===
+
<references />
=== Bsave ===
 
  
 
== См. также ==
 
== См. также ==
* [[Запускаем AVR-DOS на SD-Card МиниБота]]
+
* [[AVR-DOS]]
* [http://members.aon.at/voegel/index.html Официальная страница AVR-DOS]
+
* [[Основные команды AVR-DOS]]

Текущая версия на 08:29, 9 января 2009

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

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

FileDate

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

sDate = FileDate ()

sDate = FileDate (file)

sDate(String) Дата создания или изменения(?) файла
File(String) Имя файла в текущей директории[1][2]

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

<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>

FileTime

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

sTime = FileTime ()

sTime = FileTime (file)

sTime(String) Время создания или изменения(?) файла
File(String) Имя файла в текущей директории[1][2]

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

<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>

Файлы

Flush

Скидывает кеш текущего файла на диск и обновляет информацию раздела, директории.

Процедура осуществляет запись всей несохраненной информации о/в файле на диск. Обычно запись на диск производится при закрытии файлового потока или переходе на другой сектор файла, однако вы можете поменять параметр cFATDirSaveAtEnd, в этом случае вам придется принудительно сбрасывать изменения файла на диск.

Flush #bFileNumber

Flush

BFileNumber(Byte) Идентификационный номер открытого файлового потока[3]. Если не указан, то изменения всех открытых файлов сбрасываются на диск.

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

<source lang="vb"> $include "startup.inc"

'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>

Get

Reads a byte from the hardware or software UART. Reads data from a file opened in BINARY mode.

GET in combination with the software/hardware UART is provided for compatibility with BASCOM-8051. It reads one byte. GET in combination with the AVR-DOS filesystem is very flexible and versatile. It works on files opened in BINARY mode and you can reads all data types. By default you only need to provide the variable name. When the variable is a byte, 1 byte wil be read. When the variable is a word or integer, 2 bytes will be read. When the variable is a long or single, 4 bytes will be read. When the variable is a string, the number of bytes that will be read is equal to the dimensioned size of the string. DIM S as string * 10 , would read 10 bytes. Note that when you specify the length for a string, the maximum length is 255. The maximum length for a non-string array is 65535. <source lang="vb"> Example : GET #1 , var ,,2 ‘ read 2 bytes, start at current position GET #1, var , PS ‘ start at position stored in long PS GET #1, var , PS, 2 ‘ start at position stored in long PS and read 2 bytes</source>

GET #channel, var

GET #channel, var , [pos] [, length]

#channel(...) A channel number, which identifies an opened file. This can be a hard coded constant or a variable
Var(...) The variable or variable array that will be assigned with the data from the file
Pos(...) This is an optional parameter that may be used to specify the postion where the reading must start from. This must be a long variable
Length(...) This is an optional parameter that may be used to specify how many bytes must be read from the file.

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

<source lang="vb"> 'for the binary file demo we need some variables of different types Dim B As Byte , W As Word , L As Long , Sn As Single , Ltemp As Long Dim Stxt As String * 10 B = 1 : W = 50000 : L = 12345678 : Sn = 123.45 : Stxt = "test"

'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 Seek(#2) ; " = LOC+1"

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

'now open the file again and write only the single Open "test.bin" For Binary As #2 L = 1 'specify the file position B = Seek(#2 , L) ' reset is the same as using SEEK #2,L Get #2 , B ' get the byte Get #2 , W ' get the word Get #2 , L ' get the long Get #2 , Sn ' get the single Get #2 , Stxt ' get the string Close #2 </source>

Put

Writes a byte to the hardware or software UART. Writes data to a file opened in BINARY mode.

PUT in combination with the software/hardware UART is provided for compatibility with BASCOM-8051. It writes one byte PUT in combination with the AVR-DOS filesystem is very flexible and versatile. It works on files opened in BINARY mode and you can write all data types. By default you only need to provide the variable name. When the variable is a byte, 1 byte wil be written. When the variable is a word or integer, 2 bytes will be written. When the variable is a long or single, 4 bytes will be written. When the variable is a string, the number of bytes that will be written is equal to the dimensioned size of the string. DIM S as string * 10 , would write 10 bytes. Note that when you specify the length for a string, the maximum length is 255. The maximum length for a non-string array is 65535. Example: <source lang="vb"> PUT #1, var PUT #1, var , , 2 ‘ write 2 bytes at default position PUT #1, var ,PS, 2 ‘ write 2 bytes at location storied in variable PS</source>

PUT #channel, var

PUT #channel, var ,[pos] [,length]

#channel(...) A channel number, which identifies an opened file. This can be a hard coded constant or a variable.
Var(...) The variable or variable array that will be written to the file
Pos(...) This is an optional parameter that may be used to specify the postion where the data must be written to. This must be a long variable.
Length(...) This is an optional parameter that may be used to specify how many bytes must be written to the file.

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

<source lang="vb"> 'for the binary file demo we need some variables of different types Dim B As Byte , W As Word , L As Long , Sn As Single , Ltemp As Long Dim Stxt As String * 10 B = 1 : W = 50000 : L = 12345678 : Sn = 123.45 : Stxt = "test"

'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 Seek(#2) ; " = LOC+1"

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

'now open the file again and write only the single Open "test.bin" For Binary As #2 L = 1 'specify the file position B = Seek(#2 , L) ' reset is the same as using SEEK #2,L Get #2 , B ' get the byte Get #2 , W ' get the word Get #2 , L ' get the long Get #2 , Sn ' get the single Get #2 , Stxt ' get the string Close #2 </source>

Seek

Function: Returns the position of the next Byte to be read or written. Statement: Sets the position of the next Byte to be read or written.

This function returns the position of the next Byte to be read or written. If an error occures, 0 is returned. Check DOS-Error in variable gbDOSError[4].. The statetement also returns an error in the gbDOSerror variable in the event that an error occurs. You can for example not set the fileposition behinds the filesize. In QB/VB the file is filled with 0 bytes when you set the filepointer behind the size of the file. For embedded systems this does not seem a good idea. Seek and Loc seems to do the same function, but take care : the seek function will return the position of the next read/write, while the Loc function returns the position of the last read/write. You may say that Seek = Loc+1. Difference with QB In QB/VB you can use seek to make the file bigger. When a file is 100 bytes long, setting the filepointer to 200 will increase the file with 0 bytes. By design this is not the case in AVR-DOS.

Function: NextReadWrite = Seek (#bFileNumber)

Statement: Seek #bFileNumber, NewPos)

bFileNumber(Byte) Filenumber, which identifies an opened file
NextReadWrite(Long) A Long Variable, which is assigned with the Position of the next Byte to be read or written (1-based)
NewPos(Long) A Long variable that holds the new position the filepointer must be set too.

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

<source lang="vb"> 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 Seek(#2) ; " = LOC+1"

Close #2

'now open the file again and write only the single Open "test.bin" For Binary As #2 Seek #2 , Ltemp ' set the filepointer Sn = 1.23 ' change the single value so we can check it better Put #2 , Sn = 1 'specify the file position Close #2 </source>

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

LOC

Returns the position of last read or written Byte of the file.

This function returns the position of the last read or written Byte. If an error occurs, 0 is returned. Check DOS-Error in variable gbDOSError[4].. If the file position pointer is changed with the command SEEK, this function can not be used till the next read/write operation. Difference with QB This function differs from QB. In QB the byte position is divided by 128.

lLastReadWritten = Loc (#bFileNumber)

bFileNumber(Byte) Filenumber, which identifies an opened file
lLastReadWritten(Long) Variable, whichsigned with the Position of last read or written Byte (1-based)

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

<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>

FileAttr

Возвращает режим открытия файлового потока.

bFileAttribut = FileAttr (bFileNumber)

bFileAttribut(Long) Режим:

1 - INPUT
2 - OUTPUT
8 - APPEND
32 - BINARY

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

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

<source lang="vb"> 'open the file in BINARY mode Open "test.biN" For Binary As #2 Print Fileattr(#2) ; " file mode" ' should be 32 for binary Put #2 , Sn ' write a single Put #2 , Stxt ' write a string Close #2 </source>

Другие

Bload

Writes the Content of a File into SRAM.

This function writes the content of a file to a desired space in SRAM. A free handle is needed for this function.

BLoad sFileName, wSRAMPointer

sFileName(Long) Name of the File to be read
wSRAMPointer(Word) Variable, which holds the SRAM Address to which the content of the file should be written

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

<source lang="vb"> 'now the good old bsave and bload Dim Ar(100) As Byte , I As Byte For I = 1 To 100 Ar(i) = I ' fill the array Next

Wait 2

W = Varptr(ar(1)) Bsave "josef.img" , W , 100 For I = 1 To 100 Ar(i) = 0 ' reset the array Next

Bload "josef.img" , W ' Josef you are amazing !

For I = 1 To 10 Print Ar(i) ; " " ; Next Print </source>

Bsave

Save a range in SRAM to a Fileю

This function writes a range from the SRAM to a file. A free file handle is needed for this function.

BSave sFileName, wSRAMPointer, wLength

sFileName(Long) Name of the File to be written
wSRAMPointer(Word) Variable, which holds the SRAM Address, from where SRAM should be written to a File
wLength(Word) Count of Bytes from SRAM, which should be written to the file

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

<source lang="vb">'now the good old bsave and bload Dim Ar(100) As Byte , I As Byte For I = 1 To 100 Ar(i) = I ' fill the array Next

Wait 2

W = Varptr(ar(1)) Bsave "josef.img" , W , 100 For I = 1 To 100 Ar(i) = 0 ' reset the array Next

Bload "josef.img" , W ' Josef you are amazing !

For I = 1 To 10 Print Ar(i) ; " " ; Next Print </source>

Сноски

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

См. также