Advertisement
sinned6915

caliper sketch 2

Oct 24th, 2020
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. //
  2. //Digital caliper code to read the value off of a cheap set of digital calipers
  3. //By Making Stuff Youtube channel https://www.youtube.com/c/makingstuff
  4. //This code is open source and in the public domain.
  5.  
  6. const byte clockPin = 2; //attach to clock pin on calipers
  7. const byte dataPin = 3; //attach to data pin on calipers
  8.  
  9. //Milliseconds to wait until starting a new value
  10. //This can be a different value depending on which flavor caliper you are using.
  11. const int cycleTime = 50;
  12.  
  13. unsigned volatile int clockFlag = 0;
  14.  
  15. long now = 0;
  16. long lastInterrupt = 0;
  17. long value = 0;
  18.  
  19. float finalValue = 0;
  20. float previousValue = 0;
  21.  
  22. int newValue = 0;
  23. int sign = 1;
  24. int currentBit = 1;
  25.  
  26. void setup() {
  27. Serial.begin(115200);
  28. Serial.println("void setup start");
  29. Serial.println("Caliper Test Sketch");
  30. pinMode(clockPin, INPUT);
  31. pinMode(dataPin, INPUT);
  32.  
  33.  
  34. //We have to take the value on the RISING edge instead of FALLING
  35. //because it is possible that the first bit will be missed and this
  36. //causes the value to be off by .01mm.
  37. attachInterrupt(digitalPinToInterrupt(clockPin), clockISR, RISING);
  38. Serial.println("void setup end");
  39. }
  40.  
  41. void loop() {
  42. // Serial.println("void loop start");
  43. if(newValue)
  44. {
  45. if(finalValue != previousValue) {
  46. previousValue = finalValue;
  47. Serial.println(finalValue,2);
  48. }
  49. newValue = 0;
  50. }
  51.  
  52. //The ISR Can't handle the arduino command millis()
  53. //because it uses interrupts to count. The ISR will
  54. //set the clockFlag and the clockFlag will trigger
  55. //a call the decode routine outside of an ISR.
  56. if(clockFlag == 1)
  57. {
  58. clockFlag = 0;
  59. decode();
  60. }
  61.  
  62. }
  63.  
  64. void decode(){
  65. unsigned char dataIn;
  66. dataIn = digitalRead(dataPin);
  67.  
  68. now = millis();
  69.  
  70. if((now - lastInterrupt) > cycleTime)
  71. {
  72. finalValue = (value * sign) / 100.00;
  73. currentBit = 0;
  74. value = 0;
  75. sign = 1;
  76. newValue = 1;
  77. }
  78. else if (currentBit < 16 )
  79. {
  80.  
  81. if (dataIn == 0)
  82. {
  83. if (currentBit < 16) {
  84. value |= 1 << currentBit;
  85. }
  86. else if (currentBit == 20) {
  87. sign = -1;
  88. }
  89.  
  90. }
  91.  
  92. currentBit++;
  93.  
  94. }
  95.  
  96. lastInterrupt = now;
  97.  
  98. }
  99.  
  100. void clockISR(){
  101. clockFlag = 1;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement