I'm having trouble with my code.. Here's the background: I've linked up my bluetooth to my phone, and I want to be able to send messages to the arduino. However, when I type to send a word, it sends out the characters individually. So now I'm trying to write code that will buffer the characters and will only print when I type a period. Here's my code:
Any tips? BTW, I'm using 46 because I think that equals the "." yeah? =)
const int SENS_PIN = A0;
const int LED_PIN = 13;
int sensorValue = 0;
int x = 0;
int words[100];
boolean toggle = true;
void setup()
{
Serial.begin(9600);
pinMode(13, OUTPUT);
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
digitalWrite(2, LOW);
digitalWrite(3, HIGH);
}
void loop()
{
inputbuffer();
}
void inputbuffer()
{
if (Serial.available())
{
words[x] = Serial.read();
if(words[x] = 46)
{
int i;
Serial.print("Got: ");
for (i = 0; i < x; i++)
{
Serial.print(words[i]);
}
Serial.println("");
}
Serial.print(words[x]);
digitalWrite(LED_PIN, toggle); // toggle the LED
toggle = !toggle;
x = x+1;
}
}
BTW, I'm using 46 because I think that equals the "."
Then, why not use '.'?
int words[100];
One does not read ints from the serial port. One does not read words from the serial port.
void loop()
{
inputbuffer();
}
Could you maybe add a few more useless blank lines?
if(words[x] = 46)
Assigning 46 to words[x] will always succeed, so the test will always be true. ==?
The words array should have a much better name. The type should be char. After each character is added, a NULL needs to be added after it (but don't increment the index again).
for (i = 0; i < x; i++)
{
Serial.print(words[i]);
}
If you properly NULL terminated the array, and it was the right size/type, you wouldn't need a for loop to print it.
At some point, it might be a good idea to reset i to 0.
You could try something like below substituting a . for the , as the word delimiter.
//zoomkat 3-5-12 simple delimited ',' string parce
//from serial port input (via serial monitor)
//and print result out serial port
// CR/LF could also be a delimiter
String readString;
void setup() {
Serial.begin(9600);
Serial.println("serial delimit test 1.0"); // so I can keep track of what is loaded
}
void loop() {
//expect a string like wer,qwe rty,123 456,hyre kjhg,
//or like hello world,who are you?,bye!,
if (Serial.available()) {
char c = Serial.read(); //gets one byte from serial buffer
if (c == ',') {
//do stuff
Serial.println(readString); //prints string to serial port out
readString=""; //clears variable for new input
}
else {
readString += c; //makes the string readString
}
}
}
This is does not directly answer your question, but if you are trying to control your project via text commands over a serial interface I have developed a library that might interest you.
Its called CommandLine and gives you a unix or dos like command line interface on your serial port or any device that implements the Arduino Stream interface.