
'by jean-claude.feltes@education.lu + WEIGU
'11.12.2014

'new:
' Output to USB + RS232 in modes 1s, 100ms
' Output only to USB in mode 10ms and 4ms
' Mode 1ms is too fast as critical block takes ca. 2.8ms

'USB  send from Asserlogger to PC    TESTED, works in modes 0 and 1 :-)
'USB from PC to Asserlogger works for commans s, x, 0, 1 ,2, 4
'tested on Linux and WinXP (don't try to install a driver! HID works without!)

'TODO:
'temperature measurement

Declare Sub Usb_print(byval S As String * 63)

$crystal = 16000000
Config Clockdiv = 1
$regfile = "m32u4def.dat"
$hwstack = 200
$swstack = 200
$framesize = 200

Baud = 38400


'------------------------------------------------------------------------------
'    USB
'Interrupts
On Usb_gen Usb_isr_general
On Usb_com Usb_isr_communication

' For usb_lib_hid_v1_2.bas, the constants Mouse and Keyboard must be set:
Const Mouse = 0                                             'No mouse emulation
Const Keyboard = 0                                          'no keyboard remulation

'Include usb library without executing code (jump over)
Goto Init
$include "lib\usb_lib_hid_v1_3.bas"


Init:
Dim Usbstring As String * 63                                'String var for USB operations
Dim Usbstringbuf As String * 63 At Ep1_buf Overlay          'Buffer for USB transfer to PC
Dim Usblongcommand As String * 63 At Ep2_buf Overlay        'Buffer for USB transfer from PC
'' these strings are dimensioned for 63 characters as strings end with chr(0)
'' maybe 64 wouls also be OK?

Gosub Usb_init_device                                       'activate USB
'------------------------------------------------------------------------------

'  INITIALIZATIONS

'Timer3 Compare A -> interrupt every  second   for 16MHz crystal
Ocr3a = 62500
Config Timer3 = Timer , Prescale = 256 , Clear Timer = 1 , Compare A = Disconnect
On Oc3a Timer3_isr
''Enable Oc3a   (later)

'Pulse generator on output A
'Timer1 for pulse generator is configured in generator sub

'Serial interrupt
On Urxc Serialinterrupt
Enable Urxc
Dim Ok As Byte

'Switch continuous / on demand (jumper)
Config Pinb.0 = Input
Portb.0 = 1

'Trigger output
Triggerout Alias Portb.4                                    'Portc.6
Config Triggerout = Output

'Sync output
Config Portc.7 = Output

'LED
Config Portd.6 = Output
'Debug
Config Portd.7 = Output


'DS18B20
Dim Dsread(9) As Byte
Dim Itemperature As Integer At Dsread Overlay               'enthält Temp. in 0.0625°C
Dim Temperature As Single
Config 1wire = Portd.7


'ADC
Config Adc = Single , Prescaler = Auto , Reference = Internal
Start Adc
Dim Uadc0 As Single
Dim Uadc1 As Single
Dim Uadc2 As Single
Dim Uadc3 As Single
Dim Wadc0 As Word
Dim Wadc1 As Word
Dim Wadc2 As Word
Dim Wadc3 As Word
'ADC constants due to circuit:
Const Kadc0 = 0.010227272727272727                          '900k / 220k * 2.56 / 1024
Const Kadc1 = 0.010227272727272727

Const Kadc2 = 0.0295775
Const Kadc3 = 0.0295775
Const Kref2 = 15.2347787
Const Kref3 = 15.2347787


'ADC linear calibration factors:
Dim Ac(4) As Eram Single                                    'for Ukorr = a UM + b
Dim Bc(4) As Eram Single                                    'with Ac(i) = a, Bc(i) = b
Dim Cc(4) As Single
Dim Ummax(4) As Single                                      'measured value for Umasx=10V
Dim Ummin(4) As Single                                      'measured value for Umin=1V


Enable Interrupts

Dim Temperatureflag As Bit
Dim Seconds As Single
Dim Timecode As Byte                                        ' Code 0123 -> 1s / 0.1s / 10ms / 1ms
Timecode = "0"                                              ' 1s
'''Dim Printvaluesflag As Bit                                  'Printvalues yes/no

'Generator
Dim Period_us As Single
Dim Ctrvalue As Word
Dim Prescaleval As Word
Dim Frequency As Single

'---------------------------------------------------------------------------
' Temporary variables
Dim Tempstring As String * 20
Dim Tempstring2 As String * 63
Dim Stmp As Single
Dim Stmp2 As Single                                         'for cal. correction
Dim Ltmp As Long
Dim I As Long
Dim Newtime As Bit
Dim Btmp As Byte
'------------------------------------------------------------------------------
'Hi, I'm alive
For I = 1 To 10
   Toggle Portd.6                                           'LED
   Toggle Triggerout
   Waitms 50
Next I

Usb_print "# Analog logger ready"

'-----------------------------------------------------------------------------

'Calibration factors OK?  If not, use defaults
Gosub Check_calibration_factors

'***************************************************************************
'  MAIN LOOP

'If jumper not set: automatically begin to measure and transmit
Timecode = "0"
Gosub Startmeasure
                                            '1s
''If Pinb.1 = 1 Then Gosub Startmeasure

Do


      'If new time interval: calculate voltages and print values
      ' (print always if switch activated or print only if sequence started, until stop)
      If Newtime = 1 Then

          Newtime = 0
          Portd.6 = 1                                       'LED ON

      '-----  Block start
         'The marked block takes max. ca. 2.8ms for output to USB and 11ms for
         'output to USB and RS232
         'This defines the shortest possible time interval in continuous operation
         'For debugging and analysis: LED
         Portd.7 = 1
         Gosub Calculatevoltages                            'takes ca. 700us
         Portd.7 = 0
         '' debug:
         Waitus 100
         ''TODO If Temperatureflag = 1 Then Gosub Measuretemperature
         Portd.7 = 1
         Gosub Printvalues                                  'takes ca. 2ms for USB
         Portd.7 = 0
     '----   Block end


         Portd.6 = 0                                        'LED OFF

      End If


      'command over USB ? If yes put it into var.  ok (for 1 char command)
      If Ep2_flag = 1 Then
         If Ep2_cnt = 1 Then
            Ok = Ep2_buf(1)                                 'short command -> ok
         Else
             'Long command is in buffer = Usblongcommand
             Gosub Usb_menu
         End If
         Ep2_flag = 0
      End If

      'short command in var. ok  -> menu
       If Ok > 0 Then Gosub Menu

Loop
'***************************************************************************
'------------------------------------------------------------------------------
Measureadc:
' read 4 channels raw values

 Wadc0 = Getadc(0)
 Wadc1 = Getadc(1)
 Wadc2 = Getadc(4)
 Wadc3 = Getadc(5)
 Return
'------------------------------------------------------------------------------
Calculatevoltages:
'Convert raw values to voltages


 'Normal calculation      'max. 180us  instead of 480us  ------
 '   0...10V                    by direct Kadc

  Uadc0 = Wadc0 * Kadc0
  Uadc1 = Wadc1 * Kadc1

 '  -15...+15V
  Uadc2 = Wadc2 * Kadc2
  Uadc2 = Uadc2 - Kref2

  Uadc3 = Wadc3 * Kadc3
  Uadc3 = Uadc3 - Kref3
                                                '-------

 'Correction for channels 0123
 'Take care: CHnb is 0 based, arrays are 1 based!
   'CH0
   Stmp = Ac(1)
   Uadc0 = Uadc0 * Stmp
   Stmp = Bc(1)
   Uadc0 = Uadc0 + Stmp

   'CH1
   Stmp = Ac(2)
   Uadc1 = Uadc1 * Stmp
   Stmp = Bc(2)
   Uadc1 = Uadc1 + Stmp

   'CH2
   Stmp = Ac(3)
   Uadc2 = Uadc2 * Stmp
   Stmp = Bc(3)
   Uadc2 = Uadc2 + Stmp

   'CH3
   Stmp = Ac(4)
   Uadc3 = Uadc3 * Stmp
   Stmp = Bc(4)
   Uadc3 = Uadc3 + Stmp

Return

'-----------------------------------------------------------------------------
Measureall:
'Measure all channels and calculate voltages
    Gosub Measureadc
    Gosub Calculatevoltages
Return
'------------------------------------------------------------------------------
Measuretemperature:
'gemessene Temperatur steht in Variable Temperature
'1wire muss vorher konfiguriert sein

      'Messen
      1wreset
      1wwrite &HCC                                          'alle herhören
      1wwrite &H44                                          'Messen
      Waitus 200

      'auslesen
      1wreset
      1wwrite &HCC
      1wwrite &HBE                                          'RAM auslesen
      Dsread(1) = 1wread(9)                                 '9 Byte lesen

      Temperature = Itemperature * 0.5                      'DS1820
      'Temperature = Itemperature * 0.0625    'DS18B20
Return
'-------------------------------------------------------------------------------
Printvalues:
    'output values via RS232 and USB in modes 0 and 1 (1s and 100ms)
    'Usbstring and Tempstring are used as buffers

    'takes ca. 2ms for USB,  10ms for USB and RS232

     '------------------------------------------   ca. 2ms

      'time
      Select Case Timecode
            Case "0" : Seconds = I
            Case "1" : Seconds = I / 10
            Case "2" : Seconds = I / 100
            Case "4" : Seconds = I / 250
      End Select


      'Time
      Tempstring = Fusing(seconds , "#######.###")
      Tempstring = Tempstring + Chr(9)
      Usbstring = Tempstring

      'Voltage
      Tempstring = Fusing(uadc0 , "##.##")
      Tempstring = Tempstring + Chr(9)
      Usbstring = Usbstring + Tempstring

       Tempstring = Fusing(uadc1 , "##.##")
      Tempstring = Tempstring + Chr(9)
      Usbstring = Usbstring + Tempstring

      Tempstring = Fusing(uadc2 , "##.##")
      Tempstring = Tempstring + Chr(9)
      Usbstring = Usbstring + Tempstring

      Tempstring = Fusing(uadc3 , "##.##")
      Tempstring = Tempstring + Chr(9)
      Usbstring = Usbstring + Tempstring

     '---------------------------------------------  to here

      ''TODO
      ''If Temperatureflag = 1 Then Print Temperature;

      'output
      If Timecode < "2" Then
            'to USB and RS232 for dt = 1s, 100ms
            Usb_print Usbstring
      Else
            'only USB    for shorter dt
            Usbstringbuf = Usbstring
            Ep1_cnt = 64
            Ep1_flag = 1
      End If

Return
'-----------------------------------------------------------------------------

Sub Usb_print(s)
      'output s (max. 64 bytes) to USB and RS232

      ' -> USB
      ' Set number of bytes and flag,the rest is done by the library
      Usbstringbuf = S
      Ep1_cnt = 64
      Ep1_flag = 1

      ' -> RS232
      Print S

      ' to be sure that PC gets USB message, wait 1ms
      ''' this could be done in a better way depending on the size of the message
      Waitms 1
      ''' eventually not necessary if it is sure that s is not updated too fast
      '' but this would be the case if multiple Usb_print ... occur one after the other
End Sub

'-----------------------------------------------------------------------------

Menu:
      Select Case Ok
           Case "?" : Gosub Help
           Case "v" : Gosub Printversion
           Case "t" : Gosub Settime
           Case "s" : Gosub Startmeasure
           Case "0" : Gosub Start0123
           Case "1" : Gosub Start0123
           Case "2" : Gosub Start0123
           ''Case "3" : Gosub Start0123
           Case "4" : Gosub Start0123
           Case "x" : Gosub Stopmeasure
           ''Case "T" : Toggle Temperatureflag
           Case "g" : Gosub Generator
           Case "r" : Gosub Rect_generator_1
           Case "f" : Gosub Rect_generator_2
           Case "+" : Triggerout = 1
           Case "-" : Triggerout = 0

           Case "C" : Gosub Show_cal_factors
           Case "c" : Gosub Calibrate
           Case "%" : Gosub Set_calibration_factors
           Case "!" : Gosub Set_default_calibration
      End Select
      Ok = 0
Return
'----------------------------------------------------------------------------
Usb_menu:
' dispatch long USB commands
      Tempstring = Left(usblongcommand , 1)
      Usb_print Tempstring

      Select Case Tempstring
           Case "G"                                         'rect generator eg. "ur500" -> T = 500us
              'rect generator
              Tempstring = Mid(usblongcommand , 2)
              Usb_print Tempstring
              Period_us = Val(tempstring )
              Gosub Generator
              Gosub Calc_real_t
              Tempstring = Str(period_us)
              Usb_print Tempstring
      End Select
      Usblongcommand = ""
Return
'----------------------------------------------------------------------------
Printversion:
      Tempstring2 = "# " + Version(3)
      Usb_print Tempstring2
      Tempstring2 = "# " + Version()
      Usb_print Tempstring2
                 'Strange bug: "#" is ignored !
Return
'----------------------------------------------------------------------------
Help:
      Usb_print "Commands via RS232 or USB:"
      Usb_print "? = help"
      Usb_print "v = firmware version"
      'Usb_print "t = set time interval"
      'Usb_print "s = start"
      Usb_print "0 = start 1s"
      Usb_print "1 = start 100ms"
      Usb_print "2 = start 10ms"
      Usb_print "4 = start 4ms"
      Usb_print "x = stop (exit)"
      Usb_print "+ = Set trigger out"
      Usb_print "- = Reset trigger out"
      Usb_print "C = Show calibration coefficients"
      Usb_print "! = Reset calibration coefficients to a=1 and b=0"

      Usb_print " "
      Usb_print "Commands via RS232 only:"
      Usb_print "g = generator, output A"
      Usb_print "r = rect generator, output A, input period in us"
      Usb_print "f = rect generator, output A, input frequency"
      Usb_print "c = Calibrate with 10V and 1V source"
      Usb_print "% = set calibration coefficients manually"

      Usb_print " "
      Usb_print "Commands via USB only:"
      Usb_print "G<period value> e.g. G500 -> rect gen. T = 500us"

       ''Usb_print "T = toggle temperature logging"
Return



'-----------------------------------------------------------------
Settime:
'set interval interactively
      Disable Urxc
      Print "Set interval"
      Print "0 -> 1s"
      Print "1 -> 100ms"
      Print "2 -> 10ms"
      Print "3 -> 3ms"

      Do
          Timecode = Inkey()
      Loop Until Timecode > 0

      Gosub Settimeinterval
      Enable Urxc
Return
'----------------------------------------------------------------------------

Settimeinterval:

   Stop Timer3
   Timer3 = 0

      Select Case Timecode
         Case "0"
             ' 1s
             Ocr3a = 62500
             Config Timer3 = Timer , Prescale = 256 , Clear Timer = 1 , Compare A = Disconnect

         Case "1"
             '100ms
             Ocr3a = 6250
             Config Timer3 = Timer , Prescale = 256 , Clear Timer = 1 , Compare A = Disconnect
         Case "2"
             '10ms
             Ocr3a = 625
             Config Timer3 = Timer , Prescale = 256 , Clear Timer = 1 , Compare A = Disconnect
         Case "3"
             '3ms
             Ocr3a = 750
             Config Timer3 = Timer , Prescale = 64 , Clear Timer = 1 , Compare A = Disconnect
         Case "4"
             '4ms
             Ocr3a = 1000
             Config Timer3 = Timer , Prescale = 64 , Clear Timer = 1 , Compare A = Disconnect


      End Select
Return


'-------------------------------------------------------------------------------
Start0123:
' direct start for modes 0-3 by "0", ..."3"
   Timecode = Ok
   'continue with Startmeasure

Startmeasure:
' start by "s" with Timecode already set
   Triggerout = 1
   Gosub Settimeinterval


      'first measure for t=0:
      I = 0
      Gosub Measureadc

      Newtime = 1                                           'output by main program
      '''Printvaluesflag = 1

      'all other measures by timer interrupt
      Enable Oc3a


Return
'-------------------------------------------------------------------------------
Stopmeasure:
' stop in time modes 1s and 100ms
   Triggerout = 0
   Disable Oc3a
   Stop Timer3
   Timer3 = 0
   I = 0

Return
'-------------------------------------------------------------------------------

'-------------------------------------------------------------------------------

Timer3_isr:
'this interrupt controls time interval between measurements
'Timecode 0, 1 (slow) -> Measureadc all channels, output in main program every 1s/0.1s
    'incr i

    Portc.7 = 1


     '1s / 100ms / 10ms /3ms : measure and tell main program to output value
     Gosub Measureadc
     Newtime = 1
     Incr I

   Portc.7 = 0
 Return


'-------------------------------------------------------------------------------
Serialinterrupt:
'input serial command byte to variable ok
      Ok = Udr

Return
'-------------------------------------------------------------------------------

'    CALIBRATION
'    LINEAR CALIBRATION by function y = ax + b for all channels

Check_calibration_factors:
' If a = 0 or FFFFFFFF (never set), set a = 1
' If b = FFFFFFFF  (never set), set b = 0

   Disable Interrupts
    'check AC
    For I = 1 To 4
       Stmp = Ac(i)
       If Hex(stmp) = "FFFFFFFF" Or Stmp = 0 Then
            Stmp = 1
            Ac(i) = Stmp
            Stmp = 0
            Bc(i) = Stmp
       End If
    Next I

    'check BC
    For I = 1 To 4
       Stmp = Bc(i)
       If Hex(stmp) = "FFFFFFFF" Then
            Stmp = 0
            Bc(i) = Stmp

       End If
    Next I
    Enable Interrupts
Return
'-------------------------------------------------------------------------------
Set_calibration_factors:
' Interactively set calibration for all channels
      Disable Interrupts
      Print "Set calibration factors:"
      For I = 1 To 4
            Ltmp = I - 1
            Print "CH" ; Ltmp
            Input "A=" , Stmp
            Ac(i) = Stmp
            Input "B=" , Stmp
            Bc(i) = Stmp
      Next I
      Enable Interrupts
Return
'-----------------------------------------------------------------------------
Set_default_calibration:
' set a = 1 and b = 0 for all channels
      Disable Interrupts
      Print "calibration reset"
      For I = 1 To 4
            Stmp = 1
            Ac(i) = Stmp
            Stmp = 0
            Bc(i) = Stmp
      Next I
      Enable Interrupts
Return

'------------------------------------------------------------------------------
Show_cal_factors:

      'Disable Interrupts
      Usb_print "# Calibration factors:"
      For I = 1 To 4
            Stmp = Ac(i)
            Tempstring2 = Str(stmp) + Chr(9)
            Stmp = Bc(i)
            Tempstring2 = Tempstring2 + Str(stmp )
            Tempstring2 = "#" + Tempstring2
            Usb_print Tempstring2
      Next I
      'Enable Interrupts
Return


Show_cal_factors_old:

      'Disable Interrupts
      Print "Calibration factors:"
      For I = 1 To 4
            Stmp = Ac(i)
            Print Stmp ; Chr(9);
            Stmp = Bc(i)
            Print Stmp
      Next I
      'Enable Interrupts
Return
'-----------------------------------------------------------------------------
Calibrate:
'Calibration procedure
' 10V and 1V reference must be ready to use
' Calibration is reset!

    Gosub Set_default_calibration

    Disable Interrupts
    Print "Calibration reset!"

    '10V cal
    Print "Apply 10V to all IN!"
    Input "ready?" , Btmp
    Gosub Measureall

    Ummax(1) = Uadc0
    Ummax(2) = Uadc1
    Ummax(3) = Uadc2
    Ummax(4) = Uadc3

    Print "Measured for 10V: "
    For I = 1 To 4
       Print Ummax(i)
    Next I Stmp
    Print


    '1V cal
    Print "Now apply 1V to all IN!"
    Input "ready?" , Btmp
    Gosub Measureall

    Ummin(1) = Uadc0
    Ummin(2) = Uadc1
    Ummin(3) = Uadc2
    Ummin(4) = Uadc3

    Print "Measured for 1V: "
    For I = 1 To 4
       Print Ummin(i)
    Next I
    Print

    'Calculate coefficients a, b
    For I = 1 To 4

        Btmp = I - 1
        Print "CH" ; Btmp

        ' a = (Umax-Umin)/(UMmax-UMmin) = 9/(UMmax-UMmin)
        Stmp = Ummax(i) - Ummin(i)
        Stmp = 9 / Stmp
        Ac(i) = Stmp
        Print "A=" ; Stmp

        'b = Umax - a * Ummax
        Stmp = Stmp * Ummax(i)
        Stmp = 10 - Stmp
        Bc(i) = Stmp
        Print "B=" ; Stmp
    Next I
    Print "CAL OK"


    Enable Interrupts
Return

'******************************************************************************
'-------------------------------------------------------------------------------
'     GENERATOR
'-------------------------------------------------------------------------------
Rect_generator_1:
      Disable Urxc

      Input "Period/us=" , Period_us

      Gosub Generator
      Gosub Calc_real_t

      Print Period_us ; Chr(9) ; Ctrvalue ; Chr(9) ; Prescaleval

      Enable Urxc

Return
',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
Rect_generator_2:
      Disable Urxc

      Input "Frequency/Hz=" , Frequency
      Period_us = 1000000 / Frequency
      If Frequency = 0 Then Period_us = 0                   'switch off
      Gosub Generator
      Gosub Calc_real_t
      Frequency = 1000000 / Period_us
      Print Frequency ; Chr(9) ; Period_us ; Chr(9) ; Ctrvalue ; Chr(9) ; Prescaleval

      Enable Urxc

Return

',,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,


Generator:
'receives period value (in us) in Period_us (0 = switch off)
'and generates rect signal on OC1A = PortB.5

      Config Portb.5 = Output

      'set Prescale and OCR1A according to Period_us
      Select Case Period_us
         Case 0
            Tccr1b = 0                                      'Prescaler = 0 -> gen. disabled
            Portb.5 = 0

         Case Is < 8190
            Ctrvalue = Period_us * 8
            Ocr1a = Ctrvalue - 1
            Config Timer1 = Timer , Prescale = 1 , Clear Timer = 1 , Compare A = Toggle
            Prescaleval = 1

         Case Is < 65535
            Ctrvalue = Period_us
            Ocr1a = Ctrvalue - 1
            Config Timer1 = Timer , Prescale = 8 , Clear Timer = 1 , Compare A = Toggle
            Prescaleval = 8


         Case Is < 524280
            Ctrvalue = Period_us / 8
            Ocr1a = Ctrvalue - 1
            Config Timer1 = Timer , Prescale = 64 , Clear Timer = 1 , Compare A = Toggle
            Prescaleval = 64

         Case Is < 2097120
            Ctrvalue = Period_us / 32
            Ocr1a = Ctrvalue - 1
            Config Timer1 = Timer , Prescale = 256 , Clear Timer = 1 , Compare A = Toggle
            Prescaleval = 256

         Case Is < 8388480
            Ctrvalue = Period_us / 128
            Ocr1a = Ctrvalue - 1
            Config Timer1 = Timer , Prescale = 1024 , Clear Timer = 1 , Compare A = Toggle
            Prescaleval = 1024

         Case Else
            Usb_print "# Period too long"

      End Select

Return
'..............................................................................
Calc_real_t:
     'Tmin = 2*prescale*Tcrystal  = prescale * 2/16us
     'T = Tmin * (OCR1A+1)
     Period_us = Prescaleval / 8
     Ctrvalue = Ctrvalue + 1
     Period_us = Period_us * Ctrvalue

Return