i am newbie to this so i hope i can explain my problem clearly;
Arduino MEGA connected to PC via USB port.
I am using an encoder to trigger function to send data to pc, data is a simple string "A01" or "A02" when i turn encoder to opposite direction, when arduino sends that string to serial port PC answers with another string from serial and its something like "MCPHDGxxx" and arduino does if serial available gets the string and filter it to get and show that number on my 7-segment display. (xxx is a number between 000 and 359, and that number changes on PC screen when arduino send "A01" or "A02" string to PC)
When i don't send display data from PC to arduino, encoder function works as intended, changes numbers up and down rapidly on PC screen but when i try to send that "number" data to Arduino from serial port number on the PC screen changes so slowly like 1 point up/down per 2 sec even if i turn encoder continuously. Seems like receiving data from PC blocking my send data function until it's done.
Is it possible to make it work asynchronously?
Here is my sketch:
#include "DigitLedDisplay.h"
#define outputA 24
#define outputB 25
int aState;
int aLastState;
unsigned long lastButtonPress = 0;
long finalMCPHDGLong;
String ReceivedSerialString;
DigitLedDisplay ld = DigitLedDisplay(21, 22, 23);
void setup() {
pinMode (outputA,INPUT);
pinMode (outputB,INPUT);
Serial.begin (115200);
// Reads the initial state of the outputA
aLastState = digitalRead(outputA);
/* Set the brightness min:1, max:15 */
ld.setBright(10);
/* Set the digit count */
ld.setDigitLimit(8);
}
void loop() {
aState = digitalRead(outputA); // Reads the "current" state of the outputA
// If the previous and the current state of the outputA are different, that means a Pulse has occured
if (aState != aLastState){
// If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
if (digitalRead(outputB) != aState) {
if (millis() - lastButtonPress > 25) {
Serial.println("A01");
}
// Remember last button press event
lastButtonPress = millis();
} else {
if (millis() - lastButtonPress > 25) {
Serial.println("A02");
}
// Remember last button press event
lastButtonPress = millis();
}
}
aLastState = aState;
while (Serial.available() > 0){
ReceivedSerialString = Serial.readString();
if (ReceivedSerialString.substring(0,6) == "MCPHDG"){
String value = ReceivedSerialString.substring(6,9);
long val = value.toInt();
finalMCPHDGLong = val;
if((finalMCPHDGLong <= 99)){
ld.printDigit(0,7);
}if((finalMCPHDGLong <= 9)){
ld.printDigit(0,6);
}
ld.printDigit(val, 5);
}
}
}