sunplus 发表于 2019-12-27 11:15:28

arduino 串口接收 发送 小例子

本帖最后由 sunplus 于 2019-12-27 11:32 编辑

#include "Arduino.h"


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

#define LEN 1024
uint8_t gWriteBuffer;
uint8_t gReadBuffer;
volatile static int iWpos = 0;
volatile static int iRpos = 0;

void loop()
{
        while (true)
        {
                int iLen =0;

                iLen = Serial.available();
                //写buffer
                if(iLen > 0 && iLen <= LEN)
                {               
                        if (iLen + iWpos < LEN)
                        {
                                Serial.readBytes(gWriteBuffer+iWpos,iLen);
                                iWpos += iLen;
                        }
                        else
                        {
                                Serial.readBytes(gWriteBuffer+iWpos,LEN - iWpos);
                                Serial.readBytes(gWriteBuffer,iLen -(LEN - iWpos));               
                                iWpos = iLen -(LEN - iWpos);                       
                        }
                }
                else if(iLen > LEN)
                {
                        Serial.flush();                       
                }

                int iReadTempPos = 0;
                iReadTempPos = iWpos;
                int iRlen = 0;
                //读buffer
                if (iReadTempPos != iRpos)
                {
                        memset(gReadBuffer,0,sizeof(gReadBuffer));
                        if (iReadTempPos > iRpos)
                        {
                                memcpy(gReadBuffer,gWriteBuffer+iRpos,iReadTempPos - iRpos);
                                iRlen = iReadTempPos - iRpos;                                               
                        }
                        else
                        {
                                memcpy(gReadBuffer ,gWriteBuffer+iRpos,LEN - iRpos);
                                memcpy(gReadBuffer+(LEN - iRpos) ,gWriteBuffer,iReadTempPos);
                                iRlen = (LEN - iRpos) + iReadTempPos;                                                       
                        }
                        iRpos = iReadTempPos;
                }

                Serial.printf("serial iWpos %d ,iRpos %d ,iRlen %d \r\n",iWpos,iRpos,iRlen);               
                Serial.write(gReadBuffer,iRlen);

        }
}

xuwuhan 发表于 2019-12-27 11:17:00

感谢分享。

t3486784401 发表于 2019-12-27 16:57:47

Serial 类已经集成了 FIFO 机制,自己再做一套..... 多用用 parseInt 吧

sunplus 发表于 2019-12-27 17:06:56

t3486784401 发表于 2019-12-27 16:57
Serial 类已经集成了 FIFO 机制,自己再做一套..... 多用用 parseInt 吧

谢啦,你说的对。再做接收,确实多此一举了。

t3486784401 发表于 2019-12-27 17:46:01

sunplus 发表于 2019-12-27 17:06
谢啦,你说的对。再做接收,确实多此一举了。

以前串口接收都自己写超时的,结果发现 Serial 直接有 setTimeout,简单拆包一把搞定。

不过复杂的工业项目就算了,宁可自己搭一遍底层。
页: [1]
查看完整版本: arduino 串口接收 发送 小例子