Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. #include <Arduino.h>
  2.  
  3. // We communicate with the power board at 115200 baud.
  4. #define SERIAL_BAUD 115200
  5.  
  6. #define FW_VER 0
  7. #define trigPin 13
  8. #define echoPin 12
  9.  
  10. void setup() {
  11. Serial.begin(SERIAL_BAUD);
  12. }
  13.  
  14. int read_pin() {
  15. while (!Serial.available());
  16. int pin = Serial.read();
  17. return (int)(pin - 'a');
  18. }
  19.  
  20. void command_read() {
  21. int pin = read_pin();
  22. // Read from the expected pin.
  23. int level = digitalRead(pin);
  24. // Send back the result indicator.
  25. if (level == HIGH) {
  26. Serial.write('h');
  27. } else {
  28. Serial.write('l');
  29. }
  30. }
  31.  
  32. void command_analogue_read() {
  33. int pin = read_pin();
  34. int value = analogRead(pin);
  35. Serial.print(value);
  36. }
  37.  
  38. void command_write(int level) {
  39. int pin = read_pin();
  40. digitalWrite(pin, level);
  41. }
  42.  
  43. void command_mode(int mode) {
  44. int pin = read_pin();
  45. pinMode(pin, mode);
  46. }
  47. void getDist(){
  48. long duration, distance;
  49. digitalWrite(trigPin, LOW); // Added this line
  50. delayMicroseconds(2); // Added this line
  51. digitalWrite(trigPin, HIGH);
  52. // delayMicroseconds(1000); - Removed this line
  53. delayMicroseconds(10); // Added this line
  54. digitalWrite(trigPin, LOW);
  55. duration = pulseIn(echoPin, HIGH);
  56. distance = (duration/2) / 29.1;
  57. Serial.print(distance);
  58. Serial.println(" cm");
  59. }
  60.  
  61. void loop() {
  62. // Fetch all commands that are in the buffer
  63. while (Serial.available()) {
  64. int selected_command = Serial.read();
  65. // Do something different based on what we got:
  66. switch (selected_command) {
  67. case 'a':
  68. command_analogue_read();
  69. break;
  70. case 'd':
  71. getDist();
  72. break;
  73. case 'r':
  74. command_read();
  75. break;
  76. case 'l':
  77. command_write(LOW);
  78. break;
  79. case 'h':
  80. command_write(HIGH);
  81. break;
  82. case 'i':
  83. command_mode(INPUT);
  84. break;
  85. case 'o':
  86. command_mode(OUTPUT);
  87. break;
  88. case 'p':
  89. command_mode(INPUT_PULLUP);
  90. break;
  91. case 'v':
  92. Serial.print("SRcustom:");
  93. Serial.print(FW_VER);
  94. break;
  95. default:
  96. // A problem here: we do not know how to handle the command!
  97. // Just ignore this for now.
  98. break;
  99. }
  100. Serial.print("\n");
  101. }
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement