edgeDetect.m 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. function timestamps = edgeDetect(signal, threshold, type)
  2. % edgeDetect
  3. %
  4. % Detects rising or falling edges of a signal whenever the signal crosses
  5. % the threshold.
  6. %
  7. %
  8. % Use timestamps = edgeDetect(signal, threshold, type)
  9. %
  10. % Variables fname and threshold are optional.
  11. %
  12. % signal: Name of the file to be opened. If the fname is omitted
  13. % the user will be prompted to select a file.
  14. %
  15. % threshold: The value used for threshold crossings. This function
  16. % will detect when the signal crosses this value.
  17. % DEFAULT: It will automatically choose the threshold at
  18. % 80% of the maximum value in the signal.
  19. %
  20. %
  21. % type: Contains the points in the signal where the threshold
  22. % crossing occurs.
  23. % DEFAULT: It will find the rising edges.
  24. %
  25. % Example 1:
  26. % timestamps = edgeDetect(signal, 1000);
  27. %
  28. % In the example above, the points where signal crosses value 1000
  29. % (rising edge) is detected and returned in variable timestamps.
  30. %
  31. % timestamps = edgeDetect(signal, 1000, 'falling');
  32. %
  33. % In the example above, the points where signal crosses value 1000
  34. % (falling edge) is detected and returned in variable timestamps.
  35. %
  36. % Kian Torab
  37. % kian@blackrockmicro.com
  38. % Blackrock Microsystems
  39. % Version 1.1.0.0
  40. %
  41. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  42. % Version History
  43. %
  44. % 1.0.0.0:
  45. % - Initial release.
  46. %
  47. % 1.1.0.0:
  48. % - Added automatic edge detection.
  49. % - Updated help.
  50. %
  51. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  52. %% Validations
  53. % Validating input arguments.
  54. if nargin < 1 || nargin > 3
  55. disp('Invalid number of input arguments. Use ''help edgeDetect'' for more information.');
  56. return;
  57. end
  58. if ~exist('threshold', 'var')
  59. threshold = 0.8 * max(signal);
  60. disp(['Threshold was not provided. It wss automatically calculated and set at ' num2str(threshold) '.']);
  61. end
  62. % Validating variable 'type'
  63. if ~exist('type', 'var')
  64. type = 'rising';
  65. end
  66. % Validating type and determining the threshold crossing points
  67. if strcmpi(type, 'rising')
  68. timestamps = signal>threshold;
  69. elseif strcmpi(type, 'falling')
  70. timestamps = signal<threshold;
  71. else
  72. disp('Type does not exist. Please type ''help edgeDetect'' to see all available types.');
  73. timestamps = 0;
  74. return;
  75. end
  76. % Finding all the points where the signal crosses the threshold
  77. timestamps = diff(timestamps);
  78. timestamps = find(timestamps==1);