Arduino Serial.read can't add to a string - c++
I have this code:
void setup()
{
analogReference(INTERNAL);
Serial.begin(9600);
AtInit();
SendAt("RE");
xbeeLow = SendAt("SL");
xbeeFirmware = SendAt("VR");
xbeeHardware = SendAt("HV");
SendAt("WR");
closeAt();
}
bool AtInit(){
int loopCount = 0;
leds.setPixelColor(1, amber);
leds.show();
while(1){
delay(1100);
Serial.print("+++");
delay(1100);
String atInitResult = ReadLine( 1000 );
if(atInitResult){
leds.setPixelColor(1, green);
leds.show();
return true;
}
if(loopCount == 3){
leds.setPixelColor(1, red);
leds.show();
return false;
}else{
loopCount += 1;
}
}
}
String ReadLine( unsigned long timeout ){
char inByte;
unsigned long readLineStart = millis();
String response;
delay(timeout);
while(1){
if(Serial.available() > 0){
inByte = Serial.read();
Serial.print(inByte);
if(inByte == '\r'){
response = dataString;
dataString = "";
break;
}
dataString += inByte;
}
}
return response;
}
String SendAt( String command ){
String atResponse;
String atClose;
Serial.println("AT" + command);
atResponse = ReadLine( 500 );
Serial.print(F("*********>"));
Serial.print(atResponse);
Serial.println(F("<*********"));
return atResponse;
}
The sendAt fucntion calls the Readline to get Data from an xbee in AT command mode.
The Serial.prints are for debuging purpose.
Here is what i got on my terminal screen
+++OK
ATRE
OK
*********>OK<*********
ATSL
40B23B83
*********>40<*********
ATVR
8070
*********><*********
ATHV
2342
*********><*********
ATWR
OK
*********><*********
ATCN
OK
Why does the Serial.print just after the Serial.read() of the char itself acutally print the good caracter, even though the dataString += inByte doesn't seem to add the char to the actual string? It seems to work for the first few commands only, after that it doesn't add more.
Related
3x Arduino + ESP32 with ESP-NOW
The configuration on "machine" looks like this: Computer with custom app WPF C#, have connected ESP32-sender. On other side of room there is ESP32 as recaiver that have connected to it 3 arduino due, that controls a lot of stepper motors. My problem is, that if I send a single command all works great. Directly on other side it executes. The problem starts when there is a lot of commands to send. ESP32 starts to makes Delivery fail status and after that moment all further commands are lost. That's the code of Master-ESP connected to PC. Which arduino to send is decide by one of the symbols on begin of message "!,#,#" #include <esp_now.h> #include <WiFi.h> #include <Wire.h> uint8_t broadcastAddress[] = {0x94, 0xB9, 0x7E, 0xD0, 0x93, 0x64}; String inMess; typedef struct Message { char a[100]; } Message; // Variable to store if sending data was successful String success; Message message; Message send_message; esp_now_peer_info_t peerInfo; char incoming; String full = ""; bool text_done = false; bool sended = false; // Callback when data is sent void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { //Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success*" : "Delivery Fail*"); if (status ==0){ success = "Delivery Success :)"; text_done = false; full = ""; sended = false; } else{ success = "Delivery Fail :("; delay(10); sended = false; Serial.println(success); } } // Callback when data is received void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) { memcpy(&message, incomingData, sizeof(message)); Serial.println(message.a); } void setup() { // Init Serial Monitor Serial.begin(115200); // Set device as a Wi-Fi Station WiFi.mode(WIFI_STA); Serial.println(WiFi.macAddress()); // Init ESP-NOW if (esp_now_init() != ESP_OK) { Serial.println("Error initializing ESP-NOW"); return; } esp_now_register_send_cb(OnDataSent); // Register peer memcpy(peerInfo.peer_addr, broadcastAddress, 6); peerInfo.channel = 0; peerInfo.encrypt = false; // Add peer if (esp_now_add_peer(&peerInfo) != ESP_OK){ Serial.println("Failed to add peer"); return; } esp_now_register_recv_cb(OnDataRecv); } void loop() { if(Serial.available() > 0 && !text_done){ incoming = Serial.read(); if(incoming == '\n'){ text_done = true; full.trim(); full.toUpperCase(); } if(text_done == false){ full += incoming; } } if(text_done){ if(full[0] != '!' && full[0] != '#' && full[0] != '#'){ //check if text is worth sending to other esp text_done = false; full = ""; } } if(text_done){ if(!sended){ full.toCharArray(send_message.a,sizeof(send_message)); esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &send_message, sizeof(send_message)); if (result == ESP_OK) { //Serial.println("Sent success*"); sended = true; } else { Serial.println("Error sending*"); delay(10); } } } } That's the code of recaiver ESP #include <esp_now.h> #include <WiFi.h> #include <SoftwareSerial.h> #include <Wire.h> SoftwareSerial worker; SoftwareSerial tool; //Serial2 is Table, software serials are others uint8_t broadcastAddress[] = {0x7C, 0x9E, 0xBD, 0x4B, 0x47, 0xA4}; String outMess; String outMessTable; String outMessTool; String inMess; typedef struct Message { char a[100]; } Message; String success; Message message; Message send_message; bool sended = true; String again_message = ""; esp_now_peer_info_t peerInfo; void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { //Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail"); if (status == 0) { success = "Delivery Success :)"; sended = true; again_message = ""; } else { success = "Delivery Fail :("; sended = false; delay(5); } } void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) { memcpy(&message, incomingData, sizeof(message)); Serial.println(message.a); sendTo((String)message.a); } void setup() { // Init Serial Monitor Serial.begin(115200); Serial2.begin(115200, SERIAL_8N1, 16, 17); //rx tx worker.begin(57600, SWSERIAL_8N1, 25, 26, false); if (!worker) { Serial.println("Invalid SoftwareSerial pin configuration, check config"); while (1) { delay (1000); } } //rx tx tool.begin(57600, SWSERIAL_8N1, 32, 33, false); if (!tool) { Serial.println("Invalid SoftwareSerial pin configuration, check config"); while (1) { delay (1000); } } // Set device as a Wi-Fi Station WiFi.mode(WIFI_STA); Serial.println(WiFi.macAddress()); // Init ESP-NOW if (esp_now_init() != ESP_OK) { Serial.println("Error initializing ESP-NOW"); return; } // Once ESPNow is successfully Init, we will register for Send CB to // get the status of Trasnmitted packet esp_now_register_send_cb(OnDataSent); // Register peer memcpy(peerInfo.peer_addr, broadcastAddress, 6); peerInfo.channel = 0; peerInfo.encrypt = false; // Add peer if (esp_now_add_peer(&peerInfo) != ESP_OK) { Serial.println("Failed to add peer"); return; } // Register for a callback function that will be called when data is received esp_now_register_recv_cb(OnDataRecv); } void loop() { // Set values to send if(sended){ if (worker.available() > 0) {//! char t = worker.read(); if(t == '\n'){ outMess.trim(); sendToEsp(outMess,"!"); outMess = ""; } else{ outMess += t; } } }else{ if(again_message.length()>0){ delay(10); sendToEsp(again_message.substring(1),again_message.substring(0,1)); }else{ sended = true; } } if(sended){ if (tool.available() > 0) {//# char t = tool.read(); if(t == '\n'){ outMessTool.trim(); sendToEsp(outMessTool,"#"); outMessTool = ""; } else{ outMessTool += t; } } }else{ if(again_message.length()>0){ delay(10); sendToEsp(again_message.substring(1),again_message.substring(0,1)); }else{ sended = true; } } if(sended){ if (Serial2.available() > 0) { //# char t = Serial2.read(); if(t == '\n'){ outMessTable.trim(); sendToEsp(outMessTable,"#"); outMessTable = ""; }else{ outMessTable += t; } } }else{ if(again_message.length()>0){ delay(10); sendToEsp(again_message.substring(1),again_message.substring(0,1)); }else{ sended = true; } } if(Serial.available() > 0){ outMess = Serial.readStringUntil('\n'); //read command from pc outMess.trim(); // remove uneccesery spaces sendTo(outMess); } } void sendToEsp(String text, String which){ String mess = which + text; again_message = mess; mess.toCharArray(send_message.a,sizeof(send_message)); esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &send_message, sizeof(send_message)); if (result == ESP_OK) { // Serial.println("Sent with success"); } else { Serial.println("Error sending the data"); sended = true; again_message = ""; } } void sendTo(String outMess){ Serial.print("="); Serial.print(outMess); if(outMess[0] == '!'){ //worker worker.enableTx(true); worker.println(outMess.substring(1)); worker.enableTx(false); Serial.println("send to worker"); } if(outMess[0] == '#') {//table Serial2.println(outMess.substring(1)); Serial.println("send to table"); } if(outMess[0] == '#'){ //tool tool.enableTx(true); tool.println(outMess.substring(1)); tool.enableTx(false); Serial.println("send to tool"); } } If I send one message with a delay of writing next one by hand it works great. If the message is sended via c# very fast, esp32 is handling first few of them then losing on sending or recaiving, sometimes both of esp32 sometimes only one. How could I prevent that to make stable connection ?
PubSubClient ESP32 disconnected while receive message
I create a project to receive message from MQTT. My full code is here https://github.com/kamshory/OTP-Mini/blob/main/Server/Server.ino WiFiClient espClient; PubSubClient client(espClient); void setup() { char * mqttServer = "192.168.1.3"; client.setServer(mqttServer, 1883); client.setCallback(mqttCallback); } void mqttCallback(const char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived on topic: "); Serial.print(topic); Serial.print("Message: "); char * mqttTopic = "sms"; String messageTemp; for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); messageTemp += (char)payload[i]; } Serial.println(); // Feel free to add more if statements to control more GPIOs with MQTT // If a message is received on the topic esp32/output, you check if the message is either "on" or "off". // Changes the output state according to the message if (String(topic) == String(mqttTopic)) { } } void mqttReconnect() { Serial.print("WiFi status = "); Serial.println(WiFi.status()); char * clientId = "php"; char * mqttUsername = "user"; char * mqttPassword = "pass"; char * mqttTopic = "sms"; // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection "); // Attempt to connect if (client.connect(clientId, mqttUsername, mqttPassword)) { Serial.println("connected"); // Subscribe boolean sub = client.subscribe("sms"); Serial.println(sub); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } When ESP32 publish a message in a topic, the message is received by subscriber (I create the subscriber with Java). But when it try to receive the message with callback, the client is disconnected. I try to debug with edit library on file PubSubClient.cpp boolean PubSubClient::loop() { if (connected()) { unsigned long t = millis(); if ((t - lastInActivity > MQTT_KEEPALIVE*1000UL) || (t - lastOutActivity > MQTT_KEEPALIVE*1000UL)) { if (pingOutstanding) { this->_state = MQTT_CONNECTION_TIMEOUT; _client->stop(); return false; } else { buffer[0] = MQTTPINGREQ; buffer[1] = 0; _client->write(buffer,2); lastOutActivity = t; lastInActivity = t; pingOutstanding = true; } } if (_client->available()) { uint8_t llen; uint16_t len = readPacket(&llen); uint16_t msgId = 0; uint8_t *payload; if (len > 0) { lastInActivity = t; uint8_t type = buffer[0]&0xF0; if (type == MQTTPUBLISH) { if (callback) { uint16_t tl = (buffer[llen+1]<<8)+buffer[llen+2]; /* topic length in bytes */ memmove(buffer+llen+2,buffer+llen+3,tl); /* move topic inside buffer 1 byte to front */ buffer[llen+2+tl] = 0; /* end the topic as a 'C' string with \x00 */ char *topic = (char*) buffer+llen+2; // msgId only present for QOS>0 if ((buffer[0]&0x06) == MQTTQOS1) { msgId = (buffer[llen+3+tl]<<8)+buffer[llen+3+tl+1]; payload = buffer+llen+3+tl+2; callback(topic,payload,len-llen-3-tl-2); buffer[0] = MQTTPUBACK; buffer[1] = 2; buffer[2] = (msgId >> 8); buffer[3] = (msgId & 0xFF); _client->write(buffer,4); lastOutActivity = t; } else { payload = buffer+llen+3+tl; callback(topic,payload,len-llen-3-tl); } } } else if (type == MQTTPINGREQ) { buffer[0] = MQTTPINGRESP; buffer[1] = 0; _client->write(buffer,2); } else if (type == MQTTPINGRESP) { pingOutstanding = false; } } else if (!connected()) { // readPacket has closed the connection return false; } } return true; } return false; } The type value is 208 which is MQTTPINGRESP not 48 which is MQTTPUBLISH. So, where is the problem? Is my library or my code? I download library from https://www.arduino.cc/reference/en/libraries/pubsubclient/
Arduino compiler failing with error code - invalid types 'int[int]' for array subscript
Quite a bit of untested code but the only thing really concerning me at the moment is my DISPLAY variable. I don't see how it is much different than my FONT array (which works fine) yet DISPLAY is the one that gets 'invalid types 'int[int]' for array subscript' I should be able to index an array of integers with integers (at least I have been with FONT). #include <WiFiNINA.h> #include <NTPClient.h> #include <WiFiUdp.h> #include "font.h" const int PIXEL_WIDTH = 30; const int PIXEL_HEIGHT = 5; int DISPLAY[PIXEL_HEIGHT][PIXEL_WIDTH] = {}; bool MILI_TIME = false; String FORMATTING[2] = {"LONGS","SHORTH:LONGM"}; char ssid[] = "REMOVED"; // your network SSID (name) between the " " char pass[] = "REMOVED"; // your network password between the " " int keyIndex = 0; // your network key Index number (needed only for WEP) int status = WL_IDLE_STATUS; // connection status WiFiServer server(80); // server socket WiFiClient client = server.available(); WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP); int ledPin = LED_BUILTIN; void setup() { Serial.begin(9600); pinMode(ledPin, OUTPUT); while (!Serial); // dont do anything until there is a serial connection enable_WiFi(); connect_WiFi(); server.begin(); printWifiStatus(); timeClient.begin(); timeClient.setTimeOffset(-14400); } void loop() { timeClient.update(); client = server.available(); if (client) { printWEB(); } preRender(); } void preRender(){ String FILLED_FORMATTING[2] = FORMATTING; for(int i=0;i<2;i++){ FILLED_FORMATTING[i].replace("LONGH",leadWithZero(timeHours())); FILLED_FORMATTING[i].replace("LONGM",leadWithZero(timeMinutes())); FILLED_FORMATTING[i].replace("LONGS",leadWithZero(timeSeconds())); FILLED_FORMATTING[i].replace("SHORTH",timeHours()); FILLED_FORMATTING[i].replace("SHORTM",timeMinutes()); FILLED_FORMATTING[i].replace("SHORTS",timeSeconds()); } int x = 0; for(int i=0;i<FILLED_FORMATTING[0].length();i++){ int c_ID = charID(FILLED_FORMATTING[0][i]); if(c_ID < 38){ for(int j=0;j<5;j++){ DISPLAY[j][x] = FONT[c_ID][j][0]; x += 1; DISPLAY[j][x] = FONT[c_ID][j][1]; x += 1; DISPLAY[j][x] = FONT[c_ID][j][2]; x += 1; if(i != FILLED_FORMATTING[0].length()){ DISPLAY[j][x] = 0; x += 1; } } } } x = PIXEL_WIDTH-1; for(int i=FILLED_FORMATTING[1].length()-1;i>=0;i--){ int c_ID = charID(FILLED_FORMATTING[1][i]); if(c_ID < 38){ for(int j=0;j<5;j++){ DISPLAY[j][x] = FONT[c_ID][j][0]; x -= 1; DISPLAY[j][x] = FONT[c_ID][j][1]; x -= 1; DISPLAY[j][x] = FONT[c_ID][j][2]; x -= 1; if(i != 0){ DISPLAY[j][x] = 0; //<----------- compiler error here, and ofc all instances above x -= 1; } } } } } int charID(char c){ for(int i=0;i<FONT_ID.length();i++){ if(FONT_ID[i] == c){ return i; } } return 40; } String timeHours(){ if(MILI_TIME){ return String(timeClient.getHours()); } else{ return convFromMili(timeClient.getHours()); } } String timeMinutes(){ return String(timeClient.getMinutes()); } String timeSeconds(){ return String(timeClient.getSeconds()); } String leadWithZero(String t){ if(t.length() < 2){ t = "0"+t; return t; } } String convFromMili(int t){ if(t > 12){ t -= 12; }else if(t == 0){ t += 12; } String ts = String(t); return ts; } void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID()); // print your board's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); // print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm"); Serial.print("To see this page in action, open a browser to http://"); Serial.println(ip); } void enable_WiFi() { // check for the WiFi module: if (WiFi.status() == WL_NO_MODULE) { Serial.println("Communication with WiFi module failed!"); // don't continue while (true); } String fv = WiFi.firmwareVersion(); if (fv < "1.0.0") { Serial.println("Please upgrade the firmware"); } } void connect_WiFi() { while (status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); status = WiFi.begin(ssid, pass); delay(10000); } } void printWEB() { if (client) { // if you get a client, Serial.println("new client"); // print a message out the serial port String currentLine = ""; // make a String to hold incoming data from the client while (client.connected()) { // loop while the client's connected if (client.available()) { // if there's bytes to read from the client, char c = client.read(); // read a byte, then Serial.write(c); // print it out the serial monitor if (c == '\n') { // if the byte is a newline character // if the current line is blank, you got two newline characters in a row. // that's the end of the client HTTP request, so send a response: if (currentLine.length() == 0) { // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) // and a content-type so the client knows what's coming, then a blank line: client.println("HTTP/1.1 200 OK"); client.println("Content-type:text/html"); client.println(); //create the buttons client.print(WiFi.getTime()); client.print("<br>"); client.print(timeClient.getEpochTime()); client.print("<br>"); client.print(timeClient.getFormattedTime()); client.print("<br>"); client.print(timeClient.getDay()); client.print("<br>"); client.print(timeClient.getHours()); client.print("<br>"); client.print(timeClient.getMinutes()); client.print("<br>"); client.print(timeClient.getSeconds()); client.print("<br>"); client.print("<div style=\"display:block;padding-left:calc(50% - 150px);margin-bottom:50px\"><div style=\"background-color:#e3e3e3;width:300px;height:120px;font-size:50px;text-align:center;padding-top:50px\">ON</div></div>"); client.print("<div style=\"display:block;padding-left:calc(50% - 150px)\"><div style=\"background-color:#e3e3e3;width:300px;height:120px;font-size:50px;text-align:center;padding-top:50px\">OFF</div></div>"); // The HTTP response ends with another blank line: client.println(); // break out of the while loop: break; } else { // if you got a newline, then clear currentLine: currentLine = ""; } } else if (c != '\r') { // if you got anything else but a carriage return character, currentLine += c; // add it to the end of the currentLine } if (currentLine.endsWith("GET /H")) { digitalWrite(ledPin, HIGH); } if (currentLine.endsWith("GET /L")) { digitalWrite(ledPin, LOW); } if (currentLine.endsWith("%VAL")) { // Trim 'GET /' and '%VAL' currentLine.remove(0,5); currentLine.remove(currentLine.indexOf("%"),4); Serial.println(currentLine); Serial.println(); } } } // close the connection: client.stop(); Serial.println("client disconnected"); } } font.h: int FONT[37][5][3] = {{{1,1,1},{1,0,1},{1,0,1},{1,0,1},{1,1,1},},{{1,1,0},{0,1,0},{0,1,0},{0,1,0},{1,1,1},},{{1,1,1},{0,0,1},{1,1,1},{1,0,0},{1,1,1},},{{1,1,1},{0,0,1},{1,1,1},{0,0,1},{1,1,1},},{{1,0,1},{1,0,1},{1,1,1},{0,0,1},{0,0,1},},{{1,1,1},{1,0,0},{1,1,1},{0,0,1},{1,1,1},},{{1,1,1},{1,0,0},{1,1,1},{1,0,1},{1,1,1},},{{1,1,1},{0,0,1},{0,0,1},{0,0,1},{0,0,1},},{{1,1,1},{1,0,1},{1,1,1},{1,0,1},{1,1,1},},{{1,1,1},{1,0,1},{1,1,1},{0,0,1},{1,1,1},},{{1,1,1},{1,0,1},{1,1,1},{1,0,1},{1,0,1},},{{1,1,0},{1,0,1},{1,1,0},{1,0,1},{1,1,0},},{{1,1,1},{1,0,0},{1,0,0},{1,0,0},{1,1,1},},{{1,1,0},{1,0,1},{1,0,1},{1,0,1},{1,1,0},},{{1,1,1},{1,0,0},{1,1,1},{1,0,0},{1,1,1},},{{1,1,1},{1,0,0},{1,1,1},{1,0,0},{1,0,0},},{{1,1,1},{1,0,0},{1,0,1},{1,0,1},{1,1,1},},{{1,0,1},{1,0,1},{1,1,1},{1,0,1},{1,0,1},},{{1,1,1},{0,1,0},{0,1,0},{0,1,0},{1,1,1},},{{0,0,1},{0,0,1},{0,0,1},{1,0,1},{1,1,1},},{{1,0,1},{1,0,1},{1,1,0},{1,0,1},{1,0,1},},{{1,0,0},{1,0,0},{1,0,0},{1,0,0},{1,1,1},},{{1,1,1},{1,1,1},{1,0,1},{1,0,1},{1,0,1},},{{1,1,0},{1,0,1},{1,0,1},{1,0,1},{1,0,1},},{{1,1,1},{1,0,1},{1,0,1},{1,0,1},{1,1,1},},{{1,1,1},{1,0,1},{1,1,1},{1,0,0},{1,0,0},},{{1,1,1},{1,0,1},{1,0,1},{1,1,0},{0,0,1},},{{1,1,1},{1,0,1},{1,1,0},{1,0,1},{1,0,1},},{{0,1,1},{1,0,0},{0,1,0},{0,0,1},{1,1,0},},{{1,1,1},{0,1,0},{0,1,0},{0,1,0},{0,1,0},},{{1,0,1},{1,0,1},{1,0,1},{1,0,1},{1,1,1},},{{1,0,1},{1,0,1},{1,0,1},{0,1,0},{0,1,0},},{{1,0,1},{1,0,1},{1,0,1},{1,1,1},{1,1,1},},{{1,0,1},{1,0,1},{0,1,0},{1,0,1},{1,0,1},},{{1,0,1},{1,0,1},{1,1,1},{0,0,1},{1,1,1},},{{1,1,1},{0,0,1},{0,1,0},{1,0,0},{1,1,1},},{{0,0,0},{0,1,0},{0,0,0},{0,1,0},{0,0,0}}}; String FONT_ID = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ:"; did check - int D[5][30]; void setup() { } void loop() { D[0][0] = 0; } and of course its fine, so I'm just wondering where I went wrong in the mess above? and yes there's a good bit of mess/debugging stuff
Simple solution... don't use DISPLAY as a variable it seems. Changing to DISPLAY_ fixed it, figured the variable was defined as a normal integer somewhere... just not in my code.
Arduino Serial parsing
I'm working on an Arduino sketch and I'm trying to change a variable with serial. I'm using some example code that I found on arduino.cc to start with. I'm trying to modify the code with an "if statement" to update a variable timevar with integerFromPC; the problem I'm having is if I type a number higher than 4 digits like 99999 it prints out the wrong data and the variable timevar doesn't get updated correctly? I'm not sure what to do? unsigned long timevar = 1000000; const byte numChars = 32; char receivedChars[numChars]; char tempChars[numChars]; // temporary array for use when parsing // variables to hold the parsed data char messageFromPC[numChars] = {0}; int integerFromPC = 0; int ifpc = 0; float floatFromPC = 0.0; boolean newData = false; //============ void setup() { Serial.begin(9600); Serial.println("This demo expects 3 pieces of data - text, an integer and a floating point value"); Serial.println("Enter data in this style <HelloWorld, 12, 24.7> "); Serial.println(); } //============ void loop() { recvWithStartEndMarkers(); if (newData == true) { strcpy(tempChars, receivedChars); // this temporary copy is necessary to protect the original data // because strtok() used in parseData() replaces the commas with \0 parseData(); showParsedData(); newData = false; } } //============ void recvWithStartEndMarkers() { static boolean recvInProgress = false; static byte ndx = 0; char startMarker = '<'; char endMarker = '>'; char rc; while (Serial.available() > 0 && newData == false) { rc = Serial.read(); if (recvInProgress == true) { if (rc != endMarker) { receivedChars[ndx] = rc; ndx++; if (ndx >= numChars) { ndx = numChars - 1; } } else { receivedChars[ndx] = '\0'; // terminate the string recvInProgress = false; ndx = 0; newData = true; } } else if (rc == startMarker) { recvInProgress = true; } } } //============ void parseData() { // split the data into its parts char * strtokIndx; // this is used by strtok() as an index strtokIndx = strtok(tempChars,","); // get the first part - the string strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC strtokIndx = strtok(NULL, ","); // this continues where the previous call left off integerFromPC = atoi(strtokIndx); strtokIndx = strtok(NULL, ","); floatFromPC = atof(strtokIndx); // convert this part to a float } //============ void showParsedData() { if (strcmp(messageFromPC, "set time") == 0) timevar = integerFromPC; Serial.print("Time Set To "); Serial.println(integerFromPC); Serial.println(timevar); } //do other stuff
You declare int integerFromPC. int on Arduino is 16 bits. 99999 doesn't fit into 16 bits, so will appear mod 2^16 as 34463. Use long instead as you do for timeVar and it will be ok for up to +/- 2^31 .
How to store numbers in Arduino?
I have written this to an Arduino. char incomingbytea; char incomingbyteb; char incomingop; char result; void setup() { Serial.begin(9600); } void loop(){ incomingbytea = 0; incomingbyteb = 0; incomingop = 0; result = 0; bytea: if (Serial.available() > 0) { incomingbytea = Serial.read(); Serial.println("1ok"); Serial.println(incomingbytea); goto byteb; } goto bytea; byteb: if (Serial.available() > 0) { incomingbyteb = Serial.read(); Serial.println("2ok"); Serial.println(incomingbyteb); goto op; } goto byteb; op: if (Serial.available() > 0) { incomingop = Serial.read(); Serial.println("opok"); Serial.println(incomingop); goto oper; } goto op; oper: result = incomingbytea + incomingbyteb; Serial.println(result); Serial.println(incomingbytea); Serial.println(incomingbyteb); Serial.println(incomingop); } What I want to do is: - connect to serial (check) - collect 2 variables to add/subtract/multiply/divide later (check) - collect a variable to decide what to do with them 1-add, 2-subtract, etc. (check) - redirect the script to do the required operation (later) - print the result to serial (check) The problem is, when I enter 1 and 1 and 1(whatever, the third one doesn't count now) and I get 98 as a result. Any help? Maybe the variables are wrong?
First you should know the length of the number, and subtract 48 (48 is the ascii representation of 0) later multiply the number for 1, 10, 100, 1000, 10000, ... depending of the position of each number. For example: String "233" to integer, using custom method void setup() { Serial.begin(9600); } void loop() { String Numero1 = "40"; String Numero2 = "50"; double Suma = StringAInt(Numero1)+StringAInt(Numero2);//+ StringAInt(Numero2); Serial.println(Suma); } double StringAInt(String Dato) { String Numero = Dato; char Valores [Numero.length()+1]; Numero.toCharArray(Valores,Numero.length()+1); double NumeroEnt = 0; for(int i = 0; i<Numero.length(); i++) { int NumValores = Valores[i]; NumValores-=48; double MultPor = pow(10,Numero.length()-(i+1)); NumeroEnt += (NumValores*MultPor); //Serial.println(NumValores*MultPor); } return NumeroEnt; } Now you only need build a string with the data received from serial port, and you can do math simply.