I have had a bit of trouble getting my Arduino and Nextion Touch Screen to communicate through serial without “speaking over each other”, if that makes any sense. I have made a basic sketch which sends some information to the Nextion, like updating the waveform and a progress bar, but I also send variables from the Nextion to the Arduino which at the moment just changes an LED from on to off.
Previously my code was a total mess and every second command that got sent from the Nextion would not even be registered by the Arduino.
I have now gotten to the point where there is a basic master/slave protocol between the two and it is working allot better, but there are still some hiccups and I was wondering if anyone would be able to provide some help.
Here is the code for my Arduino:
long interval = 500;
long preMillis = 0;
String dat = "";
#include "Nextion.h"
NexWaveform s0 = NexWaveform(1, 1, "s0");
void setup() {
nexInit();
Serial.begin(9600);
pinMode(A0, INPUT);
pinMode(10, OUTPUT);
}
void loop() {
unsigned long curntMillis = millis();
if(preMillis-curntMillis>interval){
progBar();
preMillis=curntMillis;
}
sButton();
}
void progBar() {
int val = analogRead(0);
val = map(val, 0, 1023, 0, 100);
Serial.print("j0.val=");
Serial.print(val/2);
Serial.write(0xff);
Serial.write(0xff);
Serial.write(0xff);
s0.addValue(0, val);
if (val > 50){
Serial.print("p2.pic=57");
Serial.write(0xff);
Serial.write(0xff);
Serial.write(0xff);
}else if (val < 50){
Serial.print("p2.pic=56");
Serial.write(0xff);
Serial.write(0xff);
Serial.write(0xff);
}
}
void sButton(){
dat = Serial.readString();
Serial.print("va0.val=1");
Serial.write(0xff);
Serial.write(0xff);
Serial.write(0xff);
Serial.print(dat);
delay(50);
if (dat == "a1"){
digitalWrite(10, HIGH);
}else if(dat == "a0"){
digitalWrite(10, LOW);
}
dat = "";
}
The code I used in the Nextion Editor is in the attachments.