STM32F303K8T6でCANに流れてくるデータを受信してFloatに変換する

Dependencies:   mbed

Committer:
sashida_h
Date:
Thu Jul 30 10:37:02 2020 +0000
Revision:
0:18f4b01f6caf
initial commit

Who changed what in which revision?

UserRevisionLine numberNew contents of line
sashida_h 0:18f4b01f6caf 1 /*
sashida_h 0:18f4b01f6caf 2 CAN通信slave側
sashida_h 0:18f4b01f6caf 3 2種類のIDから受信する.
sashida_h 0:18f4b01f6caf 4 rd - RXD
sashida_h 0:18f4b01f6caf 5 td - TXD
sashida_h 0:18f4b01f6caf 6 MCP2551まわりは以下参照(終端Rは410ohmを使った,そこにあったので)
sashida_h 0:18f4b01f6caf 7 https://raw.githubusercontent.com/rummanwaqar/teensy_can/master/schematic.png
sashida_h 0:18f4b01f6caf 8 */
sashida_h 0:18f4b01f6caf 9 #include "mbed.h"
sashida_h 0:18f4b01f6caf 10
sashida_h 0:18f4b01f6caf 11 Serial pc(PA_2, PA_3, 115200); //pin19,20 TX,RX
sashida_h 0:18f4b01f6caf 12 CAN can(PA_11, PA_12, 100000); //pin21,22 rd,td
sashida_h 0:18f4b01f6caf 13 DigitalOut myled(PB_1); //pin15
sashida_h 0:18f4b01f6caf 14
sashida_h 0:18f4b01f6caf 15
sashida_h 0:18f4b01f6caf 16
sashida_h 0:18f4b01f6caf 17 CANMessage msg;
sashida_h 0:18f4b01f6caf 18
sashida_h 0:18f4b01f6caf 19 union Float2Byte{
sashida_h 0:18f4b01f6caf 20 float _float;
sashida_h 0:18f4b01f6caf 21 char _byte[4];
sashida_h 0:18f4b01f6caf 22 };
sashida_h 0:18f4b01f6caf 23 typedef union Float2Byte Float2Byte;
sashida_h 0:18f4b01f6caf 24
sashida_h 0:18f4b01f6caf 25 void receive(){
sashida_h 0:18f4b01f6caf 26 Float2Byte getFloat;
sashida_h 0:18f4b01f6caf 27
sashida_h 0:18f4b01f6caf 28 if(can.read(msg)){
sashida_h 0:18f4b01f6caf 29 /*ID: 0x01*/
sashida_h 0:18f4b01f6caf 30 if(msg.id == 0x01){
sashida_h 0:18f4b01f6caf 31 //pc.printf("ID: 0x01\n\r");
sashida_h 0:18f4b01f6caf 32 for(int i=0;i<4;++i){
sashida_h 0:18f4b01f6caf 33 getFloat._byte[i] = msg.data[i];
sashida_h 0:18f4b01f6caf 34 //pc.printf("get_char: %d\n\r", getFloat._byte[i]);
sashida_h 0:18f4b01f6caf 35 }
sashida_h 0:18f4b01f6caf 36 pc.printf("%.2f\r\n", getFloat._float);
sashida_h 0:18f4b01f6caf 37 myled = !myled;
sashida_h 0:18f4b01f6caf 38 }
sashida_h 0:18f4b01f6caf 39 /*ID: 0x02*/
sashida_h 0:18f4b01f6caf 40 if(msg.id == 0x02){
sashida_h 0:18f4b01f6caf 41 //pc.printf("ID: 0x02\n\r");
sashida_h 0:18f4b01f6caf 42 for(int i=0;i<4;++i){
sashida_h 0:18f4b01f6caf 43 getFloat._byte[i] = msg.data[i];
sashida_h 0:18f4b01f6caf 44 //pc.printf("get_char: %d\n\r", getFloat._byte[i]);
sashida_h 0:18f4b01f6caf 45 }
sashida_h 0:18f4b01f6caf 46 pc.printf("avarage: %.0f\n\r", getFloat._float);
sashida_h 0:18f4b01f6caf 47 myled = !myled;
sashida_h 0:18f4b01f6caf 48 }
sashida_h 0:18f4b01f6caf 49 }
sashida_h 0:18f4b01f6caf 50
sashida_h 0:18f4b01f6caf 51 }
sashida_h 0:18f4b01f6caf 52
sashida_h 0:18f4b01f6caf 53 int main(){
sashida_h 0:18f4b01f6caf 54 pc.printf("Slave_Start.\n\r");
sashida_h 0:18f4b01f6caf 55 can.attach(receive, CAN::RxIrq);
sashida_h 0:18f4b01f6caf 56 while(1){
sashida_h 0:18f4b01f6caf 57 pc.printf("Slave loop()\n\r");
sashida_h 0:18f4b01f6caf 58 wait(0.2);
sashida_h 0:18f4b01f6caf 59 }
sashida_h 0:18f4b01f6caf 60 }