Curiosity always seems to get the better of me. The only time i ever saw that _write error was when I tried to use printf without redefining it to Serial.printf. So i found the gcc++ getopt.h/.c online and it uses printf's in its function. So for for fun i change @luni's sketch to:
Code:
#include "Arduino.h"
#define printf Serial.printf
//#include <getopt.h>
#include <unistd.h>
/*
extern "C"
{
// this is required for getopt to output error messages
int _write(int handle, char *buf, int count)
{
return Serial.write(buf, count);
}
}
*/
void setup()
{
Serial.begin(0);
while (!Serial);
char *argv[] = {new char[10], new char[10], new char[10],new char[10],new char[10]};
int argc = 5;
strcpy(argv[0],"");
strcpy(argv[1],"-b val");
strcpy(argv[2],"-x");
strcpy(argv[3],"-c");
strcpy(argv[4],"-a");
int option;
while ((option = getopt(argc, argv, "ab:c")) != -1)
{
switch (option)
{
case 'a':
Serial.println("Flag a detected");
break;
case 'b':
Serial.print("option b detected, value:");
Serial.println(optarg);
break;
case 'c':
Serial.println("Flag c detected");
break;
default:
break;
}
}
Serial.println("done");
}
void loop()
{
}
. It compiled without error and ran. But the only output I got was:
Code:
option b detected, value: val
If I change unistd to #include <getopt.h> gives me the same output. However, if you change the getopt call to:
Code:
getopt(argc, argv, "ab:c::x"
it will output correctly:
Code:
option b detected, value: val
Flag c detected
Flag a detected
done
Maybe this will help
EDIT: looking at the test sample in getopt.c this is probably the way to go:
Code:
#include "Arduino.h"
#define printf Serial.printf
#include <getopt.h>
void setup()
{
Serial.begin(0);
while (!Serial);
char *argv[] = {new char[10], new char[10], new char[10],new char[10],new char[10]};
int argc = 5;
strcpy(argv[0],"");
strcpy(argv[1],"-b val");
strcpy(argv[2],"-a");
strcpy(argv[3],"-c");
strcpy(argv[4],"-x");
int option;
while ((option = getopt(argc, argv, "ab:c::x")) != -1)
{
switch (option)
{
case 'a':
Serial.println("Flag a detected");
break;
case 'b':
Serial.print("option b detected, value:");
Serial.println(optarg);
break;
case 'c':
Serial.println("Flag c detected");
break;
case '?':
break;
default:
printf ("?? getopt returned character code %c ??\n", option);
break;
}
}
Serial.println("done");
}
void loop()
{
}
which gives the following output:
Code:
option b detected, value: val
Flag a detected
Flag c detected
?? getopt returned character code x ??
done