Hello,
I've been having a lot of trouble getting my Arduino Mega 2560 to talk to my computer running a C++ program. I need to control a lot of motors with the Arduino and the direction and PWM duty cycle (0-255) are sent over by the computer using a message format where 's' is the start character, 'm' starts the sequence for each motor and 'x' delineates the two values sent for each motor. So for example 'sm1x255m0x150' would turn one motor in direction 1 with magnitude 255 and another one in direction 0 with magnitude 150.
The problem starts when converting this message to integers for writing to the pins. I think I'm using atoi() incorrectly because the output I get in the C++ console is just zeros rather than the values I've sent. What am I doing wrong?
This is the Arduino code (only uses one motor):
#include <stdlib.h>
byte dir_pin=52;
byte pwm_pin=10;
char charRead;
char buf1[2];
char buf2[4];
unsigned int dir, pwm;
void setup() {
Serial.begin(9600);
pinMode(dir_pin, OUTPUT);
pinMode(pwm_pin, OUTPUT);
// buf1[1]='\0';
// buf2[3]='\0';
// memset(buf1, '\0', 1);
// memset(buf2, '\0', 3);
}
void loop() {
if(Serial.available()){
charRead=Serial.read();
if(charRead=='s'){
charRead=Serial.read();
if(charRead=='m'){
buf1[0]=Serial.read();
}
charRead=Serial.read();
if(charRead=='x'){
buf2[0]=Serial.read();
buf2[1]=Serial.read();
buf2[2]=Serial.read();
}
}
dir=atoi(buf1);
pwm=atoi(buf2);
//Serial.println(buf1);
//Serial.println(buf2);
Serial.println(dir,DEC);
Serial.println(pwm,DEC);
}
analogWrite(pwm_pin,pwm);
digitalWrite(dir_pin,dir);
}
This is the C++ code running on the computer:
#include <iostream>
#include "SerialClass.h"
#include <stdio.h>
#include <string.h>
using namespace std;
char buffer[20];
char test[20];
char to_send[1];
int main() {
cout << "Hello" << endl;
Serial arduino("COM4");
sprintf(to_send,"sm%dx%d", 1, 150);
arduino.WriteData( to_send , strlen(to_send));
cout << "Data sent to Arduino: " << to_send<<endl;
Sleep(100);
arduino.ReadData(buffer,20);
arduino.~Serial();
cout << "Data received from Arduino:\n" << buffer << endl;
return 0;
}