Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Blink without Delay from Arduino example files.
- Modified to listen for and respond to serial input.
- This version accepts up to 10 chars input and ignores the excess.
- The buffer is sent back when a newline character is read.
- */
- // blink without delay stuff
- const int ledPin = LED_BUILTIN; // the number of the LED pin
- int ledState = LOW; // ledState used to set the LED
- unsigned long previousMillis = 0; // will store last time LED was updated
- const long interval = 200; // interval at which to blink (milliseconds)
- void blink_led(void)
- {
- unsigned long currentMillis = millis();
- if (currentMillis - previousMillis >= interval)
- {
- previousMillis = currentMillis;
- if (ledState == LOW)
- {
- ledState = HIGH;
- } else
- {
- ledState = LOW;
- }
- digitalWrite(ledPin, ledState);
- }
- }
- // buffer to assemble complete input lines in
- #define InBuffSize 10 // size of buffer
- char InBuff[InBuffSize + 1] = {'\0'}; // buffer with initial '\0'
- int InBuffIndex = 0; // index of next char to fill
- void check_serial(void)
- {
- // if no serial input, do nothing
- while (Serial.available() > 0)
- {
- // read the incoming byte:
- char in_byte = Serial.read();
- if (in_byte == '\n')
- {
- // end of command, return what was sent
- // this is where you might analyse the input string, get a number, etc
- Serial.print("Got: '");
- Serial.print(InBuff);
- Serial.println("'");
- // set buffer back to empty state
- InBuffIndex = 0;
- InBuff[0] = '\0';
- }
- else if (InBuffIndex < InBuffSize)
- {
- // save the character in the buffer if not already overflowed
- InBuff[InBuffIndex] = in_byte;
- ++InBuffIndex;
- InBuff[InBuffIndex] = '\0'; // make sure string always '\0' terminated
- }
- }
- }
- void setup()
- {
- Serial.begin(115200);
- pinMode(ledPin, OUTPUT);
- }
- void loop()
- {
- blink_led();
- check_serial();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement