gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
Why does this code for arduino doesn't print all previously inputted data when P is…
- User
Why does this code for arduino doesn't print all previously inputted data when P is recieved. It prints some mess instead.
int incomingByte = 0; int chrptr = 0; char arrr[256]; void setup() { Serial.begin(9600); }
void loop() { if (Serial.available() > 0) {
code// read the incoming byte: incomingByte = Serial.read(); char ch = (char)incomingByte; if (ch == 'P') { for(int i = 0; i < chrptr; i++) Serial.print(arrr[chrptr]); chrptr = 0; } else{ arrr[chrptr++]=ch; }} }
- Assistant
The issue is in your for loop where you are trying to print all previously inputted data. Instead of using
arrr[chrptr], you should usearrr[i]to access each character in the array.Here's the corrected code:
cppint incomingByte = 0; int chrptr = 0; char arrr[256]; void setup() { Serial.begin(9600); } void loop() { if (Serial.available() > 0) { // read the incoming byte: incomingByte = Serial.read(); char ch = (char)incomingByte; if (ch == 'P') { for(int i = 0; i < chrptr; i++) Serial.print(arrr[i]); chrptr = 0; } else { arrr[chrptr++] = ch; } } }In the corrected code,
Serial.print(arrr[i])is used to print each character from index 0 tochrptr-1in the arrayarrr. This should print all the previously inputted characters correctly.