Takeuchi Issei
/
Serial_Writer-re
Serial_Writerの受信側
Serial_Writer.h@2:9e785d92712d, 2021-05-07 (annotated)
- Committer:
- e2011220
- Date:
- Fri May 07 09:27:44 2021 +0000
- Revision:
- 2:9e785d92712d
- Parent:
- 1:ace5fce2d493
- Child:
- 6:657302a3a908
fc
Who changed what in which revision?
User | Revision | Line number | New contents of line |
---|---|---|---|
e2011220 | 0:7babc610f171 | 1 | #ifndef SERIAL_WRITER |
e2011220 | 0:7babc610f171 | 2 | #define SERIAL_WRITER |
e2011220 | 0:7babc610f171 | 3 | #include <mbed.h> |
e2011220 | 0:7babc610f171 | 4 | class Serial_Writer |
e2011220 | 0:7babc610f171 | 5 | { |
e2011220 | 0:7babc610f171 | 6 | public: |
e2011220 | 0:7babc610f171 | 7 | Serial_Writer(PinName TxPin,PinName RxPin,int baudrate); |
e2011220 | 0:7babc610f171 | 8 | template <typename T> |
e2011220 | 0:7babc610f171 | 9 | inline void write(T &send,int delay){ |
e2011220 | 0:7babc610f171 | 10 | int num=sizeof(send); |
e2011220 | 0:7babc610f171 | 11 | char buffer[num+2]; |
e2011220 | 0:7babc610f171 | 12 | for (int i=1,k=0;i<=num;k++){ |
e2011220 | 0:7babc610f171 | 13 | for(int _bitNum=sizeof(send[0])-1;_bitNum>=0;i++,_bitNum--)buffer[i]=(send[k]>>(8*_bitNum))&0xFF; |
e2011220 | 0:7babc610f171 | 14 | } |
e2011220 | 0:7babc610f171 | 15 | buffer[0]='['; |
e2011220 | 0:7babc610f171 | 16 | buffer[num+1]=']'; |
e2011220 | 0:7babc610f171 | 17 | for (int p=0;p<sizeof(buffer);p++)_Serial.putc(buffer[p]); |
e2011220 | 0:7babc610f171 | 18 | wait_ms(delay); |
e2011220 | 0:7babc610f171 | 19 | } |
e2011220 | 0:7babc610f171 | 20 | |
e2011220 | 0:7babc610f171 | 21 | template <typename R> |
e2011220 | 0:7babc610f171 | 22 | inline int receive(R &get){ |
e2011220 | 0:7babc610f171 | 23 | int num=sizeof(get); |
e2011220 | 0:7babc610f171 | 24 | int num_0=sizeof(get[0]); |
e2011220 | 0:7babc610f171 | 25 | char buffer[num+2]; |
e2011220 | 0:7babc610f171 | 26 | if (_Serial.readable()){ |
e2011220 | 0:7babc610f171 | 27 | for(int i=0;i<sizeof(buffer);i++){ |
e2011220 | 0:7babc610f171 | 28 | buffer[i]=_Serial.getc(); |
e2011220 | 0:7babc610f171 | 29 | if(buffer[0]!='[')return -1; |
e2011220 | 0:7babc610f171 | 30 | } |
e2011220 | 0:7babc610f171 | 31 | if(buffer[num+1]==']'){ |
e2011220 | 0:7babc610f171 | 32 | for (int s=0;s<(num/num_0);s++)get[s]=0x0; |
e2011220 | 0:7babc610f171 | 33 | for (int p=1,k=0;p<=num;k++){ |
e2011220 | 0:7babc610f171 | 34 | for (int _byte=num_0-1;_byte>=0;p++,_byte--)get[k]|=buffer[p]<<(8*_byte); |
e2011220 | 0:7babc610f171 | 35 | } |
e2011220 | 0:7babc610f171 | 36 | return 0;//正常終了 |
e2011220 | 2:9e785d92712d | 37 | }else return -1;//異常終了1(正しく受信できていない) |
e2011220 | 2:9e785d92712d | 38 | }else return -2;//異常終了2(受信するものがない) |
e2011220 | 0:7babc610f171 | 39 | } |
e2011220 | 0:7babc610f171 | 40 | |
e2011220 | 0:7babc610f171 | 41 | private: |
e2011220 | 0:7babc610f171 | 42 | Serial _Serial; |
e2011220 | 0:7babc610f171 | 43 | }; |
e2011220 | 0:7babc610f171 | 44 | |
e2011220 | 0:7babc610f171 | 45 | #endif |