获取指定字符数组arduino的前n个元素 [英] getting the first n elements of a specified char array arduino
问题描述
我的目标是从串行读取一些字符串,例如 234124!3455addg#5867 如果程序看到 !它应该开始将它添加到一个字符数组,如果它看到 # 它应该返回该字符数组的前 4 个元素,对于我的示例,返回值应该是 3455.我该如何解决?我使用 String 类做了这个,但我需要将它实现为 char 数组.我对arduino很陌生,所以请清楚谢谢.这是我的代码:
My aim is reading some string from serial for example 234124!3455addg#5867 if the program sees ! it should start to add it to a char array and if it sees # it should return the first 4 elements of that char array for my example the return should be 3455. How can I solve it? I made this using String class but I need to implement it to char array. I am quite new on arduino so please be clear thank you. Here is my code:
const char *s = "123123123!0037selam#aaaaSDSDa";
const char *CHAR1 = "!";
const char *CHAR2 = "#";
char *target = NULL;
char *start, *end;
void setup() {
Serial.begin(9600);
}
void loop() {
if ( start = strstr( s, CHAR1 ) )
{
start += strlen( CHAR1 );
if ( end = strstr( start, CHAR2 ) )
{
target = ( char * )malloc( end - start + 1 );
memcpy( target, start, end - start );
target[end - start] = '\0';
}
}
if ( target )
{
for(int i=0; i<4;i++)
Serial.print( target[i]);
}
free( target );
return 0;
}
推荐答案
我认为这是一种更简单的方法.这取决于是否有未明确说明的要求.
Here's a simpler way of going about it, I think. It depends on whether or not there are requirements that aren't explicitly stated.
一些值得一提的事情,
- 您想返回跟在 '!' 之后的前 4 个字节,所以您只需要缓冲 4 个字符
- 我暂时没有准备好所有的电缆,所以我只是撞在一起的东西可以在 PC 上运行.在你的情况下,而不是返回您刚刚输出的字符串缓冲区的副本Serial.print
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
class dummy
{
public:
dummy()
{
const char *testData = "234124!3455addg#5867";
int dataLen = strlen(testData);
mData = new char[dataLen+1];
strcpy(mData, testData);
mTotal = strlen(testData);
mIndex = 0;
}
int available()
{
return mTotal - mIndex;
}
char read()
{
return mData[mIndex++];
}
private:
char *mData;
int mIndex;
int mTotal;
};
char *testFunc()
{
dummy *Serial = new dummy();
/// -------- 8< ------------ cut here until the next pair of scissors. put inside the loop function
/// your code does all of the functionality (reading and buffering) inside a single iteration of loop().
/// Normally, I'd expect a single character to be read each time. I'd expect loop() to be
/// run 16 times before a result was output, since # is the 16th character of the string.
char tmpBuffer[5] = {0};
int bufferIndex = 0;
bool marker1Seen = false;
while (Serial->available() > 0)
{
char received = Serial->read();
if (received == '!')
{
marker1Seen = true;
}
else if (received == '#')
{
return strdup(tmpBuffer);
}
else if (marker1Seen == true && bufferIndex < 4)
{
tmpBuffer[bufferIndex++] = received;
}
}
// shouldn't get here if the input is well-formed
return NULL;
/// -------- 8< ------------ cut here
}
int main()
{
char *result = testFunc();
cout << result;
delete result;
}
这篇关于获取指定字符数组arduino的前n个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!