Администрация форума не несёт ответственности за достоверность информации и оставляет за собой право редактировать или в особых случаях даже удалять посты без предупреждения. Спасибо за понимание.

Программирование ATMEL в BASCOM.

Информация о пользователе

Привет, Гость! Войдите или зарегистрируйтесь.


Вы здесь » Программирование ATMEL в BASCOM. » Готовые конструкции » Универсальная сигнализация Xmega Si4463 Рация AVR-DOS


Универсальная сигнализация Xmega Si4463 Рация AVR-DOS

Сообщений 31 страница 60 из 80

31

Nord написал(а):

что с кварцем стабильнее.

Раз имеется температурный перепад то лучше использовать термостатированный кварцевый генератор, благо их у китайцев выбор широк!

+1

32

EdGull написал(а):

Экран будет этот

https://ae01.alicdn.com/kf/HTB1r5AgJeOSBuNjy0Fdq6zDnVXa8.jpg


Кто нибудь встречал готовую библиотеку для такого экранчика?

0

33

Adagumer написал(а):

Nord написал(а):что с кварцем стабильнее.Раз имеется температурный перепад то лучше использовать термостатированный кварцевый генератор, благо их у китайцев выбор широк!

В данном случае, думаю, нет такой высокостабильной необходимости... ;)
Это же не научная аппаратура...

Кто может привести пример использования "термостатированного кварцевого генератора" в автосигналках ? ;)
Соглашусь, но только стоимость комплекта при этом перевалит за 20 круб... ;)

0

34

Nord написал(а):

Кто может привести пример использования "термостатированного кварцевого генератора" в автосигналках ?

В покупных нет, а "для себя хорошего" почему бы и нет?

+2

35

Adagumer написал(а):

В покупных нет, а "для себя хорошего" почему бы и нет?

В данной теме, думается, бюджетная сторона превалирует.
Иначе "не стоит овчинка выделки"... ;)

0

36

EdGull написал(а):

Кто нибудь встречал готовую библиотеку для такого экранчика?

SSD1306 - поиск по сайту
Или укажите используемый контроллер...
По чертежам ванговать тяжело... ;)

Отредактировано Nord (2019-06-20 01:20:01)

0

37

Продолжаем потихоньку рисование...

http://s3.uploads.ru/t/hvRHG.png

Отредактировано EdGull (2019-06-23 14:08:31)

+1

38

Потихоньку начинают подъезжать комплектующие...

http://sh.uploads.ru/t/kHYx9.jpg

+2

39

Решил сменить трансивер на SX1276 у которого судя по отзывам и описанию есть волшебный режим LoRa. И он вроде как заточен отлалвливать из сна преамбулу и первые 4 байта.
Исходников на Bascom не нашел. Поэтому начал по тихоньку переводить с помощью гугла документацию на него.
Пока перевел только 42 страницы. Дайте знать если найдете грубые ошибки.

https://vk.com/doc191426545_509792159

Отредактировано EdGull (2019-07-06 21:27:06)

0

40

Вот здесь https://vrtp.ru/index.php?showtopic=27904&st=0 у автора получилось устойчиво передавать голос на скорости 450 бит/с (0.45кб/с) на расстояние 5.5 км (правда там собственный обученный вокодер и STM32F405).

0

41

EdGull написал(а):

правда там собственный обученный вокодер и STM32F405

Многие давно начали переходить на STM32 из-за хорошего соотношения цена / возможности. В сети со временем будет больше появляться проектов на STM32 чем на AVR и других 8-ми битниках.

-1

42

Я тоже попробовал. Поставил на неделе mikropascal и mikrobasic на попробовать. Честных пять дней тыркался. Не нашел как на них запустить:
ЖКИ ssd1306
DOS на sdcard
SX1276
sim800
Ну и всю свою остальную мелочевку.
Даже просто сконфигурировать ногу на выход и подергать ей целый рассказ писать надо.
Вернулся на васик с  хмегой.

короче, разбаловал меня bascom...

Отредактировано EdGull (2019-07-07 13:19:15)

+2

43

EdGull написал(а):

DOS на sdcard

Есть библиотека Compact Flash Library.
А по поводу остального. Когда нет библиотеки для какого-то устройства, обычно скачивают на него даташит, изучают и пишут код.

EdGull написал(а):

Даже просто сконфигурировать ногу на выход и подергать ей целый рассказ писать надо.

Я бы так не сказал бы. Настройка выхода.

Код:
GPIO_Digital_Output(@GPIOC_BASE, _GPIO_PINMASK_13)

Инвертирование.

Код:
GPIOC_ODR.13 = NOT GPIOC_ODR.13

(Пример) Простая программа - "мигалка" светодиодом

-1

44

Пётр написал(а):

Я бы так не сказал бы. Настройка выхода.

Ну и я говорю, что целый рассказ получается... ))) Сравни с количеством букв такой же операции в васике (это риторическое предложение).

Пётр написал(а):

А по поводу остального. Когда нет библиотеки для какого-то устройства, обычно скачивают на него даташит, изучают и пишут код.


А в васике или включают библиотеку или спрашивают на форумах, где скачать пример работы с этим устройством... )))
но это я так - бурчу по стариковски, не обращай внимания.

Перевел до 54 страницы включительно https://vk.com/doc191426545_509853178

Кстати, оригинал даташита https://vk.com/doc191426545_509853134

0

45

EdGull написал(а):

Кстати, оригинал даташита https://vk.com/doc191426545_509853134

А кроме VK есть более адекватные файлохранилища ? ;)
Далеко не все в VK присутствуют и желают регистрироваться... ;)
Меня, например, нет ни в VK, ни в ОК, не говоря уже о прочих "смотрите, что я кушаю"... ;)

0

46

Nord написал(а):

Далеко не все в VK присутствуют и желают регистрироваться

Файл скачивается без регистрации.

+1

47

Пётр написал(а):

Файл скачивается без регистрации.

Да вот фиг там... ;)

Для работы с сайтом необходима поддержка JavaScript и Cookies

Ну и с соответствующим продолжением... ;)

-1

48

скачивается без наличия регистрации в ВК (у меня его нет):
http://sg.uploads.ru/t/luB7V.jpg

0

49

Даташит, ерата и прочая литература на сайте производителе
https://www.semtech.com/products/wirele … ers/sx1276

0

50

Nord написал(а):

Для работы с сайтом необходима поддержка JavaScript и Cookies

Какой у вас браузер? В нем это отключено?

0

51

Пётр написал(а):

Какой у вас браузер? В нем это отключено?

IE11, меня вполне устраивает, менять не планирую. ;)
JavaScript и Cookies включены, т.к. без них на некоторые интересующие меня сайты попасть не получается.

0

52

Перевел еще 10 страниц, т.е. до 64 включительно.

https://vk.com/doc191426545_510459989

0

53

Еще немного перевода, до 76 стр. включительно.

https://vk.com/doc191426545_510579490

0

54

Перевел до 90 стр. включительно
https://vk.com/doc191426545_511137224

+1

55

Исходники для RFM92 вроде как должны полностью совпадать с sx1276
Спасибо большое radan-у за помощь.

Приемная часть

Код:
'****   RFM92 RX  *************************************
'****  Anders L. april 2016 Tested on DRF1272F ********
'******************************************************
'Lora has its own fifo
'To optimise the LoRaTM modulation for a given application,
'access is given to the designer to three critical design parameters.
'Each one permitting a trade off between link budget, immunity to interference,
'spectral occupancy and nominal data rate. These parameters are
'spreading factor, modulation bandwidth and error coding rate.

$regfile = "m328pdef.dat"
$crystal = 16000000
$hwstack = 80
$swstack = 80
$framesize = 100
$baud = 38400

#if _build < 20784
  Dim ___lcdrow As Byte , ___lcdcol As Byte       ' dim these for older compiler versions
#endif

Config Portb.2 = Output       'RFM92 nSEL OUT
_slaveselectpin Alias Portb.2
Set _slaveselectpin

Config Portd.3 = Input        ' INT pin for rx done/tx done etc. Programmable.
Dio0 Alias Pind.3

Config Portb.1 = Input
Dio5 Alias Pinb.1

Config Portc.6 = Output       'Led indication
Led Alias Portc.6
Set Led

Config Base = 0

Const Debugit = 1

$include "RFM_92_registers.inc"

Const Kontrast = &HFF         '00-FF Kontrast

Dim Currentmode As Byte
Currentmode = &H81
Dim Rx(65) As Byte
Dim Receive_string As String * 64 At Rx(0) Overlay
Dim Tx(65) As Byte
Dim Send_string As String * 64 At Tx(0) Overlay

Dim Test_byte As Byte
Dim _rssi As Integer
Dim _pktsnr As Integer
Dim _pktrssi As Integer
Dim _lorafei As Integer

'CALCULATE REQUIRED FREQUENCY REGISTERS OR SET THEM DIRECTLY
Dim Freg(3) As Byte
Dim Lfreg As Dword At Freg Overlay
Dim Aa As Single
Const Fosc = 32000000
Const Divider = 2 ^ 19
Const Frf = 868000000
Dim Bb As Single
Aa = Fosc / Divider
Bb = Frf / Aa
Lfreg = Bb
'Print "msb " ; Hex(freg(2))
'Print "mid " ; Hex(freg(1))
'Print "lsb " ; Hex(freg(0))

Const Faktor = 2 ^ 24         'Used for frequency error calc


Declare Sub Setloramode
Declare Sub Startreceiving
Declare Sub Setmode(byval Newmode As Byte)
Declare Sub Receivemessage
Declare Sub Senddata
Declare Function Lorareadrssi() As Integer
Declare Function Lorapktsnr() As Integer
Declare Function Lorapktrssi() As Integer
Declare Function Lorafei() As Long

Declare Sub Writeregister(byval Addr As Byte , Byval Value As Byte)
Declare Sub Fifo_burst_write(byval Start_at As Byte , Byval Length As Byte)
Declare Sub Fifo_burst_read(fifo_pointer As Byte , Length As Byte)       'ALL Passed byref
Declare Function Readregister(byval Address As Byte) As Byte


'-------SPI configuration-------------------------------------------------------
Config Spi = Hard , Interrupt = Off , Data Order = Msb , Master = Yes , Polarity = Low , Phase = 0 , Clockrate = 4 , Noss = 1 , Spiin = 0
Spiinit

Waitms 500

Config Scl = Portc.5
Config Sda = Portc.4
Config Twi = 400000
' OLED DISP WRITE ADDRESS= &H78
I2cinit
$lib "I2C_TWI.LBX"            ' lib for using the hardware I2C. Comment out for soft I2C
$lib "glcdSSD1306-I2C.lib"    ' override the default lib with this special one
Config Graphlcd = Custom , Cols = 128 , Rows = 64 , Lcdname = "SSD1306"
Waitms 200

Cls
Setfont My12_16
Cls
Lcdat 1 , 1 , "LORA TEST"

'Setup
'// LoRa mode
Call Setloramode              ' also puts it to sleep
'HERE THE FREQUENCY ARE SET DIRECTLY FOR TESTING
'Print "msb " ; Hex(freg(2))
'Print "mid " ; Hex(freg(1))
'Print "lsb " ; Hex(freg(0))
'Call Writeregister(regfrfmsb , Freg(2))
'Call Writeregister(regfrfmid , Freg(1))
'Call Writeregister(regfrflsb , Freg(0))
'0xd84ccc - - > Ch = 10_868 , 865.20mhz
'Call Writeregister(regfrfmsb , &HD8)    'TEST
'Call Writeregister(regfrfmid , &H4C)    'TEST
'Call Writeregister(regfrflsb , &HCC)    'TEST
'Channel = 0xd8c000 - - > Ch = 16_868 , 867.00mhz
'Call Writeregister(regfrfmsb , &HD8)    'TEST
'Call Writeregister(regfrfmid , &HC0)    'TEST
'Call Writeregister(regfrflsb , &H00)    'TEST
'Channel = 0xe3ee14 - - > Ch = 04_900 , 911.72mhz
Call Writeregister(regfrfmsb , &HE3)       'TEST
Call Writeregister(regfrfmid , &HEE)       'TEST
Call Writeregister(regfrflsb , &H14)       'TEST
'CH_11_900 = 0xE7B5C2; // channel 11, central freq = 926.84MHz
'Call Writeregister(regfrfmsb , &HE7)    'TEST
'Call Writeregister(regfrfmid , &HB5)    'TEST
'Call Writeregister(regfrflsb , &HC2)    'TEST

'config modem settings. Conf1 (to test: &H08, &H27)
Call Writeregister(loraregmodemconfig1 , &H0B)       'BW:125kHz,coderate:4/5,explicit,payldCRC enable,loraoptOn
Call Writeregister(loraregmodemconfig2 , &HC4)       'SF=12=(7-4)1100 por(3-0)=0100 makes C4  RX=TX setting

Call Writeregister(loraregsymbtimeoutlsb , &H05)
Call Writeregister(loraregpayloadmaxlength , &H14)       '&H40
Test_byte = Readregister(loraregdetectoptimize)       ' should be 3 for SF7-12 and 5 for SF6
Test_byte.7 = 1
Call Writeregister(loraregdetectoptimize , Test_byte)       ' according errata Optimized Rx Spurious Response set bit 7 of reg 31


Test_byte = Readregister(loraregmodemconfig2)
Print "modconf2: " ; Bin(test_byte)
Test_byte = Readregister(regfrfmsb)
Print "Frf_MSB: " ; Hex(test_byte)
Test_byte = Readregister(regfrfmid)
Print "Frf_MID: " ; Hex(test_byte)
Test_byte = Readregister(regfrflsb)
Print "Frf_LSB: " ; Hex(test_byte)
Wait 3

Call Startreceiving

'Test_byte = Readregister(loraregirqflagsmask)
'Print "IRQMASK: " ; Bin(test_byte)

Wait 1
Cls
Do
     Test_byte = Readregister(loraregirqflags)       'test for ValidHeader bit 4
     If Test_byte.4 = 1 Then
        Call Writeregister(loraregirqflags , &H10)       'reset irq flag bit 4
        _rssi = Lorareadrssi()
        Print "RSSI for Lora: " ; _rssi
        Lcdat 4 , 1 , "RSSI: "
        Lcdat 4 , 55 , "     "
        Lcdat 4 , 55 , _rssi
     End If
   If Dio0 = 1 Then
      Call Receivemessage
      _pktsnr = Lorapktsnr()
      Print "SNR: " ; _pktsnr
      _pktrssi = Lorapktrssi()
      Print "Packet RSSI: " ; _pktrssi
      _lorafei = Lorafei()
      Lcdat 7 , 1 , "SNR: "
      Lcdat 7 , 50 , "     "
      Lcdat 7 , 50 , _pktsnr
      Print "Recived: " ; Receive_string
      Lcdat 1 , 1 , Receive_string
   End If
Loop

End
'Read a Register Byte from RFM92
Function Readregister(byval Address As Byte) As Byte
   Reset _slaveselectpin
   Address = Address And &H7F
   Spiout Address , 1         'write register address
   Spiin Readregister , 1     'store register value in Readregister
   Set _slaveselectpin
End Function

Sub Writeregister(byval Addr As Byte , Byval Value As Byte)
   Reset _slaveselectpin      ' RFM92 Slave Select
   Set Addr.7                 'Set write bit
   Spiout Addr , 1            ' Write Address
   Spiout Value , 1           ' Write Data Byte
   Set _slaveselectpin
End Sub

Sub Fifo_burst_read(fifo_pointer As Byte , Length As Byte)       'ALL Passed byref
   Local X As Byte , Y As Byte
   X = Regfifo                'Address for FIFO read
   Y = Fifo_pointer           'Start value to fill the Rx() Array
   Length = Fifo_pointer + Length
   Length = Length - 1        'Rx(1) ....Rx(32)   next is   Rx(33) ...Rx(64)  next is  Rx(65) ....Rx(96)
   Reset _slaveselectpin
   Spiout X , 1               'write fifo register address only once
    For X = Y To Length
       Spiin Rx(x) , 1        'Read the FIFO in burst mode
    Next
   Set _slaveselectpin
End Sub

Sub Fifo_burst_write(byval Start_at As Byte , Byval Length As Byte)
   Local X As Byte , Y As Byte
   X = Regfifo
   If Start_at = 0 Then Y = Length       'Tx(1) ....Tx(64)  -->  Tx(65) .....Tx(96)
   If Start_at > 0 Then
      Y = Start_at + Length   '65 + 32 = 97 - 1 = 96   .....
      Y = Y - 1
   End If
   Set X.7                    'Set write bit
   Reset _slaveselectpin
   Spiout X , 1               'write fifo register address only once
    For X = Start_at To Y
       Spiout Tx(x) , 1       'Write the FIFO in burst mode
    Next
   Set _slaveselectpin
End Sub

Sub Setloramode
'Method:   Enable LoRa mode

   Print "Setting LoRa Mode"
   Call Setmode(rf92_mode_sleep)
   Call Writeregister(regopmode , &H80)
   Print "LoRa Mode Set"
End Sub

Sub Startreceiving
'********************************************
'Method:   Setup to receive continuously

'  // Turn on implicit header mode and set payload length
   'Call Writeregister(reg_modem_config , Implicit_mode)
   Call Writeregister(loraregpayloadlength , Payload_length)
   'Call Writeregister(reg_hop_period , &HFF)
   Call Writeregister(loraregfifoaddrptr , Readregister(loraregfiforxbaseaddr))

  '// Setup Receive Continous Mode
   Call Setmode(rf92_mode_rx_continuos)
End Sub

Sub Receivemessage
'Method:   Receive FROM BUFFER

         Local X_r As Byte
         Local Currentaddr As Byte
         Local Receivedcount As Byte
         Local I As Byte

         'clear the rxDone flag
         Call Writeregister(loraregirqflags , &H40)       '&B0100_0000
         X_r = Readregister(loraregirqflags)       ' // if any of these are set then the inbound message failed
         Print "IRQFLAGS: " ; Bin(x_r)

  '// check for payload crc issues (0x20 is the bit we are looking for
  If X_r.5 = 1 Then           'IRQ crc error set?
         Print "Oops there was a crc problem!!"
         Print X_r
    ' / / Reset The Crc Flags
         Call Writeregister(loraregirqflags , &H20)       '&B0010_0000
  Else
         Currentaddr = Readregister(loraregfiforxcurrentaddr)
         Receivedcount = Readregister(loraregrxnbbytes)
         'Receivedcount = Receivedcount + 1
         Print "Packet! RX Current Addr: " ; Currentaddr;
         Print "Number of bytes received: " ; Receivedcount

         Call Writeregister(loraregfifoaddrptr , Currentaddr)
         'now loop over the fifo getting the data
         I = 0
         While I < Receivedcount
            Rx(i) = Readregister(regfifo)
            Incr I
         Wend
  End If

End Sub

Sub Setmode(byval Newmode As Byte)
' Method:   Change the mode

   If Newmode = Currentmode Then
      Exit Sub
   End If
   Select Case Newmode

      Case Rf92_mode_rx_continuos
         'Call Writeregister(reg_pa_config , &H00)   '  // TURN PA OFF FOR RECIEVE??
         Call Writeregister(reg_lna , Lna_max_gain)       '  // MAX GAIN FOR RECIEVE
         Call Writeregister(regopmode , Newmode)
         Currentmode = Newmode
         Print "Changing to Receive Continous Mode"

      Case Rf92_mode_tx
         Call Writeregister(reg_lna , Lna_off_gain)       '  // TURN LNA OFF FOR TRANSMITT
         Call Writeregister(reg_pa_config , Pa_max_boost)       '    // TURN PA TO MAX POWER
         Call Writeregister(regopmode , Newmode)
         Currentmode = Newmode
         Print "Changing to Transmit Mode"

      Case Rf92_mode_sleep
         Call Writeregister(regopmode , Newmode)
         Currentmode = Newmode
         Print "Changing to Sleep Mode"

      Case Rf92_mode_standby
         Call Writeregister(regopmode , Newmode)
         Currentmode = Newmode
         Print "Changing to Standby Mode"

   End Select
   Print " Mode Change Done"
End Sub

Sub Senddata
Local X As Byte
   X = Regfifo
  Call Setmode(rf92_mode_standby)
  Call Writeregister(loraregfifotxbaseaddr , &H00)       'Update the address ptr to the current tx base address
  Call Writeregister(loraregfifoaddrptr , &H00)
  Call Fifo_burst_write(1 , 11)
  'Go into transmit mode
  Call Setmode(rf92_mode_tx)
  ' once TxDone has flipped, everything has been sent
  While Dio0 = 0
      'print "y"
  Wend
  Print " done sending!"
  '// clear the flags 0x08 is the TxDone flag
  Call Writeregister(loraregirqflags , &H08)
  'Blink the LED
  Set Led
  Waitms 400
  Reset Led
End Sub

'/**********************************************************
'**Name:     LoRaReadRSSI
'**Function: Read the RSSI value
'**Input:    none
'**Output:   temp, RSSI value
'**********************************************************/
Function Lorareadrssi() As Integer
  Local Temp1 As Integer
  Local Rssi_mean As Integer
  Local Cntr As Byte
  Local Bbyte As Byte
  Rssi_mean = 0
  Temp1 = 0
  Cntr = 0
   While Cntr < 5
    Bbyte = Readregister(loraregrssivalue)
    Temp1 = -137 + Bbyte
    Rssi_mean = Rssi_mean + Temp1
    Incr Cntr
   Wend
   Rssi_mean = Rssi_mean \ 5
   Lorareadrssi = Rssi_mean
End Function

Function Lorapktsnr() As Integer
Local Test_byte As Byte
      Test_byte = Readregister(loraregpktsnrvalue)       'Get packet SNR
      If Test_byte.7 = 1 Then 'If negative number
         Test_byte = Not Test_byte
         Test_byte = Test_byte + 1
         Shift Test_byte , Right , 2       'divide by 4
         Lorapktsnr = - Test_byte
      Else
         Shift Test_byte , Right , 2       'divide by 4
         Lorapktsnr = Test_byte
      End If
End Function

Function Lorapktrssi() As Integer
Local Test_byte As Byte
Local Temp1 As Integer
Local Temp2 As Integer
      Temp2 = Lorapktsnr()
      If Temp2 > 0 Then
         Test_byte = Readregister(loraregpktrssivalue)
         Print "pktrssi_raw " ; Test_byte
         Temp1 = Test_byte
         'Temp1 = Temp1 \ 4  'This is stated in SX1272 manual, but corrected in reg desc.
         Temp1 = -139 + Temp1
         Lorapktrssi = Temp1
      Else
         Test_byte = Readregister(loraregpktrssivalue)
         Temp2 = Temp2 \ 4    'FORMULA from waspmote: pktssi(BW=125)=-174+10*5.1+6+SNR
         Temp2 = Test_byte + Temp2
         Temp1 = -139 + Temp2
         Lorapktrssi = Temp1
      End If
End Function

'*** Reads frequency error based on 3 bytes giving 20bit 2's complement value
'*** 'FError=FreqError x 2^24/Fxtal
Function Lorafei() As Long
Local Abyte As Byte
Local L1 As Long
Local L2 As Long

      #if Debugit = 1
          Abyte = Readregister(loraregfeimsb)       'MSB of fei
          Print "FEIREGS: " ; Hex(abyte);
          Abyte = Readregister(loraregfeimib)       'MID of fei
          Print Hex(abyte);
          Abyte = Readregister(loraregfeilsb)       'LSB of fei
          Print Hex(abyte)
      #endif

      Abyte = Readregister(loraregfeimsb)       'MSB of fei
      If Abyte.3 = 1 Then     'Negative number
         L1 = Abyte * 65536
         Abyte = Readregister(loraregfeimib)       'MID of fei
         L2 = Abyte * 256
         L1 = L1 + L2
         Abyte = Readregister(loraregfeilsb)       'LSB of fei
         L1 = L1 + Abyte
         L1 = Not L1
         L1 = L1 + 1
         #if Debugit = 1
           Print "L1 negative " ; L1
         #endif
      Else
         'Abyte = Readregister(loraregfeimsb)                   'MSB of fei
         L1 = Abyte * 65536
         Abyte = Readregister(loraregfeimib)       'MID of fei
         L2 = Abyte * 256
         L1 = L1 + L2
         Abyte = Readregister(loraregfeilsb)       'LSB of fei
         L1 = L1 + Abyte
         #if Debugit = 1
           Print "L1 positive " ; L1
         #endif
      End If
      L1 = L1 * Faktor
      L1 = L1 / Fosc
      #if Debugit = 1
           Print "lorafei= " ; L1
      #endif
      Lorafei = L1

End Function


'$include "font8x8TT.font"               ' this is a true type font with variable spacing
'$include "My6_8.font"
$include "My12_16.font"

0

56

Передающая часть

Код:
'****   RFM92 TX  *************************************
'****  Anders L. april 2016 Tested on DRF1272F ********
'******************************************************
'Lora has its own fifo
'To optimise the LoRaTM modulation for a given application,
'access is given to the designer to three critical design parameters.
'Each one permitting a trade off between link budget, immunity to interference,
'spectral occupancy and nominal data rate. These parameters are
'spreading factor, modulation bandwidth and error coding rate.

$regfile = "m328pdef.dat"
$crystal = 16000000
$hwstack = 80
$swstack = 80
$framesize = 100
$baud = 38400

Config Portb.2 = Output       'RFM92 nSEL OUT
_slaveselectpin Alias Portb.2
Set _slaveselectpin

Config Portd.3 = Input        ' INT pin for rx done/tx done etc. Programmable.
Dio0 Alias Pind.3

Config Portb.1 = Input
Dio5 Alias Pinb.1

Config Portc.5 = Output       'Led indication
Led Alias Portc.5
Set Led

Config Base = 0

Const Debugit = 1

Dim Currentmode As Byte
Currentmode = &H81
Dim Rx(65) As Byte
Dim Receive_string As String * 64 At Rx(0) Overlay
Dim Tx(65) As Byte
Dim Send_string As String * 64 At Tx(0) Overlay
Dim Teller1 As Byte

$include "RFM_92_registers.inc"

'CALCULATE REQUIRED FREQUENCY REGISTERS OR SET THEM DIRECTLY
Dim Freg(3) As Byte
Dim Lfreg As Dword At Freg Overlay
Dim Aa As Single
Const Fosc = 32000000
Const Divider = 2 ^ 19
Const Frf = 868000000
Dim Bb As Single
Aa = Fosc / Divider
Bb = Frf / Aa
Lfreg = Bb

Const Faktor = 2 ^ 24         'Used for frequency error calc

Dim Test_byte As Byte
Dim _rssi As Integer
Dim _pktsnr As Integer
Dim _pktrssi As Integer


Declare Sub Setloramode
Declare Sub Startreceiving
Declare Sub Setmode(byval Newmode As Byte)
Declare Sub Receivemessage
Declare Sub Senddata
Declare Function Lorareadrssi() As Integer
Declare Function Lorapktrssi() As Integer
Declare Function Lorapktsnr() As Integer
Declare Function Lorafei() As Long

Declare Sub Writeregister(byval Addr As Byte , Byval Value As Byte)
Declare Sub Fifo_burst_write(byval Start_at As Byte , Byval Length As Byte)
Declare Sub Fifo_burst_read(fifo_pointer As Byte , Length As Byte)       'ALL Passed byref
Declare Function Readregister(byval Address As Byte) As Byte


'-------SPI configuration-------------------------------------------------------
Config Spi = Hard , Interrupt = Off , Data Order = Msb , Master = Yes , Polarity = Low , Phase = 0 , Clockrate = 4 , Noss = 1 , Spiin = 0
Spiinit

Waitms 500

'// LoRa mode
Call Setloramode              ' also puts it to sleep
'HERE THE FREQUENCY ARE SET DIRECTLY FOR TESTING
'Print "msb " ; Hex(freg(3))
'Print "mid " ; Hex(freg(2))
'Print "lsb " ; Hex(freg(1))
'Call Writeregister(regfrfmsb , Freg(3))
'Call Writeregister(regfrfmid , Freg(2))
'Call Writeregister(regfrflsb , Freg(1))
'0xd84ccc - - > Ch = 10_868 , 865.20mhz
'Call Writeregister(regfrfmsb , &HD8)                        'TEST
'Call Writeregister(regfrfmid , &H4C)                        'TEST
'Call Writeregister(regfrflsb , &HCC)                        'TEST
'Channel = 0xd8c000 - - > Ch = 16_868 , 867.00mhz
'Call Writeregister(regfrfmsb , &HD8)                        'TEST
'Call Writeregister(regfrfmid , &HC0)                        'TEST
'Call Writeregister(regfrflsb , &H00)                        'TEST
'Channel = 0xe3ee14 - - > Ch = 04_900 , 911.72mhz
Call Writeregister(regfrfmsb , &HE3)       'TEST
Call Writeregister(regfrfmid , &HEE)       'TEST
Call Writeregister(regfrflsb , &H14)       'TEST
'CH_11_900 = 0xE7B5C2; // channel 11, central freq = 926.84MHz
'Call Writeregister(regfrfmsb , &HE7)                        'TEST
'Call Writeregister(regfrfmid , &HB5)                        'TEST
'Call Writeregister(regfrflsb , &HC2)                        'TEST


'config modem settings. Conf1 to test &H08, &H27
Call Writeregister(loraregmodemconfig1 , &H0B)       'BW:125kHz,coderate:4/5,explicit,payldCRC enable,loraoptOn
Call Writeregister(loraregmodemconfig2 , &HC4)       'SF=12=(7-4)1100 por(3-0)=0100 makes C4

Call Writeregister(loraregpayloadlength , Payload_length)
Call Writeregister(loraregpayloadmaxlength , &H14)       '&H40

Test_byte = Readregister(loraregdetectoptimize)       ' should be 3 for SF7-12 and 5 for SF6
Test_byte.7 = 1
Call Writeregister(loraregdetectoptimize , Test_byte)       ' according errata Optimized Rx Spurious Response set bit 7 of reg 31

'// Change the DIO mapping to 01 so we can listen for TxDone on the interrupt
Call Writeregister(reg_dio_mapping_1 , &H40)
Call Writeregister(reg_dio_mapping_2 , &H00)

Call Writeregister(regocp , &H0F)       ' dissable/set to max the over current protection

'// Go to standby mode
Call Setmode(rf92_mode_standby)

Print "Setup Complete"

  Wait 5                      'Just for test in case the power drawn are to much for usb port

Do
  Incr Teller1
  Send_string = "ABCDE " + Str(teller1)
  Call Senddata
  Wait 5
  'Test_byte = Readregister(regpadac)
  'Print "PAdac reg: " ; Hex(test_byte)

Loop

End

'Read a Register Byte from RFM92
Function Readregister(byval Address As Byte) As Byte
   Reset _slaveselectpin
   Address = Address And &H7F
   Spiout Address , 1         'write register address
   Spiin Readregister , 1     'store register value in Readregister
   Set _slaveselectpin
End Function

Sub Writeregister(byval Addr As Byte , Byval Value As Byte)
   Reset _slaveselectpin      ' RFM92 Slave Select
   Set Addr.7                 'Set write bit
   Spiout Addr , 1            ' Write Address
   Spiout Value , 1           ' Write Data Byte
   Set _slaveselectpin
End Sub

Sub Fifo_burst_read(fifo_pointer As Byte , Length As Byte)       'ALL Passed byref
   Local X As Byte , Y As Byte
   X = Regfifo                'Address for FIFO read
   Y = Fifo_pointer           'Start value to fill the Rx() Array
   Length = Fifo_pointer + Length
   Length = Length - 1        'Rx(1) ....Rx(32)   next is   Rx(33) ...Rx(64)  next is  Rx(65) ....Rx(96)
   Reset _slaveselectpin
   Spiout X , 1               'write fifo register address only once
    For X = Y To Length
       Spiin Rx(x) , 1        'Read the FIFO in burst mode
    Next
   Set _slaveselectpin
End Sub

Sub Fifo_burst_write(byval Start_at As Byte , Byval Length As Byte)
   Local X As Byte , Y As Byte
   X = Regfifo
   If Start_at = 0 Then Y = Length       'Tx(1) ....Tx(64)  -->  Tx(65) .....Tx(96)
   If Start_at > 0 Then
      Y = Start_at + Length   '65 + 32 = 97 - 1 = 96   .....
      Y = Y - 1
   End If
   Set X.7                    'Set write bit
   Reset _slaveselectpin
   Spiout X , 1               'write fifo register address only once
    For X = Start_at To Y
       Spiout Tx(x) , 1       'Write the FIFO in burst mode
    Next
   Set _slaveselectpin
End Sub

Sub Setloramode
'/////////////////////////////////////
'//    Method:   Enable LoRa mode
'//////////////////////////////////////
   Print "Setting LoRa Mode"
   Call Setmode(rf92_mode_sleep)
   Call Writeregister(regopmode , &H80)
   Print "LoRa Mode Set"
End Sub

Sub Startreceiving
'********************************************
'Method:   Setup to receive continuously
'  // Turn on implicit header mode and set payload length
   'Call Writeregister(reg_modem_config , Implicit_mode)
   Call Writeregister(loraregpayloadlength , Payload_length)
   'Call Writeregister(reg_hop_period , &HFF)
   Call Writeregister(loraregfifoaddrptr , Readregister(loraregfiforxbaseaddr))
  '// Setup Receive Continous Mode
   Call Setmode(rf92_mode_rx_continuos)
End Sub

Sub Receivemessage
'Method:   Receive FROM BUFFER
         Local X_r As Byte
         Local Currentaddr As Byte
         Local Receivedcount As Byte
         Local I As Byte
         'clear the rxDone flag
         Call Writeregister(loraregirqflags , &B0100_0000)       ' &H40)           '&B0100_0000
         X_r = Readregister(loraregirqflags)       ' // if any of these are set then the inbound message failed
         Print "IRQFLAGS: " ; Bin(x_r)
  '// check for payload crc issues (0x20 is the bit we are looking for
  If X_r.5 = 1 Then           'IRQ crc error set?
         Print "Oops there was a crc problem!!"
         Print X_r
    ' / / Reset The Crc Flags
         Call Writeregister(loraregirqflags , &H20)       '&B0010_0000
  Else
         Currentaddr = Readregister(loraregfiforxcurrentaddr)
         Receivedcount = Readregister(loraregrxnbbytes)
         'Receivedcount = Receivedcount + 1
         Print "Packet! RX Current Addr: " ; Currentaddr
    '//Serial.print("Number of bytes received:");
    '//Serial.println(receivedCount);
         Print "Number of bytes received: " ; Receivedcount
         Call Writeregister(loraregfifoaddrptr , Currentaddr)
   ' // now loop over the fifo getting the data
         I = 0
         While I < Receivedcount
            Rx(i) = Readregister(regfifo)
            Incr I
         Wend
  End If
End Sub

Sub Setmode(byval Newmode As Byte)
' Method:   Change the mode
   If Newmode = Currentmode Then
      Exit Sub
   End If
   Select Case Newmode
      Case Rf92_mode_rx_continuos
         'Call Writeregister(reg_pa_config , &H00)   '  // TURN PA OFF FOR RECIEVE??
         Call Writeregister(reg_lna , Lna_max_gain)       '  // MAX GAIN FOR RECIEVE
         Call Writeregister(regopmode , Newmode)
         Currentmode = Newmode
         Print "Changing to Receive Continous Mode"
      Case Rf92_mode_tx
         Call Writeregister(reg_lna , Lna_off_gain)       '  // TURN LNA OFF FOR TRANSMITT
         Call Writeregister(reg_pa_config , Pa_max_boost)       '    // TURN PA TO MAX POWER
         Call Writeregister(regopmode , Newmode)
         Currentmode = Newmode
         Print "Changing to Transmit Mode"
      Case Rf92_mode_sleep
         Call Writeregister(regopmode , Newmode)
         Currentmode = Newmode
         Print "Changing to Sleep Mode"
      Case Rf92_mode_standby
         Call Writeregister(regopmode , Newmode)
         Currentmode = Newmode
         Print "Changing to Standby Mode"
   End Select

   Print " Mode Change Done"
End Sub


Sub Senddata
Local X As Byte

   X = Regfifo
  Call Setmode(rf92_mode_standby)

  Call Writeregister(loraregfifotxbaseaddr , &H00)       'Update the address ptr to the current tx base address
  Call Writeregister(loraregfifoaddrptr , &H00)

  Call Fifo_burst_write(0 , 10)

  'Go into transmit mode
  Call Setmode(rf92_mode_tx)

  ' once TxDone has flipped, everything has been sent
  While Dio0 = 0
      'print "y"
  Wend

  Print " done sending!"

  '// clear the flags 0x08 is the TxDone flag
  Call Writeregister(loraregirqflags , &H08)

  'Blink the LED
  Set Led
  Waitms 400
  Reset Led

End Sub

'/**********************************************************
'**Name:     LoRaReadRSSI
'**Function: Read the RSSI value
'**Input:    none
'**Output:   temp, RSSI value
'**********************************************************/
Function Lorareadrssi() As Integer
  Local Temp1 As Integer
  Local Rssi_mean As Integer
  Local Cntr As Byte
  Local Bbyte As Byte
  Rssi_mean = 0
  Temp1 = 0
  Cntr = 0
   While Cntr < 5
    Bbyte = Readregister(loraregrssivalue)
    Temp1 = -137 + Bbyte
    Rssi_mean = Rssi_mean + Temp1
    Incr Cntr
   Wend
   Rssi_mean = Rssi_mean \ 5
   Lorareadrssi = Rssi_mean
End Function
Function Lorapktsnr() As Integer
Local Test_byte As Byte
      Test_byte = Readregister(loraregpktsnrvalue)       'Get packet SNR
      If Test_byte.7 = 1 Then 'If negative number
         Test_byte = Not Test_byte
         Test_byte = Test_byte + 1
         Shift Test_byte , Right , 2       'divide by 4
         Lorapktsnr = - Test_byte
      Else
         Shift Test_byte , Right , 2       'divide by 4
         Lorapktsnr = Test_byte
      End If
End Function
Function Lorapktrssi() As Integer
Local Test_byte As Byte
Local Temp1 As Integer
Local Temp2 As Integer
      Temp2 = Lorapktsnr()
      If Temp2 > 0 Then
         Test_byte = Readregister(loraregpktrssivalue)
         Print "pktrssi_raw " ; Test_byte
         Temp1 = Test_byte
         'Temp1 = Temp1 \ 4  'This is stated in SX1272 manual, but corrected in reg desc.
         Temp1 = -139 + Temp1
         Lorapktrssi = Temp1
      Else
         Test_byte = Readregister(loraregpktrssivalue)
         Temp2 = Temp2 \ 4    'FORMULA from waspmote: pktssi(BW=125)=-174+10*5.1+6+SNR
         Temp2 = Test_byte + Temp2
         Temp1 = -139 + Temp2
         Lorapktrssi = Temp1
      End If
End Function
'*** Reads frequency error based on 3 bytes giving 20bit 2's complement value
'*** 'FError=FreqError x 2^24/Fxtal
Function Lorafei() As Long
Local Abyte As Byte
Local L1 As Long
Local L2 As Long
      #if Debugit = 1
          Abyte = Readregister(loraregfeimsb)       'MSB of fei
          Print "FEIREGS: " ; Hex(abyte);
          Abyte = Readregister(loraregfeimib)       'MID of fei
          Print Hex(abyte);
          Abyte = Readregister(loraregfeilsb)       'LSB of fei
          Print Hex(abyte)
      #endif
      Abyte = Readregister(loraregfeimsb)       'MSB of fei
      If Abyte.3 = 1 Then     'Negative number
         L1 = Abyte * 65536
         Abyte = Readregister(loraregfeimib)       'MID of fei
         L2 = Abyte * 256
         L1 = L1 + L2
         Abyte = Readregister(loraregfeilsb)       'LSB of fei
         L1 = L1 + Abyte
         L1 = Not L1
         L1 = L1 + 1
         #if Debugit = 1
           Print "L1 negative " ; L1
         #endif
      Else
         'Abyte = Readregister(loraregfeimsb)                   'MSB of fei
         L1 = Abyte * 65536
         Abyte = Readregister(loraregfeimib)       'MID of fei
         L2 = Abyte * 256
         L1 = L1 + L2
         Abyte = Readregister(loraregfeilsb)       'LSB of fei
         L1 = L1 + Abyte
         #if Debugit = 1
           Print "L1 positive " ; L1
         #endif
      End If
      L1 = L1 * Faktor
      L1 = L1 / Fosc
      #if Debugit = 1
           Print "lorafei= " ; L1
      #endif
      Lorafei = L1
End Function

0

57

Файл RFM_92_registers.inc с константами

Код:
' // ----------------------------------------
'// Registers Mapping
Const Regfifo = &H00          '/ / Common
Const Regopmode = &H01        ' / / Common
Const Fskregbitratemsb = &H02
Const Fskregbitratelsb = &H03
Const Fskregfdevmsb = &H04
Const Fskregfdevlsb = &H05
Const Regfrfmsb = &H06        '/ / Common
Const Regfrfmid = &H07        '/ / Common
Const Regfrflsb = &H08        '/ / Common
Const Regpaconfig = &H09      ' / / Common
Const Regparamp = &H0A        '/ / Common
Const Regocp = &H0B           '/ / Common
Const Reglna = &H0C           '/ / Common
Const Fskregrxconfig = &H0D
Const Loraregfifoaddrptr = &H0D
Const Fskregrssiconfig = &H0E
Const Loraregfifotxbaseaddr = &H0E
Const Fskregrssicollision = &H0F
Const Loraregfiforxbaseaddr = &H0F
Const Fskregrssithresh = &H10
Const Loraregfiforxcurrentaddr = &H10
Const Fskregrssivalue = &H11
Const Loraregirqflagsmask = &H11
Const Fskregrxbw = &H12
Const Loraregirqflags = &H12
Const Fskregafcbw = &H13
Const Loraregrxnbbytes = &H13
Const Fskregookpeak = &H14
Const Loraregrxheadercntvaluemsb = &H14
Const Fskregookfix = &H15
Const Loraregrxheadercntvaluelsb = &H15
Const Fskregookavg = &H16
Const Loraregrxpacketcntvaluemsb = &H16
Const Loraregrxpacketcntvaluelsb = &H17
Const Loraregmodemstat = &H18
Const Loraregpktsnrvalue = &H19
Const Fskregafcfei = &H1A
Const Loraregpktrssivalue = &H1A
Const Fskregafcmsb = &H1B
Const Loraregrssivalue = &H1B
Const Fskregafclsb = &H1C
Const Lorareghopchannel = &H1C
Const Fskregfeimsb = &H1D
Const Loraregmodemconfig1 = &H1D
Const Fskregfeilsb = &H1E
Const Loraregmodemconfig2 = &H1E
Const Fskregpreambledetect = &H1F
Const Loraregsymbtimeoutlsb = &H1F
Const Fskregrxtimeout1 = &H20
Const Loraregpreamblemsb = &H20
Const Fskregrxtimeout2 = &H21
Const Loraregpreamblelsb = &H21
Const Fskregrxtimeout3 = &H22
Const Loraregpayloadlength = &H22
Const Fskregrxdelay = &H23
Const Loraregpayloadmaxlength = &H23
Const Fskregosc = &H24
Const Lorareghopperiod = &H24
Const Fskregpreamblemsb = &H25
Const Loraregfiforxbyteaddr = &H25
Const Loraregmodemconfig3 = &H26
Const Fskregpreamblelsb = &H26
Const Fskregsyncconfig = &H27
Const Loraregfeimsb = &H28
Const Fskregsyncvalue1 = &H28
Const Loraregfeimib = &H29
Const Fskregsyncvalue2 = &H29
Const Loraregfeilsb = &H2A
Const Fskregsyncvalue3 = &H2A
Const Fskregsyncvalue4 = &H2B
Const Loraregrssiwideband = &H2C
Const Fskregsyncvalue5 = &H2C
Const Fskregsyncvalue6 = &H2D
Const Fskregsyncvalue7 = &H2E
Const Fskregsyncvalue8 = &H2F
Const Fskregpacketconfig1 = &H30
Const Fskregpacketconfig2 = &H31
Const Loraregdetectoptimize = &H31
Const Fskregpayloadlength = &H32
Const Fskregnodeadrs = &H33
Const Lorareginvertiq = &H33
Const Fskregbroadcastadrs = &H34
Const Fskregfifothresh = &H35
Const Fskregseqconfig1 = &H36
Const Fskregseqconfig2 = &H37
Const Loraregdetectionthreshold = &H37
Const Fskregtimerresol = &H38
Const Fskregtimer1coef = &H39
Const Loraregsyncword = &H39
Const Fskregtimer2coef = &H3A
Const Fskregimagecal = &H3B
Const Fskregtemp = &H3C
Const Fskreglowbat = &H3D
Const Fskregirqflags1 = &H3E
Const Fskregirqflags2 = &H3F

Const Regversion = &H42       '/ / Common

Const Regpadac = &H5A         '// common

'// MODES
Const Rf92_mode_rx_continuos = &H85
Const Rf92_mode_tx = &H83
Const Rf92_mode_sleep = &H80
Const Rf92_mode_standby = &H81
Const Payload_length = &H0A
Const Implicit_mode = &H0C

'  / / Power Amplifier Config
'b7=0 RFIO pin. Output power is limited to 13 dBm.
'b7=1 PA_BOOST pin. Output power is limited to 20 dBm
'RegPaDac 0x5A 20dbm=0x87 17dbm=0x84(default)
Const Reg_pa_config = &H09
Const Pa_max_boost = &H8F
Const Pa_low_boost = &H81
Const Pa_med_boost = &H8A
Const Pa_off_boost = &H0F     'PA off,max on rfio pin=13dbm

'// LOW NOISE AMPLIFIER
Const Reg_lna = &H0C
Const Lna_max_gain = &H23     '0010_0011 Max gain,boost ON
Const Lna_off_gain = &H20     '0010_0000 Max gain,no boost

'DIO mapping
Const Reg_dio_mapping_1 = &H40
Const Reg_dio_mapping_2 = &H41

'Channel = 0xd84ccc - - > Ch = 10_868 , 865.20mhz
'Channel = 0xd86000 - - > Ch = 11_868 , 865.50mhz
'Channel = 0xD87333  --> CH = 12_868, 865.80MHz
'Channel = 0xd88666 - - > Ch = 13_868 , 866.10mhz
'Channel = 0xd89999 - - > Ch = 14_868 , 866.40mhz
'Channel = 0xD8ACCC  --> CH = 15_868, 866.70MHz
'Channel = 0xd8c000 - - > Ch = 16_868 , 867.00mhz
'Channel = 0xe1c51e - - > Ch = 00_900 , 903.08mhz
'Channel = 0xe24f5c - - > Ch = 01_900 , 905.24mhz
'Channel = 0xe2d999 - - > Ch = 02_900 , 907.40mhz
'Channel = 0xe363d7 - - > Ch = 03_900 , 909.56mhz
'Channel = 0xe3ee14 - - > Ch = 04_900 , 911.72mhz
'Channel = 0xe47851 - - > Ch = 05_900 , 913.88mhz
'Channel = 0xe5028f - - > Ch = 06_900 , 916.04mhz
'Channel = 0xe58ccc - - > Ch = 07_900 , 918.20mhz
'Channel = 0xe6170a - - > Ch = 08_900 , 920.36mhz
'Channel = 0xe6a147 - - > Ch = 09_900 , 922.52mhz
'Channel = 0xe72b85 - - > Ch = 10_900 , 924.68mhz
'Channel = 0xe7b5c2 - - > Ch = 11_900 , 926.84mhz

0

58

Перевел до 100 страницы включительно

https://vk.com/doc191426545_511975217

0

59

Калькулятор для LoRa https://www.semtech.com/uploads/documen … tup1_1.zip

0

60

Решил для ускорения процесса и за одно попробовать новый для меня сервис EasyEDA, по быстрому развести минимальную макетку для XMega256A3.

Схема
https://vk.com/doc191426545_512905903

http://s7.uploads.ru/t/X2H1Z.png

http://s3.uploads.ru/t/Xzhfy.png

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

Всем активно участвующим в развитии данного ресурса готов задарить плат и/или исходники.

0


Вы здесь » Программирование ATMEL в BASCOM. » Готовые конструкции » Универсальная сигнализация Xmega Si4463 Рация AVR-DOS