STM32F103 SPI different pins does not work - spi

I am currently working on a project with LoRaWAN technology using STM32F103C8T6 microcontroller. For LoRa I am using SPI in Full-Duplex Master mode (spi1 specifically) and in CubeIDE when you activate SPI1, automatically pins PA5, PA6 and PA7 are activated (ver1):
However, PCB is designed and printed and those pins are unfortunately busy. Because, before it was planned to use other SPI1 pins (PB3, PB4, PB5) (ver2):
So, when I use ver1, all is good, LoRa connects to server and sends data without a problem. However, when I use ver2, it does not work at all. I debugged to find where is problem and found out that, SPI read fails (when version of LoRa is read, it returns 0). Thus, ASSERT fires and code is stuck in infinite loop. I could not find any reference of difference of SPI pins in the internet.
Can anyone explain the difference of these pins? And is it possible to use ver2? Thanks beforehand.
P.S. I am using HAL Library + LMIC library (for LoRa) and the configuration of SPI are the same for both ver1 and ver2. Here is code of configuration, if needed:
void MX_SPI1_Init(void)
{
hspi1.Instance = SPI1;
hspi1.Init.Mode = SPI_MODE_MASTER;
hspi1.Init.Direction = SPI_DIRECTION_2LINES;
hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi1.Init.NSS = SPI_NSS_SOFT;
hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64;
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi1.Init.CRCPolynomial = 10;
if (HAL_SPI_Init(&hspi1) != HAL_OK)
{
Error_Handler();
}
}
P.S.S: I also gave this question in electronics stackexchange, but there was no answer there, so I decided to share the question here too.

After lots of tries, I found out that, remapped SPI1 does not work together with I2C1, because of I2C1-SMBA pin overlap with SP1 MOSI pin (PB5), even if you are not using SMBA. You can find about that here: STM32F103x8 errata chapter 2.8.7
So, I guess, I will use I2C2 for avoiding collision. The only change I should make on PCB would be redirecting I2C1 pins to I2C2 (2 pins), which is way better than redirecting SPI1 pins (3 pins) and other elements occupying ver1 (also 3) pins.

Related

Movesense CustomGATT and ECG or Accelerometer

There have been a few posts on this issue without any solutions announced.
Wanting to access internal movesense sensor data (ECG, Acc…) but without using the Android or iOS platforms ( as suggested by a movesense presentation https://www.movesense.com/wp-content/uploads/2018/11/2018-11-06-Using-Movesense-CustomGATTService.pdf ), I have failed to do so for at least 1 week.
I can successfully create my own GATT characteristics and subscribe to them from outside the movesense device. This is easily done by augmenting the samples/custom_gattsvc_app with a few lines :
Definition :
const uint16_t myCharUUID16 = 0x2A58; // this new characteristic will appear in the service as the third one in the sample
In CustomGATTSvcClient::configGattSvc() :
WB_RES::GattProperty myCharProp = WB_RES::GattProperty::INDICATE;
myChar.props = wb::MakeArray<WB_RES::GattProperty>( &myCharProp, 1);
myChar.uuid = wb::MakeArray<uint8_t>( reinterpret_cast<const uint8_t*>(&myCharUUID16), 2);
customGattSvc.chars = wb::MakeArray<WB_RES::GattChar>(characteristics, 3); // 3 here since there are 3 characteristics now
Accessing
You can now see and subscribe with a BTLE client (bluetility…) to the new service even if it does not do anything for now.
The problems start here for me :
In CustomGATTSvcClient::onGetResult() I try to force a subscription to ECG or Acc since onGetResult() is called by CustomGATTSvcClient::onPostResult() once all the BT services are created :
int32_t sampleRate = 10;
asyncSubscribe(WB_RES::LOCAL::MEAS_ACC_SAMPLERATE(),AsyncRequestOptions::Empty, sampleRate);
I do not implement onSubscribeResult()
In onNotify() you should be able to intercept the call from the whiteboard with the new data every 1/10 second by
switch (resourceId.getConstId()) {
case WB_RES::LOCAL::MEAS_ACC_SAMPLERATE::ID:
{
// To see a blinking LED on each new Acc data
asyncPut(WB_RES::LOCAL::COMPONENT_LED(),AsyncRequestOptions::Empty, myFlippingBool);
myFlippingBool = ! myFlippingBool;
}
What I have observed :
A. When I asyncSubscribe() the ECG or Acc, the sample’s WB_RES::LOCAL::MEAS_TEMP::LID is no longer called and no updates are dispatched to a BT client even after a successful subscription to the 0x2A1C characteristic. This means that all Notifications are disabled by a resource conflict ?
B. When subscribing ( as before ) or even by :
wb::Result result = getResource("Meas/Acc/10", mMyAccResourceId);
result = asyncSubscribe(mMyAccResourceId);
The onNotify() method is never called as the LED does not blink ( even directly after onNotify() implementation without the switch / case )
There is a lack of documentation on CustomGatt and it seems it blocks many people in integrating the sensor on other platforms ( Raspberry Pi or generic processors running a BT stack ).
I have tried before to access the movesense platform with direct AT commands from a rudimentary microcontroller and a BT module without success (Movesense direct access to GATT endpoints ), so now I’m turning to a Raspberry solution + Qt without success.
Thank you for any example or answers to this question !
At least 10 Hz is not supported. What happens with Meas\Acc\13 ?

Openthread CLI UDP communication from main.c (NRF52840)

We are working with NRF52840 dongles and want to be able to have them relay data over an OpenThread mesh network through UDP automatically. We have found within the OpenThread API a solid Udp.h library with all the Udp functions we need to create code that runs on the dongles from the main.c.
Below is our code that should broadcast the message: "Hallo" to all nodes that have an open socket on port 1994.
We have read that the ipv6 address ff03::1 is reserved for multicast UDP broadcasting and it works perfectly when manually performed with the CLI udp commands.
CLI: Udp open, udp send ff03::1 1994 Hallo
With all the nodes that have udp open, udp bind :: 1994, receiving the Hallo message from the sending node.
We are trying to recreate this in the main.c of our nodes so that we can provide the nodes with some intelligence of their own.
This piece of code is run once when the push button on the dongle is pressed.
The code compiles perfectly and we have tested the functions that have a return with the RGB led (green OK, red not) to confirm that there weren't any errors produced (sadly not all functions return a no_error value)
void udpSend(){
const char *buf = "Hallo";
otMessageInfo messageInfo;
otInstance *myInstance;
myInstance = thread_ot_instance_get();
otUdpSocket mySocket;
memset(&messageInfo, 0, sizeof(messageInfo));
// messageInfo.mPeerAddr = otIp6GetUnicastAddresses(myInstance)->mNext->mNext->mAddress;
otIp6AddressFromString("ff03::1", &messageInfo.mPeerAddr);
messageInfo.mPeerPort = 1994;
messageInfo.mInterfaceId = OT_NETIF_INTERFACE_ID_THREAD;
otUdpOpen(myInstance, &mySocket, NULL, NULL);
otMessage *test_Message = otUdpNewMessage(myInstance, NULL);
otMessageSetLength(test_Message, sizeof(buf));
if (otMessageAppend(test_Message, &buf, sizeof(buf)) == OT_ERROR_NONE){
nrf_gpio_pin_write(LED2_G, 0);
}
else{
nrf_gpio_pin_write(LED2_R, 0);
}
otUdpSend(&mySocket, test_Message, &messageInfo);
otCliUartOutputFormat("Done.\0");
otUdpClose(&mySocket);
}
Now, we aren't exactly experts, so we are not sure why this isn't working as we had a lot of trouble figuring out how everything is called/initialised.
We hope to create a way to send and receive data through UDP through the code, so that they can operate autonomously.
We would really appreciate it if someone could assist us with our project!
Thanks!
Jonathan
There are a few errors in your code:
Remove the call to otMessageSetLength(). The message length is automatically increased as part of otMessageAppend().
The call to otMessageAppend() should be: otMessageAppend(test_message, buf, (uint16_t)strlen(buf)).
Removed the & before buf.
Replaced sizeof() with strlen().
Couple other things you should consider:
After calling otUdpNewMessage(), if any following call returns an error, make sure to call otMessageFree() on the message buffer.
Custody is only given to OpenThread after a successful call to otUdpSend().
Do not call udpSend() from interrupt context.
OpenThread library was designed to assume a single thread of execution.
Hope that helps.

atmel sensor using printf

I have an atmel UC3-L0 and compass sensor. Now I install AtmelStudio and download some demo code into the board. But I have no idea where the function printf in demo code will appear the data. How should I do to get the data?
The printf function outputs to stdout.
Usually on a "naked" processor with no operating system you need to define how a character is sent or received from a physical interface (usually an USART, console port, USB port, 4-port LCD interface, etc.). So typically you may want to use the USART port of your processor board to connect to a PC running Hyperterm, PuTTY or similar using a serial cable.
In essence you will need to
create FILE streams using the fdev_setup_stream() macro and
provide pointers to functions get() and put() that tell the printf() function how exactly to read and write from/to that stream (e.g. read/write to a USART, an LCD display, etc.).
you may have libraries - depending on your hardware - that already contain such functions (plus the correct port initialisation functions), like e.g. uart.c/.h, lcd.c/.h, etc.
In the documentation of stdio.h (e.g. here) look for the following:
printf(), fdev_setup_stream()
If you have downloaded Atmel Studio you may look into the stdiodemo.c code for further insight.
In order to use printf in ATMEL studio you should check the following things:
Add and Apply the Standard serial I/O module from Project->ASF Wizard.
Also add the USART module from the ASF Wizard.
Include the following code snippet before the main function.
static struct usart_module usart_instance;
static void configure_console(void)
{
struct usart_config usart_conf;
usart_get_config_defaults(&usart_conf);
usart_conf.mux_setting = EDBG_CDC_SERCOM_MUX_SETTING;
usart_conf.pinmux_pad0 = EDBG_CDC_SERCOM_PINMUX_PAD0;
usart_conf.pinmux_pad1 = EDBG_CDC_SERCOM_PINMUX_PAD1;
usart_conf.pinmux_pad2 = EDBG_CDC_SERCOM_PINMUX_PAD2;
usart_conf.pinmux_pad3 = EDBG_CDC_SERCOM_PINMUX_PAD3;
usart_conf.baudrate = 115200;
stdio_serial_init(&usart_instance, EDBG_CDC_MODULE, &usart_conf);
usart_enable(&usart_instance);
}
Make Sure you call the configure_console after system_init() from the main function.
Now go to tools->extension manager. Add the terminal window extension.
Build and Run your program and open the terminal window from view-> terminal window. put the correct com port to which your device is running on and set the baud to 115200 and hit connect on the terminal window.
You should see the printf statements now. (Float doesn't get printed in Atmel studio)
I was recently puzzling over this myself. I has installed Atmel Studio 7.0 and was using the SAMD21 Dev Board via an example project in which a call to printf was made.
In the sample code I saw that there was a configuration section:
/*!
* \brief Initialize USART to communicate with on board EDBG - SERCOM
* with the following settings.
* - 8-bit asynchronous USART
* - No parity
* - One stop bit
* - 115200 baud
*/
static void configure_usart(void)
{
struct usart_config config_usart;
// Get the default USART configuration
usart_get_config_defaults(&config_usart);
// Configure the baudrate
config_usart.baudrate = 115200;
// Configure the pin multiplexing for USART
config_usart.mux_setting = EDBG_CDC_SERCOM_MUX_SETTING;
config_usart.pinmux_pad0 = EDBG_CDC_SERCOM_PINMUX_PAD0;
config_usart.pinmux_pad1 = EDBG_CDC_SERCOM_PINMUX_PAD1;
config_usart.pinmux_pad2 = EDBG_CDC_SERCOM_PINMUX_PAD2;
config_usart.pinmux_pad3 = EDBG_CDC_SERCOM_PINMUX_PAD3;
// route the printf output to the USART
stdio_serial_init(&usart_instance, EDBG_CDC_MODULE, &config_usart);
// enable USART
usart_enable(&usart_instance);
}
In windows device manager I saw that there was an "Atmel Corp. EDBG USB Port (COM3)" listed under "Ports". However, the one of the "Properties" of this port was listed as 9600 Bits per second. I changed this from 9600 to 115200 to be consistent with the config section above.
Finally, I ran PuTTY.exe and set the Connection-->Serial setting to COM3 and 115200 baud. Then I went to Session, then clicked the Serial Connection Type, then clicked the Open button. And, BAM, there's my printf output via PuTTY.

Detecting open PC COM port from USB Virtual Com Port device

I am using an STM32F105 microcontroller with the STM32_USB-FS-Device_Lib_V3.2.1 USB library and have adapted the VCP example for our purposes (integration with RTOS and serial API).
The problem is that if the USB cable is attached, but the port is not open on the Windows host, after a few minutes the device ends up permanently re-entering the USB ISR until the port is opened and then it all starts working normally.
I have instrumented interrupt handler and can see that when the fault occurs, the ISR handler exits and then immediately re-enters. This occurs because on exit from the interrupt the IEPINT flag in OTG_FS_GINTSTS is not clear. The OTG_FS_DAINT at this time contains 0x00000002 (IEPINT1 set), while DIEPINT1 has 0x00000080 (TXFE). The line in OTGD_FS_Handle_InEP_ISR() that clears TXFE is called, but the bit either does not clear or becomes immediately reasserted. When the COM port on the host is reopened, the state of OTG_FS_GINTSTS and OTG_FS_DAINT at the end of the interrupt is always zero, and further interrupts occur at the normal rate. Note that the problem only occurs if data is being output but the host has no port open. If either the port is open or no data is output, the system runs indefinitely. I believe that the more data that is output the sooner the problem occurs, but that is anecdotal at present.
The VCP code has a state variable that takes the following enumerated values:
UNCONNECTED,
ATTACHED,
POWERED,
SUSPENDED,
ADDRESSED,
CONFIGURED
and we use the CONFIGURED state to determine whether to put data into the driver buffer for sending. However the CONFIGURED state is set when the cable is attached not when the host has the port open and an application connected. I see that when Windows does open the port, there is a burst of interrupts so it seems that some communication occurs on this event; I wonder if it is possible therefore to detect whether the host has the port open,.
I need one of two things perhaps:
To prevent the USB code from getting stuck in the ISR in the first instance
To determine whether the host has the port open from the device end, and only push data for sending when open.
Part (1) - preventing the interrupt lock-up - was facilitated by a USB library bug fix from ST support; it was not correctly clearing the TxEmpty interrupt.
After some research and assistance from ST Support, I have determined a solution to part (2) - detecting whether the host port is open. Conventionally, when a port is opened the DTR modem control line is asserted. This information is passed to a CDC class device, so I can use this to achieve my aim. It is possible for an application to change the behaviour of DTR, but this should not happen in any of the client applications that are likely to connect to this device in this case. However there is a back-up plan that implicitly assumes the port to be open if the line-coding (baud, framing) are set. In this case there is no means of detecting closure but at least it will not prevent an unconventional application from working with my device, even if it then causes it to crash when it disconnects.
Regarding ST's VCP example code specifically I have made the following changes to usb_prop.c:
1) Added the following function:
#include <stdbool.h>
static bool host_port_open = false ;
bool Virtual_Com_Port_IsHostPortOpen()
{
return bDeviceState == CONFIGURED && host_port_open ;
}
2) Modified Virtual_Com_Port_NoData_Setup() handling of SET_CONTROL_LINE_STATE thus:
else if (RequestNo == SET_CONTROL_LINE_STATE)
{
// Test DTR state to determine if host port is open
host_port_open = (pInformation->USBwValues.bw.bb0 & 0x01) != 0 ;
return USB_SUCCESS;
}
3) To allow use with applications that do not operate DTR conventionally I have also modified Virtual_Com_Port_Data_Setup() handling of SET_LINE_CODING thus:
else if (RequestNo == SET_LINE_CODING)
{
if (Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT))
{
CopyRoutine = Virtual_Com_Port_SetLineCoding;
// If line coding is set the port is implicitly open
// regardless of host's DTR control. Note: if this is
// the only indicator of port open, there will be no indication
// of closure, but this will at least allow applications that
// do not assert DTR to connect.
host_port_open = true ;
}
Request = SET_LINE_CODING;
}
I found another solution by adopting CDC_Transmit_FS.
It can now be used as output for printf by overwriting _write function.
First it checks the connection state, then it tries to send over USB endport in a busy loop, which repeats sending if USB is busy.
I found out if dev_state is not USBD_STATE_CONFIGURED the USB plug is disconnected. If the plug is connected but no VCP port is open via PuTTY or termite, the second check fails.
This implementation works fine for me for RTOS and CubeMX HAL application. The busy loop is not blocking low priority threads anymore.
uint8_t CDC_Transmit_FS(uint8_t* Buf, uint16_t Len)
{
uint8_t result = USBD_OK;
// Check if USB interface is online and VCP connection is open.
// prior to send:
if ((hUsbDevice_0->dev_state != USBD_STATE_CONFIGURED)
|| (hUsbDevice_0->ep0_state == USBD_EP0_STATUS_IN))
{
// The physical connection fails.
// Or: The phycical connection is open, but no VCP link up.
result = USBD_FAIL;
}
else
{
USBD_CDC_SetTxBuffer(hUsbDevice_0, Buf, Len);
// Busy wait if USB is busy or exit on success or disconnection happens
while(1)
{
//Check if USB went offline while retrying
if ((hUsbDevice_0->dev_state != USBD_STATE_CONFIGURED)
|| (hUsbDevice_0->ep0_state == USBD_EP0_STATUS_IN))
{
result = USBD_FAIL;
break;
}
// Try send
result = USBD_CDC_TransmitPacket(hUsbDevice_0);
if(result == USBD_OK)
{
break;
}
else if(result == USBD_BUSY)
{
// Retry until USB device free.
}
else
{
// Any other failure
result = USBD_FAIL;
break;
}
}
}
return result;
}
CDC_Transmit_FS is used by _write:
// This function is used by printf and puts.
int _write(int file, char *ptr, int len)
{
(void) file; // Ignore file descriptor
uint8_t result;
result = CDC_Transmit_FS((uint8_t*)ptr, len);
if(result == USBD_OK)
{
return (int)len;
}
else
{
return EOF;
}
}
Regards
Bernhard
After so much searching and a kind of reverse engineering I finally found the method for detecting the open terminal and also it's termination. I found that in the CDC class there is three Data nodes , one is a control node and the other two are data In and data Out nodes.Now when you open a terminal a code is sent to the control node and also when you close it. all we need to do is to get those codes and by them start and stop our data transmission tasks. the code that is sent is respectively 0x21 and 0x22 for opening and closing the terminal.In the usb_cdc_if.c there is a function that receive and interpret those codes (there is a switch case and the variable cmd is the code we are talking about).that function is CDC_Control_FS . Here we are, Now all we need to do is to expand that function so that it interpret the 0x22 and 0x21 . there you are , now you know in your application whether the port is open or not.
I need one of two things perhaps:
To prevent the USB code from getting stuck in the ISR in the first instance
To determine whether the host has the port open from the device end, and only push data for sending when open.
You should attempt to do option 1 instead of 2. On Windows and Linux, it is possible to open a COM port and use it without setting the control signals, which means there is no fool-proof, cross-platform way to detect that the COM port is open.
A well programmed device will not let itself stop functioning just because the USB host stopped polling for data; this is a normal thing that should be handled properly. For example, you might change your code so that you only queue up data to be sent to the USB host if there is buffer space available for the endpoint. If there is no free buffer space, you might have some special error handling code.
I have the same requirement to detect PC port open/close. I have seen it implemented it as follows:
Open detected by:
DTR asserted
CDC bulk transfer
Close detected by:
DTR deasserted
USB "unplugged", sleep etc
This seems to be working reasonably well, although more thorough testing will be needed to confirm it works robustly.
Disclaimer: I use code generated by Cube, and as a result it works with HAL drivers. Solutions, proposed here before, don't work for me, so I have found one. It is not good, but works for some purposes.
One of indirect sign of not opened port arises when you try to transmit packet by CDC_Transmit_FS, and then wait till TxState is set to 0. If port is not opened it never happens. So my solution is to fix some timeout:
uint16_t count = 0;
USBD_CDC_HandleTypeDef *hcdc =
(USBD_CDC_HandleTypeDef*) USBD_Device.pClassData;
while (hcdc->TxState != 0) {
if (++count > BUSY_TIMEOUT) { //number of cycles to wait till it makes decision
//here it's clear that port is not opened
}
}
The problem is also, that if one tries to open port, after device has tried to send a packet, it cant be done. Therefore whole routine I use:
uint8_t waitForTransferCompletion(void) {
uint16_t count = 0;
USBD_CDC_HandleTypeDef *hcdc =
(USBD_CDC_HandleTypeDef*) USBD_Device.pClassData;
while (hcdc->TxState != 0) {
if (++count > BUSY_TIMEOUT) { //number of cycles to wait till it makes decision
USBD_Stop(&USBD_Device); // stop and
MX_USB_DEVICE_Init(); // init device again
HAL_Delay(RESET_DELAY); // give a chance to open port
return USBD_FAIL; // return fail, to send last packet again
}
}
return USBD_OK;
}
The question is, how big timeout has to be, not to interrupt transmission while port is opened. I set BUSY_TIMEOUT to 3000, and now it works.
I fixed it by checking of a variable hUsbDeviceFS.ep0_state.
It equal 5 if connected and 4 if do not connected or was disconnected.
But. There are some issue in the HAL. It equal 5 when program started.
Next steps fixed it at the begin of a program
/* USER CODE BEGIN 2 */
HAL_Delay(500);
hUsbDeviceFS.ep0_state = 4;
...
I do not have any wishes to learn the HAL - I hope this post will be seeing by developers and they will fix the HAL.
It helped me to fix my issue.

Using Port DD as GPIO on MCF5282

I’ve got a MCF5282 that I’m trying to use PDD4 as a GPIO on. In my setup code, I’ve got:
MCF5282_GPIO_DDRDD = 0x10; /* cs on dd4. */
MCF5282_GPIO_PORTDD = 0x10; /* active-low. */
And in my main loop, I’ve got:
MCF5282_GPIO_PORTDD = (mainloop_cnt & 0x10);
Which should give me a nice square wave on the oscilloscope, but the port doesn’t seem to be doing as I say. Am I missing some setup steps? I can’t find anything in the 5282 manual about a “Port DD pin-assignment register” to repurpose it from its “primary” role as DDATA.
Edit 2011-03-01: We never figured this out, we just used a different pin for GPIO.
You probably need to clear PSTEN in the Chip Configuration Register to disable DDATA, see page 27-4 of the MCF5282 and MCF5216 ColdFire Microcontroller User’s Manual