'------------------------------------------------------------------------------- Option Explicit ' This is an easier-to-use version of OpenSPI. '------------------------------------------------------------------------------- Public Sub Main() Dim Channel As Byte Dim ChipSelectPin As Byte Dim LSBFirst As Boolean Dim ClockPolarity As Boolean Dim ClockPhase As Boolean Dim MaxClockRate As Long Dim PinNumber As Byte ' Example of SPI on channel 1 with clock rate no greater than 2.1 MHz. Channel = 1 ChipSelectPin = 17 LSBFirst = False ClockPolarity = False ClockPhase = False MaxClockRate = 2100000 ' Hz Call SPIOpenChannel(Channel, ChipSelectPin, LSBFirst, ClockPolarity, _ ClockPhase, MaxClockRate) ' [...] End Sub '------------------------------------------------------------------------------- Private Sub SPIOpenChannel( _ ByVal Channel As Byte, _ ByVal ChipSelectPin As Byte, _ ByVal LSBFirst As Boolean, _ ByVal ClockPolarity As Boolean, _ ByVal ClockPhase As Boolean, _ ByVal MaxClockRate As Long) Const SPIRateDiv4 As Byte = bx0000_0000 ' Clock speed = f/4 Const SPIRateDiv16 As Byte = bx0000_0001 ' Clock speed = f/16 Const SPIRateDiv64 As Byte = bx0000_0010 ' Clock speed = f/64 Const SPIRateDiv128 As Byte = bx0000_0011 ' Clock speed = f/128 Dim ClockRateSelect As Byte ' See Atmel documentation for these bits. Const DORD As Byte = bx0010_0000 ' Data order, LSB first. Const CPOL As Byte = bx0000_1000 ' Clock polarity, SCK high when idle. Const CPHA As Byte = bx0000_0100 ' Clock phase. Dim SetupByte As Byte ' Safety clamp. If (Channel < 1) Then Channel = 1 ElseIf (Channel > 4) Then Channel = 4 End If ' Pick a clock rate as close as possible to MaxClockRate but without ' exceeding the rate. If (MaxClockRate >= 1843200) Then ClockRateSelect = SPIRateDiv4 ' Fastest. ElseIf (MaxClockRate >= 460800) Then ClockRateSelect = SPIRateDiv16 ElseIf (MaxClockRate >= 115200) Then ClockRateSelect = SPIRateDiv64 ElseIf (MaxClockRate >= 57600) Then ClockRateSelect = SPIRateDiv128 ' Slowest. Else ' Error, choose slowest speed. ClockRateSelect = SPIRateDiv128 End If SetupByte = ClockRateSelect If (LSBFirst) Then SetupByte = SetupByte Or DORD End If If (ClockPolarity) Then SetupByte = SetupByte Or CPOL End If If (ClockPhase) Then SetupByte = SetupByte Or CPHA End If Call OpenSPI(Channel, SetupByte, ChipSelectPin) End Sub '-------------------------------------------------------------------------------