【问题标题】:SIM800L string concatenationSIM800L 字符串连接
【发布时间】:2017-02-10 11:25:10
【问题描述】:

我从一个网站获得此代码,我将其用作从连接到我的 Arduino Mega 的 SIM800L 发送 SMS 消息的指南。

#include <Sim800l.h>
#include <SoftwareSerial.h> 
Sim800l Sim800l;  //declare the library
char* text;
char* number;
bool error; 

void setup(){
    Sim800l.begin();
    text="Testing Sms";
    number="+542926556644";
    error=Sim800l.sendSms(number,text);
    // OR 
    //error=Sim800l.sendSms("+540111111111","the text go here");
}

void loop(){
    //do nothing
}

我在中间添加了一些代码,以便它可以通过串行连接在我的 Python GUI 中接收来自用户的字符串输入。

#include <Sim800l.h>
#include <SoftwareSerial.h> 
Sim800l Sim800l;  //declare the library
char* text;
char* number;
bool error;
String data;

void setup(){
    Serial.begin(9600);        
}

void loop(){      
  if (Serial.available() > 0)
  {
    data = Serial.readString();
    Serial.print(data);
    sendmess();
  }
}   
void sendmess()
{
  Sim800l.begin();
  text="Power Outage occured in area of account #: ";
  number="+639164384650";
  error=Sim800l.sendSms(number,text);
  // OR 
  //error=Sim800l.sendSms("+540111111111","the text go here");  
}

我正在尝试将serial.readString() 中的数据连接到text 的末尾。 +%s 等常规方法不起作用。

在 Arduino IDE 中出现此错误:

error: cannot convert ‘StringSumHelper’ to ‘char*’ in assignment

如果我是正确的,char* 是一个指向地址的指针。有没有将串口监视器中的字符串添加到文本中?

【问题讨论】:

  • Arduino 有一个 String 类,它拥有一个 concat() 方法,text 可以简单地声明为 String 以利用此功能比接受的答案中的代码少得多。如果 concatenation 不能满足您的需求,那么String 也有一个addition operator

标签: string arduino gsm


【解决方案1】:

您必须将 Arduino String 对象转换为标准 C 字符串。您可以使用String 类的c_str() 方法来完成此操作。它将返回一个char* 指针。

现在您可以将这两个字符串与 C 库中的 strncat 函数 string.h 以及 strncpy 连接起来。

#include <string.h>

char message[160];  // max size of an SMS
char* text = "Power Outage occured in area of account #: ";
String data;

/*
 *    populate <String data> with data from serial port
 */

/* Copy <text> to message buffer */
strncpy(message, text, strlen(text));

/* Calculating remaining space in the message buffer */
int num = sizeof(message) - strlen(message) - 1;

/* Concatenate the data from serial port */
strncat(message, data.c_str(), num);

/* ... */

error=Sim800l.sendSms(number, message);

请注意,如果缓冲区中没有足够的空间,它将简单地切断剩余的数据。

【讨论】:

  • 谢谢你,这对我帮助很大!
猜你喜欢
  • 2014-03-31
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多