하.. CAN 통신 초보 인사 드립니다. ^^

아직까지 어떻게 활용하는지 잘은 모르지만, 점점 실력이 쌓이고 있습니다. 

CAN 은 2선으로 마스터,슬레이브 없이?(STM32F446 은 Slave 도 있더군요) 지가 아무 때나 올리고 싶은 것 올리고,
들리면 듣고 ... 전체적인 느낌 상 위의 내용처럼 판단이 됩니다. 자유로운 영혼? 

그리고, 485 보다 작은 Package의 가격이 쌉니다.
485는 작고 3.3V 지원하는 IC는 터무니 없이 비쌉니다.
5V IC 는 싼데. 그리고 자유로운 영혼은 아니죠. ^^

[작은 패키지 가격 비교]




485 자료 : 링크 
CAN 자료 : 링크


CAN 2.0 은 최대 속도가 1Mbps 라고 하네요.
STM32Fxx 의 CUBEMX 설정 가능 값은 8Mbps 정도 나오던데, 테스트는 못해봤습니다.

아.. 집에서 돈 못벙어온다고, 홧김에 한잔 하고 쓰는거라.. 위에 헛소리가 많네요. ^^

자, 시작해 보죠. 
이번에는 STM32F446 에서 CAN 을 적용해 봤습니다.
앞으로 STM32f091 과 붙여서 마스터로 쓸 놈이죠.(현재 알바 프로젝트 중, 태양광 충전기에 들어가는 ic 들이랍니다)

일단은 ID_LIST 모드로 먼저 해 보겠습니다.

1. STM446 CAN 통신을 위해 연결할 배선입니다. STM32F091 과 완전히 똑같네요.




2. 이전에 연결해 놨던 STM32F091 들하고 같은 CAN라인에 붙였습니다.





3. 같지만 다른 그림이요.




위의 그림처럼 연결은 해 두고, 이제 CUBEMX 툴에서 CAN 통신 설정을 해 보겠습니다.
4. CUBEMX에서 핀 설정 그림입니다.






5. 인터럽트 설정 CUBEMX 그림입니다. 자세히 알아보고 싶은데, 시간이 없어서 넘깁니다.
4개의 인터럽트 중 1개만 선택. 통신들이 대부분, RX 에만 인터럽트를 설정하죠.
보내고 싶으면 내 마음이지만, 받을 때는 언제 받을 지 모르니 이런 거겠죠? ^^





이건, 갑자기 인터럽트가 너무 많이 나와서 빠른 진행을 위해, 최소한 필요한 인터럽트를 찾아보다 캡쳐한 내용입니다.





6. 유튜브 보고, 그대로 진행해서, 인터럽트 설정 넘어갑니다.




이렇게 설정을 하고, 프로그램에서 코딩을 해 줘야 합니다.
간단하게 STM32F446 을 기존 STM32F091 과 같은 ID 로 설정했습니다.
이번 글의 목적은 일단 STM32F446 이 CAN 동작을 하는지 와 3개의 CAN 연결을 확인하기 위해서 입니다.
바로 다음으로, ID_MASK 를 테스트 할 예정인데, 술먹고 진행하니.. 더 진행할 자신이 없네요. ^^

STM32F446 CAN 코딩은 STM32F091 과 완전히 똑같습니다. 다만 틀린것은 CAN Hamdller 이름이 hcan 에서 hcan1로 바뀌었을 뿐. !!!

STM32F091 과 마찮가지로 CUBEMX 가 CAN 필터까지 설정을 해주지 않기 때문에, 
다음과 같이 CAN Filter 를 설정해 줍니다. 위에서 말씀드린 것처럼 STM32F091 코드에서 hcan 을 hcan1로만 바꾸면 끝.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
static void CAN_Filter_Config(void)
{
  CAN_FilterConfTypeDef  sFilterConfig;
 
  hcan1.pTxMsg = &TxMessage;
  hcan1.pRxMsg = &RxMessage;
    
  /*##-2- Configure the CAN Filter ###########################################*/
  sFilterConfig.FilterNumber = 0;
  sFilterConfig.FilterMode = CAN_FILTERMODE_IDLIST;
  sFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT;
  sFilterConfig.FilterIdHigh = filter_bd_ID<<5;
  sFilterConfig.FilterIdLow = 0x0000;
  sFilterConfig.FilterMaskIdHigh = 0x0000;
  sFilterConfig.FilterMaskIdLow = 0x0000;
  sFilterConfig.FilterFIFOAssignment = 0;
  sFilterConfig.FilterActivation = ENABLE;
  sFilterConfig.BankNumber = 14;
 
  if (HAL_CAN_ConfigFilter(&hcan1, &sFilterConfig) != HAL_OK)
  {
    /* Filter configuration Error */
    Error_Handler();
  }
 
  /*##-3- Configure Transmission process #####################################*/
  hcan1.pTxMsg->StdId = my_bd_ID;
  //hcan.pTxMsg->ExtId = 0x01;
  hcan1.pTxMsg->RTR = CAN_RTR_DATA;
  hcan1.pTxMsg->IDE = CAN_ID_STD;
  hcan1.pTxMsg->DLC = 4;
}
cs


 그 다음은 동작 시나리오를 구상한 내용인데,
STM32F091 한개를, 그대로 (코드와 ID를 그대로, 단 hcan->hcan1)카피해서 똑같이 동작하도록 하겠습니다.
상대방이 나에게 주면 UART2로 표시하고, 내가 보내면 상대방이 표시합니다.
나와 같은 ID 인 2번째 STM091은 같은 동작을 하겠죠?
그리고 같은 아이디 이기 때문에 필터로 받는 ID 설정에서 같은 ID는 제외 되므로 같은 ID 끼리는 데이터를 송수신 못 하겠죠?

다음은 그 결과이고, 시나리오와 완벽히 일치합니다.





전체 main.c 소스 코드를 올립니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/**
  ******************************************************************************
  * File Name          : main.c
  * Description        : Main program body
  ******************************************************************************
  ** This notice applies to any and all portions of this file
  * that are not between comment pairs USER CODE BEGIN and
  * USER CODE END. Other portions of this file, whether 
  * inserted by the user or by software development tools
  * are owned by their respective copyright owners.
  *
  * COPYRIGHT(c) 2017 STMicroelectronics
  *
  * Redistribution and use in source and binary forms, with or without modification,
  * are permitted provided that the following conditions are met:
  *   1. Redistributions of source code must retain the above copyright notice,
  *      this list of conditions and the following disclaimer.
  *   2. Redistributions in binary form must reproduce the above copyright notice,
  *      this list of conditions and the following disclaimer in the documentation
  *      and/or other materials provided with the distribution.
  *   3. Neither the name of STMicroelectronics nor the names of its contributors
  *      may be used to endorse or promote products derived from this software
  *      without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  ******************************************************************************
  */
 
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f4xx_hal.h"
 
/* USER CODE BEGIN Includes */
 
/* USER CODE END Includes */
 
/* Private variables ---------------------------------------------------------*/
CAN_HandleTypeDef hcan1;
 
UART_HandleTypeDef huart2;
 
/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/
CanTxMsgTypeDef        TxMessage;
CanRxMsgTypeDef        RxMessage;
uint32_t my_bd_ID;
uint32_t filter_bd_ID;
 
/* USER CODE END PV */
 
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_CAN1_Init(void);
static void MX_USART2_UART_Init(void);
 
/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/
 
/* USER CODE END PFP */
 
/* USER CODE BEGIN 0 */
// for using printf() for Nucleo Board(UART2)
#ifdef __GNUC__
 #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
 #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif
 
PUTCHAR_PROTOTYPE
{
 HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 11);
 return ch;
}
 
 
void HAL_CAN_RxCpltCallback(CAN_HandleTypeDef *CanHandle)
{
    printf("Can RX INT");
 
  if ((CanHandle->pRxMsg->StdId == filter_bd_ID) && (CanHandle->pRxMsg->IDE == CAN_ID_STD) && (CanHandle->pRxMsg->DLC == 2))
  {
        printf("0[%02X],1[%02X]\r\n",CanHandle->pRxMsg->Data[0],CanHandle->pRxMsg->Data[1]);
  }
 
  /* Receive */
  if (HAL_CAN_Receive_IT(CanHandle, CAN_FIFO0) != HAL_OK)
  {
    /* Reception Error */
    Error_Handler();
  }
}
 
static void CAN_Filter_Config(void)
{
  CAN_FilterConfTypeDef  sFilterConfig;
 
  hcan1.pTxMsg = &TxMessage;
  hcan1.pRxMsg = &RxMessage;
    
  /*##-2- Configure the CAN Filter ###########################################*/
  sFilterConfig.FilterNumber = 0;
  sFilterConfig.FilterMode = CAN_FILTERMODE_IDLIST;
  sFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT;
  sFilterConfig.FilterIdHigh = filter_bd_ID<<5;
  sFilterConfig.FilterIdLow = 0x0000;
  sFilterConfig.FilterMaskIdHigh = 0x0000;
  sFilterConfig.FilterMaskIdLow = 0x0000;
  sFilterConfig.FilterFIFOAssignment = 0;
  sFilterConfig.FilterActivation = ENABLE;
  sFilterConfig.BankNumber = 14;
 
  if (HAL_CAN_ConfigFilter(&hcan1, &sFilterConfig) != HAL_OK)
  {
    /* Filter configuration Error */
    Error_Handler();
  }
 
  /*##-3- Configure Transmission process #####################################*/
  hcan1.pTxMsg->StdId = my_bd_ID;
  //hcan.pTxMsg->ExtId = 0x01;
  hcan1.pTxMsg->RTR = CAN_RTR_DATA;
  hcan1.pTxMsg->IDE = CAN_ID_STD;
  hcan1.pTxMsg->DLC = 4;
}
 
/* USER CODE END 0 */
 
int main(void)
{
 
  /* USER CODE BEGIN 1 */
 
  /* USER CODE END 1 */
 
  /* MCU Configuration----------------------------------------------------------*/
 
  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();
 
  /* USER CODE BEGIN Init */
 
  /* USER CODE END Init */
 
  /* Configure the system clock */
  SystemClock_Config();
 
  /* USER CODE BEGIN SysInit */
 
  /* USER CODE END SysInit */
 
  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_CAN1_Init();
  MX_USART2_UART_Init();
 
  /* USER CODE BEGIN 2 */
    my_bd_ID = 0x0321;            // Other board ID : 0x322
    filter_bd_ID = 0x0322;    // Other board Filter ID : 0x321
  CAN_Filter_Config();
    
    printf("my bd(STM32F446) id = %04X, bd id from = %04X\r\n",my_bd_ID,filter_bd_ID);
    
    uint16_t i=0;
    
    //HAL_CAN_Receive_IT();
    
  if (HAL_CAN_Receive_IT(&hcan1, CAN_FIFO0) != HAL_OK)
  {
    /* Reception Error */
    Error_Handler();
  }
 
  /* USER CODE END 2 */
 
  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
  /* USER CODE END WHILE */
 
  /* USER CODE BEGIN 3 */
        if (HAL_GPIO_ReadPin(SW_IN_GPIO_Port,SW_IN_Pin))
        {
        }
        else
        {
            
            hcan1.pTxMsg->DLC = 2;
            hcan1.pTxMsg->Data[0= (uint8_t)(i&0x00FF);
            hcan1.pTxMsg->Data[1= 0xAD;
            hcan1.pTxMsg->Data[2= 0x12;
            hcan1.pTxMsg->Data[3= 0x32;
            printf("transmited data %02X:%02X\r\n",hcan1.pTxMsg->Data[0],hcan1.pTxMsg->Data[1]);
            if (HAL_CAN_Transmit(&hcan1, 10!= HAL_OK)
            {
                //Transmission Error 
                Error_Handler();
            }
            i++;
            HAL_Delay(100);
        }
 
  }
  /* USER CODE END 3 */
 
}
 
/** System Clock Configuration
*/
void SystemClock_Config(void)
{
 
  RCC_OscInitTypeDef RCC_OscInitStruct;
  RCC_ClkInitTypeDef RCC_ClkInitStruct;
 
    /**Configure the main internal regulator output voltage 
    */
  __HAL_RCC_PWR_CLK_ENABLE();
 
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
 
    /**Initializes the CPU, AHB and APB busses clocks 
    */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 4;
  RCC_OscInitStruct.PLL.PLLN = 180;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 2;
  RCC_OscInitStruct.PLL.PLLR = 2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }
 
    /**Activate the Over-Drive mode 
    */
  if (HAL_PWREx_EnableOverDrive() != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }
 
    /**Initializes the CPU, AHB and APB busses clocks 
    */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
 
  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }
 
    /**Configure the Systick interrupt time 
    */
  HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
 
    /**Configure the Systick 
    */
  HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
 
  /* SysTick_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(SysTick_IRQn, 00);
}
 
/* CAN1 init function */
static void MX_CAN1_Init(void)
{
 
  hcan1.Instance = CAN1;
  hcan1.Init.Prescaler = 18;
  hcan1.Init.Mode = CAN_MODE_NORMAL;
  hcan1.Init.SJW = CAN_SJW_1TQ;
  hcan1.Init.BS1 = CAN_BS1_4TQ;
  hcan1.Init.BS2 = CAN_BS2_5TQ;
  hcan1.Init.TTCM = DISABLE;
  hcan1.Init.ABOM = DISABLE;
  hcan1.Init.AWUM = DISABLE;
  hcan1.Init.NART = DISABLE;
  hcan1.Init.RFLM = DISABLE;
  hcan1.Init.TXFP = DISABLE;
  if (HAL_CAN_Init(&hcan1) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }
 
}
 
/* USART2 init function */
static void MX_USART2_UART_Init(void)
{
 
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    _Error_Handler(__FILE__, __LINE__);
  }
 
}
 
/** Configure pins as 
        * Analog 
        * Input 
        * Output
        * EVENT_OUT
        * EXTI
*/
static void MX_GPIO_Init(void)
{
 
  GPIO_InitTypeDef GPIO_InitStruct;
 
  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
 
  /*Configure GPIO pin : SW_IN_Pin */
  GPIO_InitStruct.Pin = SW_IN_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(SW_IN_GPIO_Port, &GPIO_InitStruct);
 
}
 
/* USER CODE BEGIN 4 */
 
/* USER CODE END 4 */
 
/**
  * @brief  This function is executed in case of error occurrence.
  * @param  None
  * @retval None
  */
void _Error_Handler(char * file, int line)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  while(1
  {
  }
  /* USER CODE END Error_Handler_Debug */ 
}
 
#ifdef USE_FULL_ASSERT
 
/**
   * @brief Reports the name of the source file and the source line number
   * where the assert_param error has occurred.
   * @param file: pointer to the source file name
   * @param line: assert_param error line source number
   * @retval None
   */
void assert_failed(uint8_t* file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
    ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
 
}
 
#endif
 
/**
  * @}
  */ 
 
/**
  * @}
*/ 
 
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
 
cs

can_main_v100.zip


+ Recent posts