Arduino passing char to function - arduino

I apologize if this is a stupid question (It probably is) but I am having a hard time getting a function to work correctly.
My code as it stands:
#define photoPin A0
char photoCode[] = "L";
void loop(void) {
analogSensor(photoPin, photoCode);
delay(5000);
}
void analogSensor(int sensorPin, char* sensorCode) {
//Poll the Photo Cell and append that to the buffer
int sensorValue=analogRead(sensorPin);
Serial.print(sensorCode);
sprintf(buf + strlen(buf), "," + sensorCode + ":%04i", sensorValue);
}
When I try to compile this, I get the following message:
In function 'void analogSensor(int, char*)':
i2c_Sensor:104: error: invalid operands of types 'const char [2]' and 'char*' to binary 'operator+'
But, if I comment out the sprintf line, it compiles fine, and ever 5 seconds, an "L" prints out on the screen. Ultimately, I am confused as all get out, and don't know where to turn at this point.
Any help is appreciated.

The last one the formatting got borked :)
I'm afriad you cant concatenate char* with the + operator :) You'd have to call sprintf or strcat :) See your local man pages.
Instead of this:
sprintf(buf + strlen(buf), "," + sensorCode + ":%04i", sensorValue);
Try this:
sprintf( buf+strlen(buf), ",%s:%04i", sensorCode, sensorValue );

Related

Arduino strange behaviour dtostrf

I do not know what's wrong with this code:
#include<stdlib.h>
void setup() {
Serial.begin(115200);
char dataH[5];
char dataC[5];
char dataF[5];
float h = 56.00;
float c = 31.50;
float f = 88.70;
dtostrf(h,5,2,dataH);
dtostrf(c,5,2,dataC);
dtostrf(f,5,2,dataF);
Serial.println(dataH);
Serial.println(dataC);
Serial.println(dataF);
}
void loop() {
// put your main code here, to run repeatedly:
}
I am expecting these as the result:
56.00
31.50
88.70
Instead, this is what I got:
blank
blank
88.70
The first 2 lines were blank (i wrote with text blank otherwise it will skipped by stackoverflow. :(
You should declare your character arrays as
char dataH[6];
char dataC[6];
char dataF[6];
so that they have space to store '\0' at the end
Okay, this my fault. After looking to its doc, I need to create buffer.
char buff[5];
dataH = dtostrf(h,5,2,buff);
I think the buff will immediately garbage collected and will be gone if not consume in next statement.

How to print Integer alongside String Arduino?

I am trying to print an integer alongside a string but it's not really working out and am getting confused.
int cmdSeries = 3;
Serial.println("Series : " + cmdSeries);// That's where the problem occur
In visual basic we used to do it this way:
Dim cmdSeries As Integer
Console.Writeline(""Series : {0}", cmdSeries)
So i've tried it with Serial.println but it returns this error :
call of overloaded 'println(const char [14], int&)' is ambiguous
Can anyone help my out, I want to achieve this without using any libraries and in a clean way.
There is a huge difference between Arduino String class and regular C-string.
The first one overloads addition operator, but there is almost excessive usage of dynamic memory. Mainly if you use something like:
String sth = String("blabla") + intVar + "something else" + floatVar;
Much better is just using:
Serial.print("Series : ");
Serial.println(cmdSeries);
Btw, this string literal resides in Flash and RAM memory, so if you want to force using flash only:
Serial.print(F("Series : "));
But it's for AVR based Arduinos only. This macro can save a lots of RAM, if you are using lots of literals.
EDIT:
Sometimes I use this:
template <class T> inline Print & operator<<(Print & p, const T & val) {
p.print(val);
return p;
}
// ...
Serial << F("Text ") << intVar << F("...") << "\n";
It prints each part separately, no concatenations or so.
Try this
int cmdSeries = 3;
Serial.println(String("Series : ") + cmdSeries);

Finding a specific character in a file in Qt

How can i find a specific character in a QFile which has a text in it?
for example i have ' $5000 ' written somewhere in my file. in want to find the "$" sign so i will realize that I've reached the number.
I tried using QString QTextStream::read(qint64 maxlen) by putting 1 as the maxlen :
QFile myfile("myfile.txt");
myfile.open(QIODevice::ReadWrite | QIODevice::Text);
QTextStream myfile_stream(&myfile);
while(! myfile_stream.atEnd())
{
if( myfile_stream.read(1) == '$')
{
qDebug()<<"found";
break;
}
}
and i get "error: invalid conversion from 'char' to 'const char* "
i also tried using the operator[] but apparently it can't be used for files.
Read in a line at a time and search the text that you've read in
QTextStream stream(&myFile);
QString line;
do
{
line = stream.readLine();
if(line.contains("$"))
{
qDebug()<<"found";
break;
}
} while (!line.isNull());
The error message you've posted doesn't match the issue in your code. Possibly the error was caused by something else.
QTextStream::read returns QString. You can't compare QString and const char* directly, but operator[] can help:
QString s = stream.read(1);
if (s.count() == 1) {
if (s[0] == '$') {
//...
}
}
However reading a file by too small pieces will be very slow. If your file is small enough, you can read it all at once:
QString s = stream.readAll();
int index = s.indexOf('$');
If your file is large, it's better to read file by small chunks (1024 bytes for example) and calculate the index of found character using indexOf result and count of already read chunks.
a single char could be read with
QTextStream myfile_stream(&myfile);
QChar c;
while (!myfile_stream.atEnd())
myfile_stream >> c;
if (c == '$') {
...
}
myfile_stream.read(1) - this is not good practice, you should not read from file one byte at a time. Either read the entire file, or buffered/line by line if there is a risk for the file to be too big to fit in memory.
The error you get is because you compare a QString for equality with a character literal - needless to say that is not going to work as expected. A string is a string even if there is only one character in it. As advised - use either the [] operator or better off for reading - QString::at() const which is guaranteed to create no extra copy. You don't use it on the QFile, nor on the QTextStream, but on the QString that is returned from the read() method of the text stream targeted at the file.
Once you have the text in memory, you can either use the regular QString methods like indexOf() to search for the index of a contained character.
in want to find the "$" sign so i will realize that I've reached the
number.
It sounds to me that you're searching for the '$' symbol because you're more interested in the dollar value that follows it. In this case, I suggest reading the files line by line and running them through a QRegExp to extract any values you're looking for.
QRegExp dollarFind("\\$(\\d+)");
while(!myfile_stream.atEnd()){
QString line = myfile_stream.readLine();
if (dollarFind.exactMatch(line)){
QStringList dollars = dollarFind.capturedTexts();
qDebug() << "Dollar values found: " << dollars.join(", ");
}
}

How to append this in Qt?

I want to add a new line in this. This is my sample code:
ui->button->setText(" Tips " + "\n" + TipsCount );
This is the error it shows:
invalid operands of types 'const char [7]' and 'const char [2]' to binary 'operator+'
But when I add to label it gets appended!
ui->label->setText(name + "\n" + City );
Can someone please help me?
This is a very common problem in C++ (in general, not just QT).
Thanks to the magic of operator overloading, name + "\n" gets turned into a method call (couldn't say which one since you don't list the type). In other words, because one of the two things is an object with + overloaded it works.
However when you try to do "abc" + "de", it blows up. The reason is because the compiler attempts to add two arrays together. It doesn't understand that you mean concatenation, and tries to treat it as an arithmetic operation.
To correct this, wrap your string literals in the appropriate string object type (std::string or QString most likely).
Here is a little case study:
QString h = "Hello"; // works
QString w = "World"; // works too, of course
QString a = h + "World"; // works
QString b = "Hello" + w; // also works
QString c = "Hello" + "World"; // does not work
String literals in C++ (text in quotes) are not objects and don't have methods...just like numeric values aren't objects. To make a string start acting "object-like" it has to get wrapped up into an object. QString is one of those wrapping objects, as is the std::string in C++.
Yet the behavior you see in a and b show we're somehow able to add a string literal to an object. That comes from the fact that Qt has defined global operator overloads for both the case where the left operand is a QString with the right a const char*:
http://doc.qt.nokia.com/latest/qstring.html#operator-2b-24
...as well as the other case where the left is a const char* and the right is a QString:
http://doc.qt.nokia.com/latest/qstring.html#operator-2b-27
If those did not exist then you would have had to write:
QString a = h + QString("World");
QString b = QString("Hello") + w;
You could still do that if you want. In that case what you'll cause to run will be the addition overload for both operands as QString:
http://doc.qt.nokia.com/latest/qstring.html#operator-2b-24
But if even that didn't exist, you'd have to call a member function. For instance, append():
http://doc.qt.nokia.com/latest/qstring.html#append
In fact, you might notice that there's no overload for appending an integer to a string. (There's one for a char, however.) So if your TipsCount is an integer, you'll have to find some way of turning it into a QString. The static number() methods are one way.
http://doc.qt.nokia.com/latest/qstring.html#number
So you might find you need:
ui->button->setText(QString(" Tips ") + "\n" + QString::number(TipsCount));

strcpy and strcat cause problems sometimes

hello I have a code like the one below
char *str ;
strcpy(str, "\t<");
strcat(str, time);
strcat(str, ">[");
strcat(str, user);
strcat(str, "]");
strcat(str, "(");
strcat(str, baseName);
strcat(str, ") $ ");
printf("\String is now: %s\n", str);
This code seems working but when I use XCode analyse function, it says "Function call argument is an uninitialized value" and also it sometimes causes my program crash.. when I remove it, then it works fine... Whats wrong with that? Thanks
strcpy and strcat are used to copy and concatenate strings to an allocated char array.
Since str in not initilized you're writing somewhere in memory and this is bad because you're corrupting other data. It may work at that moment but sooner or later you'll program will crash.
You should allocate memory when declaring str:
char str[100];
Also, strcat is not efficient as it needs to search for the string end to know where concatenate chars. Using sprintf would be more efficient:
sprintf(str, "\t<%s>[%s](%s) $ ", time, user, baseName);
Finally, if you can't guarantee the generated string will fit the array, you'd better use snsprintf.
You don't allocate memory and you leave str uninitialized. All later writes are done through an uninitialized pointer that points "somewhere" - that's undefined behavior.
You have to allocate (and later free) memory large enough to hold the resulting string:
char *str = malloc( computeResultSizeSomehow() );
if( str == 0 ) {
// malloc failed - handle as fatal error
}
//proceed with your code, then
free( str );
This is much simpler and error-free from buffer overflows:
#define BUFFERSIZE 512
char str[BUFFERSIZE];
snprintf(str, BUFFERSIZE, "\t<%s>[%s](%s) $ ", time, user, baseName);

Resources