Advertisement
Guest User

Untitled

a guest
May 14th, 2021
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. /*
  2. Blink without Delay from Arduino example files.
  3. Modified to listen for and respond to serial input.
  4.  
  5. This version accepts up to 10 chars input and ignores the excess.
  6. The buffer is sent back when a newline character is read.
  7. */
  8.  
  9.  
  10. // blink without delay stuff
  11. const int ledPin = LED_BUILTIN; // the number of the LED pin
  12. int ledState = LOW; // ledState used to set the LED
  13. unsigned long previousMillis = 0; // will store last time LED was updated
  14. const long interval = 200; // interval at which to blink (milliseconds)
  15.  
  16. void blink_led(void)
  17. {
  18. unsigned long currentMillis = millis();
  19.  
  20. if (currentMillis - previousMillis >= interval)
  21. {
  22. previousMillis = currentMillis;
  23.  
  24. if (ledState == LOW)
  25. {
  26. ledState = HIGH;
  27. } else
  28. {
  29. ledState = LOW;
  30. }
  31.  
  32. digitalWrite(ledPin, ledState);
  33. }
  34. }
  35.  
  36.  
  37. // buffer to assemble complete input lines in
  38. #define InBuffSize 10 // size of buffer
  39. char InBuff[InBuffSize + 1] = {'\0'}; // buffer with initial '\0'
  40. int InBuffIndex = 0; // index of next char to fill
  41.  
  42. void check_serial(void)
  43. {
  44. // if no serial input, do nothing
  45. while (Serial.available() > 0)
  46. {
  47. // read the incoming byte:
  48. char in_byte = Serial.read();
  49.  
  50. if (in_byte == '\n')
  51. {
  52. // end of command, return what was sent
  53. // this is where you might analyse the input string, get a number, etc
  54. Serial.print("Got: '");
  55. Serial.print(InBuff);
  56. Serial.println("'");
  57.  
  58. // set buffer back to empty state
  59. InBuffIndex = 0;
  60. InBuff[0] = '\0';
  61. }
  62. else if (InBuffIndex < InBuffSize)
  63. {
  64. // save the character in the buffer if not already overflowed
  65. InBuff[InBuffIndex] = in_byte;
  66. ++InBuffIndex;
  67. InBuff[InBuffIndex] = '\0'; // make sure string always '\0' terminated
  68. }
  69. }
  70. }
  71.  
  72. void setup()
  73. {
  74. Serial.begin(115200);
  75. pinMode(ledPin, OUTPUT);
  76. }
  77.  
  78. void loop()
  79. {
  80. blink_led();
  81. check_serial();
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement