/* Serial interface example By GllBhh for Fab Academy 2023 Based on AlexGyver example, but without any external libraries https://github.com/AlexGyver/tutorials/tree/master/parsing/parseSerial */ #define LED 0 #define BTN 1 int buttonState; //this variable tracks the state of the button, HIGH if not pressed, LOW if pressed int lastButtonState = LOW; //this variable tracks the last state of the button, HIGH if not pressed, LOW if pressed unsigned long tmr1; //global timer to track last button event int debounce = 50; // debounce delay to avoid false readings from button void setup() { Serial.begin(9600); pinMode(LED, OUTPUT); pinMode(BTN, INPUT_PULLUP); } /*from Arduino to PC 0,1 - Buttun press */ /*From PC to Arduino 0,(0..1) - LED on pin 0, where 0 - LED off, 1 - LED on */ void loop() { //digital Button debounce from 'Debounce' example // read the state of a Button into a local variable: int reading = digitalRead(BTN); // check to see if you just pressed the button // (i.e. the input went from LOW to HIGH), and you've waited long enough // since the last press to ignore any noise: // If the switch changed, due to noise or pressing: if (reading != lastButtonState) { //update timer when button pin changes state tmr1 = millis(); } if ((millis() - tmr1) > debounce) { // whatever the reading is at, it's been there for longer than the debounce // delay, so take it as the actual current state: // if the button state has changed: if (reading != buttonState) { //update button state buttonState = reading; // only if the new button state is LOW if (buttonState == LOW) { Serial.println("0,1"); } } } //update last button state lastButtonState = reading; //if there is something is serial buffer if (Serial.available()) { //we expect data in a format of ints separeted with ',': "key,val1,val2,val3,...,valn\n" //\n - new line (println) char buf[50]; //array to read from serial //get amount of bytes of incoming data int amount = Serial.readBytesUntil('\n', buf, 50); //close incoming data string by adding a NULL symbol to the end buf[amount] = '\0'; int data[10]; //buffer of ints int count = 0; //counter of ints char* offset = buf; //pointer to a char data type //(it holds the memory address of some other variable or array element or parameter or whatever, and in that address is a char) //https://www.arduino.cc/reference/en/language/structure/pointer-access-operators/dereference/ //next part will parse ONLY ints! chars will be parsed as 0 while (true) { data[count++] = atoi(offset); //write a number to a buffer offset = strchr(offset, ','); //search for next ',' char if (offset) offset++; //if not NULL - continue else break; //else - leave cycle } // print buffer //for (int i = 0; i < count; i++) Serial.println(data[i]); switch (data[0]) { case 0: //digitalWrite(LED, data[1]); analogWrite(LED, data[0]); break; case 1: break; case 2: break; } } }