#This portion of the script is derived from some of the examples from Altera
 
global usbblaster_name
global test_device

set jtag_instance 1

# List all available programming hardwares, and select the USBBlaster.
# (Note: this example assumes only one USBBlaster connected.)
# Programming Hardwares:
foreach hardware_name [get_hardware_names] {
   puts $hardware_name
    if { [string match "USB-Blaster*" $hardware_name] } {
        set usbblaster_name $hardware_name
    }
}
 
puts "\nSelect JTAG chain connected to $usbblaster_name.\n";
 
# List all devices on the chain, and select the first device on the chain.
#Devices on the JTAG chain:
 
foreach device_name [get_device_names -hardware_name $usbblaster_name] {
#   puts $device_name
    if { [string match "@1*" $device_name] } {
        set test_device $device_name
    }
}
puts "\nSelect device: $test_device.\n";
 
# Open device
proc openport {} {
    global usbblaster_name
        global test_device
    open_device -hardware_name $usbblaster_name -device_name $test_device
}
 
# Close device.  Just used if communication error occurs
proc closeport { } {
    catch {device_unlock}
    catch {close_device}
}
 
proc testit {regNum} {
    global jtag_instance
    openport
    device_lock -timeout 10000
    puts "Read Virtual register #$regNum (sample #[device_virtual_ir_shift -no_captured_ir_value -instance_index $jtag_instance -ir_value $regNum]): [device_virtual_dr_shift -instance_index $jtag_instance  -length 8 -value_in_hex]"
    closeport
}

proc readReg {regNum} {
    global jtag_instance
    openport
    device_lock -timeout 10000
    device_virtual_ir_shift -no_captured_ir_value -instance_index $jtag_instance -ir_value $regNum
    puts "Read Virtual register #$regNum [device_virtual_dr_shift -instance_index $jtag_instance  -length 8 -value_in_hex]"
    closeport
}

proc writeReg {regNum regValue} {
    global jtag_instance
    openport
    device_lock -timeout 10000
    puts "Write Virtual register #$regNum = $regValue"
    set effReg [expr $regNum + 0x08]
    device_virtual_ir_shift -no_captured_ir_value -instance_index $jtag_instance -ir_value $effReg
    device_virtual_dr_shift -instance_index $jtag_instance -no_captured_dr_value -dr_value $regValue -length 8 -value_in_hex
    closeport
}
