1 | ||||||
Две платы Нуклео по SPI. Дубль два15.12.2018, 16:17. Показов 1607. Ответов 7
Метки нет (Все метки)
Доброго времени суток всем ! Я скачал образцы от производителя ( библиотека STM32CubeL1 ) и попробовал запустить пример для SPI ( режимы Full Duplex и polling ) на двух моих платах Nucleo-L152re. Подсоединил все как сказано в файле readme. ( ножки MOSI, MISO, CLK и GND напрямую к таким же лапкам на второй плате ).
Так вот. Не заработало. Думаю, что изза того, что в SPI нет способов синхронизации начала передачи данных ( между запуском мастера и запуском слейва проходит некоторое время и в итоге приходит мусор ) Как можно это исправить ? Код выложу позднее... Добавлено через 19 минут Вот код производителя...
Вот его readme файл... @par Example Description This example shows how to ensure SPI data buffer transmission/reception in Polling mode between two boards. _________________________ _________________________ | ______________| |______________ | | |SPI3 | | SPI3| | | | | | | | | | CLK(PC10)|______________________|(PC10)CLK | | | | | | | | | | MISO(PC11)|______________________|(PC11)MISO | | | | | | | | | | MOSI(PC12)|______________________|(PC12)MOSI | | | | | | | | | |______________| |______________| | | __ | | | | |__| | | | | USER | | | | GND|______________________|GND | | | | | |_STM32L1 Master _________| |_STM32L1 Slave __________| HAL architecture allows user to easily change code to move to IT or DMA mode. To see others communication modes please check following examples: SPI\SPI_FullDuplex_ComDMA SPI\SPI_FullDuplex_ComIT At the beginning of the main program the HAL_Init() function is called to reset all the peripherals, initialize the Flash interface and the systick. Then the SystemClock_Config() function is used to configure the system clock (SYSCLK) to run at 32 MHz. The SPI peripheral configuration is ensured by the HAL_SPI_Init() function. This later is calling the HAL_SPI_MspInit()function which core is implementing the configuration of the needed SPI resources according to the used hardware (CLOCK & GPIO). You may update this function to change SPI configuration. The SPI communication is then initiated. The HAL_SPI_TransmitReceive() function allows the reception and the transmission of a predefined data buffer at the same time (Full Duplex Mode) The user can choose between Master and Slave through "#define MASTER_BOARD" in the "main.c" file. If the Master board is used, the "#define MASTER_BOARD" must be uncommented. If the Slave board is used the "#define MASTER_BOARD" must be commented. For this example the aTxBuffer is predefined and the aRxBuffer size is same as aTxBuffer. In a first step after the user press the User push-button, SPI Master starts the communication by sending aTxBuffer and receiving aRxBuffer through HAL_SPI_TransmitReceive(), at the same time SPI Slave transmits aTxBuffer and receives aRxBuffer through HAL_SPI_TransmitReceive(). The end of this step is monitored through the HAL_SPI_GetState() function result. Finally, aRxBuffer and aTxBuffer are compared through Buffercmp() in order to check buffers correctness. STM32 board's LEDs can be used to monitor the transfer status: - LED2 toggles quicly on master board waiting user button to be pressed. - LED2 turns ON if transmission/reception is complete and OK. - LED2 toggle slowly when there is a timeout or an error in transmission/reception process. @note SPIx instance used and associated resources can be updated in "main.h" file depending hardware configuration used. @note Timeout is set to 5 Seconds which means that if no communication occurs during 5 Seconds, a Timeout Error will be generated. @note You need to perform a reset on Slave board, then perform it on Master board to have the correct behaviour of this example. @note Care must be taken when using HAL_Delay(), this function provides accurate delay (in milliseconds) based on variable incremented in SysTick ISR. This implies that if HAL_Delay() is called from a peripheral ISR process, then the SysTick interrupt must have higher priority (numerically lower) than the peripheral interrupt. Otherwise the caller ISR process will be blocked. To change the SysTick interrupt priority you have to use HAL_NVIC_SetPriority() function. @note The application need to ensure that the SysTick time base is always set to 1 millisecond to have correct HAL operation. @par Directory contents - SPI/SPI_FullDuplex_ComPolling/Inc/stm32l1xx_hal_conf.h HAL configuration file - SPI/SPI_FullDuplex_ComPolling/Inc/stm32l1xx_it.h SPI interrupt handlers header file - SPI/SPI_FullDuplex_ComPolling/Inc/main.h Header for main.c module - SPI/SPI_FullDuplex_ComPolling/Src/stm32l1xx_it.c SPI interrupt handlers - SPI/SPI_FullDuplex_ComPolling/Src/main.c Main program - SPI/SPI_FullDuplex_ComPolling/Src/system_stm32l1xx.c STM32L1xx system source file - SPI/SPI_FullDuplex_ComPolling/Src/stm32l1xx_hal_msp.c HAL MSP file @par Hardware and Software environment - This example runs on STM32L1xx devices. - This example has been tested with STM32L152RE-Nucleo Rev C board and can be easily tailored to any other supported device and development board. - STM32L152RE-Nucleo Rev C Set-up: - Connect master CLK (PC10 connected to pin1 on CN7 connector) to Slave CLK (PC10 connected to pin1 on CN7 connector) - Connect master MISO (PC11 connected to pin2 on CN7 connector) to Slave MISO (PC11 connected to pin2 on CN7 connector) - Connect master MOSI (PC12 connected to pin3 on CN7 connector) to Slave MOSI (PC12 connected to pin3 on CN7 connector) - Connect Maset board GND to Slave Board GND @par How to use it ? In order to make the program work, you must do the following: - Open your preferred toolchain - Rebuild all files and load your image into target memory o Uncomment "#define MASTER_BOARD" and load the project in Master Board o Comment "#define MASTER_BOARD" and load the project in Slave Board - Run the example * <h3><center>© COPYRIGHT STMicroelectronics</center></h3> */
0
|
15.12.2018, 16:17 | |
Ответы с готовыми решениями:
7
SeggerIDE, линух и платы нуклео с STM32F746ZG Как послать пульс с платы Нуклео ? Погода. Тема дубль два QTableView + Double Click дубль два |
Модератор
8908 / 6677 / 918
Регистрация: 14.02.2011
Сообщений: 23,523
|
|
16.12.2018, 07:52 | 2 |
Сообщение было отмечено max_sk как решение
Решение
ну а где пятая ножка? CS(Chip Select), она та как раз и нужна для синхронизации
есть слейв не нужно запускать, он должен быть включен всегда "слушать" линию мастер выставил CS(установил 0) слейв это поймал и знает что сейчас пойдут данные Добавлено через 2 минуты max_sk, картинку поправь, ничего не понятно лучше если прикрепишь в графическом формате
1
|
21.12.2018, 22:20 [ТС] | 3 | ||||||||||
Есть продвижение !
Оказывается, вопреки теории, надо подсоединять пять ножек - MISO к MISO, MOSI к MOSI, NSS к NSS и CLK к CLK. Но кроме этого оказывается нужно подсоединить еще и GND к GND ! Тогда начинают отправляться и приниматься верные данные. Правда, временами мусор все таки проскальзывает. Буду думать почему... ValeryS, не могу поправить картинку. Удалите, пожалуйста, пост с картинкой, он несущественен. Добавлено через 44 минуты Все, сделал !!! Оказывается, мусор поступал потому, что пока я выводил результат через HAL_UART_Transmit(), в буффер прибывали еще данные. Выкладываю код. Вот код мастера :
0
|
23.12.2018, 21:53 [ТС] | 6 |
Добрый вечер всем ! Играюсь с проектом. Иногда данные идут чисто, иногда с помехами. Как мне кажется, есть вибрация проводов, изза чего данные искажаются. Как избежать этого ? С вибрацией кнопок я знаком, а как устранить помехи от вибрации проводов ?
0
|
01.03.2019, 18:09 [ТС] | 7 |
Пока идут детали по почте для проекта Говорящий будильник, хочу все таки попробовать добиться устойчивой передачи данных по SPI. Потому что в новом проекте тоже есть SPI. А то я тут перезапустил ётот проект, и у меня снова пошел мусор...
Я пользуюсь перемычками female-female. Может будут идеи как добиться устойчивой и верной передачи инфы ? Паять и перепаивать каждый раз платы не хотелось бы... Добавлено через 1 час 51 минуту Мне тут сказали, что перемычки тут ни при чем. И посоветовали поработать со скоростью передачи данных. Как вы думаете, может помочь ? Добавлено через 3 часа 11 минут После того, как выставил в Кубе прескалер от PCLK так, чтобы частота была наименьшей, т.е. /16, передача данных стала устойчивой. Осталась проблема запуска плат, т.е. если во время старта данные пошли искаженными, то они и будут передаваться так до самого конца. Что можно сделать с этим ? Добавлено через 12 минут Хммм… Функция HAL_SPI_TransmitReceive() начинает заполнять буффер еще до того, как Мастер послал пульс и начал передачу. Надо как то разобраться с этим...
0
|
02.03.2019, 11:43 [ТС] | 8 |
Таки решил эту проблему - связал лапку NSS слейва с лапкой PA6 мастера, через которую управляю запуском передачи данных. Теперь все работает отлично !!!
0
|
02.03.2019, 11:43 | |
02.03.2019, 11:43 | |
Помогаю со студенческими работами здесь
8
indexOf, пропись ручкой, дубль два Спойлер на сайте, дубль два (закрыть по умолчанию) Как из одной формы запустить Sub в другой форме? (Дубль два) Почему один SEO инструмент нашел две внутренние ссылки на один page (дубль) Два дисплея на ST7920 по SPI Два Nucleo board'a по SPI Искать еще темы с ответами Или воспользуйтесь поиском по форуму: |