HardFaultHandler in STM32 - bluetooth-lowenergy

I am using a NUCLEO-WB15CC board trying to build a BLE application.
I followed the instruction from a YT video by STM: https://www.youtube.com/watch?v=i10X4Blr8ns
I generated code with CubeMX version6-5-0 on linux.
The code called HardFaultHandler() as soon as it reach MX_APPE_Init() in main.c
if i break the while(1) loop in HardFaultHandler, the code continues at __HAL_RTC_WAKEUPTIMER_DISABLE(phrtc) in HW_TS_RTC_Wakeup_Handler() from Core/Src/hw_timerserver.c.
Why is that so? How do I rectify or solve this?
Thanks!
Below is main.c
#include "main.h"
IPCC_HandleTypeDef hipcc;
RTC_HandleTypeDef hrtc;
UART_HandleTypeDef huart1;
DMA_HandleTypeDef hdma_usart1_rx;
DMA_HandleTypeDef hdma_usart1_tx;
void SystemClock_Config(void);
void PeriphCommonClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_IPCC_Init(void);
static void MX_RF_Init(void);
static void MX_DMA_Init(void);
static void MX_RTC_Init(void);
int main(void)
{
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* Config code for STM32_WPAN (HSE Tuning must be done before system clock configuration) */
MX_APPE_Config();
/* Configure the system clock */
SystemClock_Config();
/* Configure the peripherals common clocks */
PeriphCommonClock_Config();
/* IPCC initialisation */
MX_IPCC_Init();
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_RF_Init();
MX_DMA_Init();
MX_RTC_Init();
/* Init code for STM32_WPAN */
MX_APPE_Init();
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
MX_APPE_Process();
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* #brief System Clock Configuration
* #retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure LSE Drive Capability
*/
HAL_PWR_EnableBkUpAccess();
__HAL_RCC_LSEDRIVE_CONFIG(RCC_LSEDRIVE_LOW);
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_HSE
|RCC_OSCILLATORTYPE_LSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.LSEState = RCC_LSE_ON;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Configure the SYSCLKSource, HCLK, PCLK1 and PCLK2 clocks dividers
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK4|RCC_CLOCKTYPE_HCLK2
|RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSE;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.AHBCLK2Divider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.AHBCLK4Divider = RCC_SYSCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
{
Error_Handler();
}
}
/**
* #brief Peripherals Common Clock Configuration
* #retval None
*/
void PeriphCommonClock_Config(void)
{
RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
/** Initializes the peripherals clock
*/
PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_SMPS|RCC_PERIPHCLK_RFWAKEUP;
PeriphClkInitStruct.RFWakeUpClockSelection = RCC_RFWKPCLKSOURCE_LSE;
PeriphClkInitStruct.SmpsClockSelection = RCC_SMPSCLKSOURCE_HSI;
PeriphClkInitStruct.SmpsDivSelection = RCC_SMPSCLKDIV_RANGE1;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
{
Error_Handler();
}
}
/**
* #brief IPCC Initialization Function
* #param None
* #retval None
*/
static void MX_IPCC_Init(void)
{
hipcc.Instance = IPCC;
if (HAL_IPCC_Init(&hipcc) != HAL_OK)
{
Error_Handler();
}
}
/**
* #brief RF Initialization Function
* #param None
* #retval None
*/
static void MX_RF_Init(void)
{
}
/**
* #brief RTC Initialization Function
* #param None
* #retval None
*/
static void MX_RTC_Init(void)
{
/** Initialize RTC Only
*/
hrtc.Instance = RTC;
hrtc.Init.HourFormat = RTC_HOURFORMAT_24;
hrtc.Init.AsynchPrediv = CFG_RTC_ASYNCH_PRESCALER;
hrtc.Init.SynchPrediv = CFG_RTC_SYNCH_PRESCALER;
hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;
hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
hrtc.Init.OutPutRemap = RTC_OUTPUT_REMAP_NONE;
if (HAL_RTC_Init(&hrtc) != HAL_OK)
{
Error_Handler();
}
/** Enable the WakeUp
*/
if (HAL_RTCEx_SetWakeUpTimer_IT(&hrtc, 0, RTC_WAKEUPCLOCK_RTCCLK_DIV16) != HAL_OK)
{
Error_Handler();
}
}
/**
* #brief USART1 Initialization Function
* #param None
* #retval None
*/
void MX_USART1_UART_Init(void)
{
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_8;
huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart1.Init.ClockPrescaler = UART_PRESCALER_DIV1;
huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetTxFifoThreshold(&huart1, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetRxFifoThreshold(&huart1, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_DisableFifoMode(&huart1) != HAL_OK)
{
Error_Handler();
}
}
/**
* Enable DMA controller clock
*/
static void MX_DMA_Init(void)
{
/* DMA controller clock enable */
__HAL_RCC_DMAMUX1_CLK_ENABLE();
__HAL_RCC_DMA1_CLK_ENABLE();
/* DMA interrupt init */
/* DMA1_Channel1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
/* DMA1_Channel2_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel2_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel2_IRQn);
}
/**
* #brief GPIO Initialization Function
* #param None
* #retval None
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOE_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOB, LD2_Pin|LD3_Pin|LD1_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin : B1_Pin */
GPIO_InitStruct.Pin = B1_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : B3_Pin */
GPIO_InitStruct.Pin = B3_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(B3_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pins : LD2_Pin LD3_Pin LD1_Pin */
GPIO_InitStruct.Pin = LD2_Pin|LD3_Pin|LD1_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pin : B2_Pin */
GPIO_InitStruct.Pin = B2_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(B2_GPIO_Port, &GPIO_InitStruct);
}
/**
* #brief This function is executed in case of error occurrence.
* #retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
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 /* USE_FULL_ASSERT */

Related

How can i write a long string to a RFID tag using arduino?

Hey i would like to write a long string like "Hello my name is james and i live in NewYork" in a rfid Tag using arduino.
The code for writing in a single block is the following one but i can only write 16 bytes in 1 block ....
but the only issue is that it does only write into 1 block.
So i would like that 16 First bytes goes to Block 1 ect ...
#include <SPI.h>
#include <MFRC522.h>
/*Using Hardware SPI of Arduino */
/*MOSI (11), MISO (12) and SCK (13) are fixed */
/*You can configure SS and RST Pins*/
#define SS_PIN 10 /* Slave Select Pin */
#define RST_PIN 7 /* Reset Pin */
/* Create an instance of MFRC522 */
MFRC522 mfrc522(SS_PIN, RST_PIN);
/* Create an instance of MIFARE_Key */
MFRC522::MIFARE_Key key;
/* Set the block to which we want to write data */
/* Be aware of Sector Trailer Blocks */
int blockNum = 2;
/* Create an array of 16 Bytes and fill it with data */
/* This is the actual data which is going to be written into the card */
byte blockData [16] = {"data-to-write-to-card"};
/* Create another array to read data from Block */
/* Legthn of buffer should be 2 Bytes more than the size of Block (16 Bytes) */
byte bufferLen = 18;
byte readBlockData[18];
MFRC522::StatusCode status;
void setup()
{
/* Initialize serial communications with the PC */
Serial.begin(9600);
/* Initialize SPI bus */
SPI.begin();
/* Initialize MFRC522 Module */
mfrc522.PCD_Init();
Serial.println("Scan a MIFARE 1K Tag to write data...");
}
void loop()
{
/* Prepare the ksy for authentication */
/* All keys are set to FFFFFFFFFFFFh at chip delivery from the factory */
for (byte i = 0; i < 6; i++)
{
key.keyByte[i] = 0xFF;
}
/* Look for new cards */
/* Reset the loop if no new card is present on RC522 Reader */
if ( ! mfrc522.PICC_IsNewCardPresent())
{
return;
}
/* Select one of the cards */
if ( ! mfrc522.PICC_ReadCardSerial())
{
return;
}
Serial.print("\n");
Serial.println("**Card Detected**");
/* Print UID of the Card */
Serial.print(F("Card UID:"));
for (byte i = 0; i < mfrc522.uid.size; i++)
{
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
}
Serial.print("\n");
/* Print type of card (for example, MIFARE 1K) */
Serial.print(F("PICC type: "));
MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
Serial.println(mfrc522.PICC_GetTypeName(piccType));
/* Call 'WriteDataToBlock' function, which will write data to the block */
Serial.print("\n");
Serial.println("Writing to Data Block...");
WriteDataToBlock(blockNum, blockData);
/* Read data from the same block */
Serial.print("\n");
Serial.println("Reading from Data Block...");
ReadDataFromBlock(blockNum, readBlockData);
/* If you want to print the full memory dump, uncomment the next line */
//mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
/* Print the data read from block */
Serial.print("\n");
Serial.print("Data in Block:");
Serial.print(blockNum);
Serial.print(" --> ");
for (int j=0 ; j<16 ; j++)
{
Serial.write(readBlockData[j]);
}
Serial.print("\n");
}
void WriteDataToBlock(int blockNum, byte blockData[])
{
/* Authenticating the desired data block for write access using Key A */
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, blockNum, &key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK)
{
Serial.print("Authentication failed for Write: ");
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
else
{
Serial.println("Authentication success");
}
/* Write data to the block */
status = mfrc522.MIFARE_Write(blockNum, blockData, 16);
if (status != MFRC522::STATUS_OK)
{
Serial.print("Writing to Block failed: ");
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
else
{
Serial.println("Data was written into Block successfully");
}
}
void ReadDataFromBlock(int blockNum, byte readBlockData[])
{
/* Authenticating the desired data block for Read access using Key A */
byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, blockNum, &key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK)
{
Serial.print("Authentication failed for Read: ");
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
else
{
Serial.println("Authentication success");
}
/* Reading data from the Block */
status = mfrc522.MIFARE_Read(blockNum, readBlockData, &bufferLen);
if (status != MFRC522::STATUS_OK)
{
Serial.print("Reading failed: ");
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
else
{
Serial.println("Block was read successfully");
}

Arduino RC 522 write and read data

I'm working on Arduino RC 522 RFID module. I'm want to write some data in the RFID card and read that data to operate a relay. So is that possible? I want to store integer data in the RFID CARD(13.5Mhz).
for writing the card you can try with this code, change the variable "blockData" with the integer, the lenght should be 16 bytes or you have to change the dimensions of the arrays and for cycles.
#include <SPI.h>
#include <MFRC522.h>
/*Using Hardware SPI of Arduino */
/*MOSI (11), MISO (12) and SCK (13) are fixed */
/*You can configure SS and RST Pins*/
#define SS_PIN 10 /* Slave Select Pin */
#define RST_PIN 7 /* Reset Pin */
/* Create an instance of MFRC522 */
MFRC522 mfrc522(SS_PIN, RST_PIN);
/* Create an instance of MIFARE_Key */
MFRC522::MIFARE_Key key;
/* Set the block to which we want to write data */
/* Be aware of Sector Trailer Blocks */
int blockNum = 2;
/* Create an array of 16 Bytes and fill it with data */
/* This is the actual data which is going to be written into the card */
byte blockData [16] = {"Electronics-Hub-"};
/* Create another array to read data from Block */
/* Legthn of buffer should be 2 Bytes more than the size of Block (16 Bytes) */
byte bufferLen = 18;
byte readBlockData[18];
MFRC522::StatusCode status;
void setup()
{
/* Initialize serial communications with the PC */
Serial.begin(9600);
/* Initialize SPI bus */
SPI.begin();
/* Initialize MFRC522 Module */
mfrc522.PCD_Init();
Serial.println("Scan a MIFARE 1K Tag to write data...");
}
void loop()
{
/* Prepare the ksy for authentication */
/* All keys are set to FFFFFFFFFFFFh at chip delivery from the factory */
for (byte i = 0; i < 6; i++)
{
key.keyByte[i] = 0xFF;
}
/* Look for new cards */
/* Reset the loop if no new card is present on RC522 Reader */
if ( ! mfrc522.PICC_IsNewCardPresent())
{
return;
}
/* Select one of the cards */
if ( ! mfrc522.PICC_ReadCardSerial())
{
return;
}
Serial.print("\n");
Serial.println("**Card Detected**");
/* Print UID of the Card */
Serial.print(F("Card UID:"));
for (byte i = 0; i < mfrc522.uid.size; i++)
{
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
}
Serial.print("\n");
/* Print type of card (for example, MIFARE 1K) */
Serial.print(F("PICC type: "));
MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
Serial.println(mfrc522.PICC_GetTypeName(piccType));
/* Call 'WriteDataToBlock' function, which will write data to the block */
Serial.print("\n");
Serial.println("Writing to Data Block...");
WriteDataToBlock(blockNum, blockData);
/* Read data from the same block */
Serial.print("\n");
Serial.println("Reading from Data Block...");
ReadDataFromBlock(blockNum, readBlockData);
/* If you want to print the full memory dump, uncomment the next line */
//mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
/* Print the data read from block */
Serial.print("\n");
Serial.print("Data in Block:");
Serial.print(blockNum);
Serial.print(" --> ");
for (int j=0 ; j<16 ; j++)
{
Serial.write(readBlockData[j]);
}
Serial.print("\n");
}
void WriteDataToBlock(int blockNum, byte blockData[])
{
/* Authenticating the desired data block for write access using Key A */
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, blockNum, &key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK)
{
Serial.print("Authentication failed for Write: ");
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
else
{
Serial.println("Authentication success");
}
/* Write data to the block */
status = mfrc522.MIFARE_Write(blockNum, blockData, 16);
if (status != MFRC522::STATUS_OK)
{
Serial.print("Writing to Block failed: ");
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
else
{
Serial.println("Data was written into Block successfully");
}
}
void ReadDataFromBlock(int blockNum, byte readBlockData[])
{
/* Authenticating the desired data block for Read access using Key A */
byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, blockNum, &key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK)
{
Serial.print("Authentication failed for Read: ");
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
else
{
Serial.println("Authentication success");
}
/* Reading data from the Block */
status = mfrc522.MIFARE_Read(blockNum, readBlockData, &bufferLen);
if (status != MFRC522::STATUS_OK)
{
Serial.print("Reading failed: ");
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
else
{
Serial.println("Block was read successfully");
}
}
For reading data use this code, change "mioCod" with the UID of the card
void ceckRFID(){
//check new cards
if (!mfrc522.PICC_IsNewCardPresent())
{
return;
}
//If read UID
if (!mfrc522.PICC_ReadCardSerial())
{
return;
}
String codLetto = ""; //clean the reading string
for (byte i = 0; i < mfrc522.uid.size; i++) { //save the code into the string
codLetto += String(mfrc522.uid.uidByte[i], HEX);
}
codLetto.toUpperCase(); //uppercase the string
Serial.println(codLetto); //print the code
if(codLetto == mioCod){ //if the code match with mioCod
Serial.println("Code recognized");
}
else{
Serial.println("Wrong code");
}
}

How can I write personal data on a RFID sensor in arduino in my code?

I want to write a personal data on my Card like:
"Name"
"Age"
"Region"
etc.
I wanna do this in this code:
https://imgur.com/BnlsKU3
https://imgur.com/4lNDqVX
https://imgur.com/LGCdXET
On this links are my screens to my code
Use this basic approach to adapt to your code. So far your arduino code is only reading information from the card or tag with pre-loaded data.
You can follow this to write data to your card
Pls: Follow your card documentation or datasheet on the amount of data you can write to it
#include <SPI.h>
#include <MFRC522.h>
/*Using Hardware SPI of Arduino */
/*MOSI (11), MISO (12) and SCK (13) are fixed */
/*You can configure SS and RST Pins*/
#define SS_PIN 10 /* Slave Select Pin */
#define RST_PIN 7 /* Reset Pin */
/* Create an instance of MFRC522 */
MFRC522 mfrc522(SS_PIN, RST_PIN);
/* Create an instance of MIFARE_Key */
MFRC522::MIFARE_Key key;
/* Set the block to which we want to write data */
/* Be aware of Sector Trailer Blocks */
int blockNum = 2;
/* Create an array of 16 Bytes and fill it with data */
/* This is the actual data which is going to be written into the card */
byte blockData [16] = {"data-to-write-to-card"};
/* Create another array to read data from Block */
/* Legthn of buffer should be 2 Bytes more than the size of Block (16 Bytes) */
byte bufferLen = 18;
byte readBlockData[18];
MFRC522::StatusCode status;
void setup()
{
/* Initialize serial communications with the PC */
Serial.begin(9600);
/* Initialize SPI bus */
SPI.begin();
/* Initialize MFRC522 Module */
mfrc522.PCD_Init();
Serial.println("Scan a MIFARE 1K Tag to write data...");
}
void loop()
{
/* Prepare the ksy for authentication */
/* All keys are set to FFFFFFFFFFFFh at chip delivery from the factory */
for (byte i = 0; i < 6; i++)
{
key.keyByte[i] = 0xFF;
}
/* Look for new cards */
/* Reset the loop if no new card is present on RC522 Reader */
if ( ! mfrc522.PICC_IsNewCardPresent())
{
return;
}
/* Select one of the cards */
if ( ! mfrc522.PICC_ReadCardSerial())
{
return;
}
Serial.print("\n");
Serial.println("**Card Detected**");
/* Print UID of the Card */
Serial.print(F("Card UID:"));
for (byte i = 0; i < mfrc522.uid.size; i++)
{
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
}
Serial.print("\n");
/* Print type of card (for example, MIFARE 1K) */
Serial.print(F("PICC type: "));
MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
Serial.println(mfrc522.PICC_GetTypeName(piccType));
/* Call 'WriteDataToBlock' function, which will write data to the block */
Serial.print("\n");
Serial.println("Writing to Data Block...");
WriteDataToBlock(blockNum, blockData);
/* Read data from the same block */
Serial.print("\n");
Serial.println("Reading from Data Block...");
ReadDataFromBlock(blockNum, readBlockData);
/* If you want to print the full memory dump, uncomment the next line */
//mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
/* Print the data read from block */
Serial.print("\n");
Serial.print("Data in Block:");
Serial.print(blockNum);
Serial.print(" --> ");
for (int j=0 ; j<16 ; j++)
{
Serial.write(readBlockData[j]);
}
Serial.print("\n");
}
void WriteDataToBlock(int blockNum, byte blockData[])
{
/* Authenticating the desired data block for write access using Key A */
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, blockNum, &key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK)
{
Serial.print("Authentication failed for Write: ");
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
else
{
Serial.println("Authentication success");
}
/* Write data to the block */
status = mfrc522.MIFARE_Write(blockNum, blockData, 16);
if (status != MFRC522::STATUS_OK)
{
Serial.print("Writing to Block failed: ");
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
else
{
Serial.println("Data was written into Block successfully");
}
}
void ReadDataFromBlock(int blockNum, byte readBlockData[])
{
/* Authenticating the desired data block for Read access using Key A */
byte status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, blockNum, &key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK)
{
Serial.print("Authentication failed for Read: ");
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
else
{
Serial.println("Authentication success");
}
/* Reading data from the Block */
status = mfrc522.MIFARE_Read(blockNum, readBlockData, &bufferLen);
if (status != MFRC522::STATUS_OK)
{
Serial.print("Reading failed: ");
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
else
{
Serial.println("Block was read successfully");
}
}

Sim800l Receives Sms but Show unknown numbers, Hardware is just fine

I'm trying Sim800l and ESP8066 As my serial communication to Mega r3.
when i try sim800l code side, something like this: which i refined the code a little bit. In Serial monitor handshakes are ok. but when new sms arrives it doesn't show the right content.
Why with same code I see different results?
void setup()
{
Serial.begin(9600);
Serial1.begin(9600);
Serial.println("Starting...");
delay(1000);
Serial1.println("AT");
pollSms();
Serial1.println("AT+CMGF=1");
pollSms();
Serial1.println("AT+CNMI=1,2,0,0,0");
pollSms();
}
void loop()
{
pollSms();
}
void pollSms()
{
delay(500);
while (Serial.available())
{
Serial1.write(Serial.read());
}
while(Serial1.available())
{
Serial.write(Serial1.read());
}
}
everything is just fine but when I try
#include <SPI.h>//Communicate via WiFi
#include <DHT.h>
#include <avr/sleep.h>
#include <avr/interrupt.h>
#include <WiFi.h>
/* Libraries */
/* Variables */
char id[] = "id";//id of Wifi network
char pass[] = "password";//password of Wifi network
const char* host = "esp8266sd";
float humadity1 , temprature1=25;//Solon 1
float humadity2 , temprature2;//Solon 2
int Soil_humadity1,Soil_humadity2,Soil_humadity3;
char c;
String WiFi_instruction="";
String SMSmessage="";
String number, Answer;
boolean valid;
#define TWO_HRS 7200000
unsigned long startTime1,startTime2;
/* Variables */
/* AM2301 */
#define DHTTYPE DHT21 // It defines which kind of humadity and temprature sensor is connecter (AM2301)
DHT dht1(DHTPIN1, DHTTYPE);
DHT dht2(DHTPIN2, DHTTYPE);
/* AM2301 */
/* Android App */
WiFiServer server(80);
/* Android App */
/* Valid numbers */
String num1="9016057005";
String num2="9026057005";//change it
/* Valid numbers */
void setup()
{
/* Pins Settings */
/* Serial communications */
Serial.begin(9600); // setup baudrate for transition to "serial monitor"
Serial1.begin(9600);//Sim800l Serial Communication
Serial3.begin(9600);//ESP8266 Serial Communication
/* SMS Settings */
Serial.println("Start!...");
Serial1.println("AT"); //Send AT command it will says "OK" if everything is fine
Serialcom(); //description below
Serial1.println("AT+CMGF=0"); // Configuring TEXT mode
Serialcom();
Serial1.println("AT+IPR=9600");
Serial1.println("AT+CNMI=1,2,0,0,0");
Serialcom();
/* SMS Settings */
/* Serial communications */
/* Timers */
startTime1 = millis();
startTime2 = millis();
/* Timers */
/* Sensors */
dht1.begin(); //setup humadity and temprature sensor: Solon 1
dht2.begin(); //setup humadity and temprature sensor: Solon 2
humadity1 = dht1.readHumidity();
temprature1 = dht1.readTemperature();
humadity2 = dht2.readHumidity();
temprature2 = dht2.readTemperature();
/* Sensors */
}//setup ended
void loop()
{
char x;
/* Receiving instruction from WiFi' serial */
while (Serial3.available())
{
x=Serial3.read();
WiFi_instruction.concat(x);
}
Serial.println("WiFi instructions");
/* Check for any instruction*/
WiFi_instruction="";// WiFi_instruction is empty now.
}//if WiFi_instruction.length()!-0
/* Receiving instruction from WiFi' serial */
/* Yl-69 Sensors */
Soil_humadity1=digitalRead(YL1);//If it return 1, soil is ok otherwise not
Soil_humadity2=digitalRead(YL2);
Soil_humadity3=digitalRead(YL3);
/* Yl-69 Sensors */
/* AS2301 Sensors's Data */
float temp_temprature1,temp_temprature2,temp_humadity1,temp_humadity2;
temp_temprature1= dht1.readTemperature();
temp_temprature2= dht2.readTemperature();
temp_humadity1=dht1.readHumidity();
temp_humadity2=dht2.readHumidity();
//Whether data is NaN or 0 or some none sense increment-decrement, new numbers won't be considered
if(isnan(temp_temprature1) ||isnan(temp_temprature2)||
isnan(temp_humadity1)||isnan(temp_humadity2))
{
/* Do nothing */
}
else
{
if(temp_temprature1!=0 &&
temp_temprature2!=0&&
temp_humadity1!=0 &&
temp_humadity2!=0)
{
if(abs(dht1.readHumidity()-humadity1)<10
&& abs(dht2.readHumidity()-humadity2)<10
&& abs(dht1.readTemperature()-temprature1)<10
&& abs(dht2.readTemperature()-temprature2)<10)
{
Serial.print(" Sensor values have been changed ");
humadity1 = dht1.readHumidity();
temprature1 = dht1.readTemperature();
humadity2 = dht2.readHumidity();
temprature2 = dht2.readTemperature();
}
}
}
/* AS2301 Sensors's Data */
/* Check for any SMS */
while(Serial1.available())
{
x=Serial1.read();
SMSmessage.concat(x);
}
Serial.println("SMS:");
Serial.println(SMSmessage);
if(SMSmessage.length()>0)
{
int valid1=SMSmessage.indexOf(num1);
int valid2=SMSmessage.indexOf(num2);
if(valid1==0 || valid2==0)
{
Serial.println("number is valid");
valid=true;
}
/*Extranct the number to andwer */
if(valid1==0)
number=num1;
if(valid2==0)
number=num2;
/*Extranct the number to andwer */
/*Check for any sms */
/* Answering via SMS */
//If there is the Code for a specific Instruction it return 1 otherwise returns -1
if(valid)
{
inst00=SMSmessage.indexOf(inst0);
inst01_CHECK=SMSinst01=SMSmessage.indexOf(inst1);//automatic
inst02_CHECK=SMSinst02=SMSmessage.indexOf(inst2);
inst03_CHECK=SMSinst03=SMSmessage.indexOf(inst3);
inst04_CHECK=SMSinst04=SMSmessage.indexOf(inst4);
if(SMSinst02 ==-1 && SMSinst03==-1 && SMSinst04==-1)// if none of the non-automatic in selected it mast remain automatic
SMSinst01=0;
inst05_CHECK=SMSinst05=SMSmessage.indexOf(inst5);//automatic
inst06_CHECK=SMSinst06=SMSmessage.indexOf(inst6);
inst07_CHECK=SMSinst07=SMSmessage.indexOf(inst7);
inst08_CHECK=SMSinst08=SMSmessage.indexOf(inst8);
if(SMSinst06 ==-1 && SMSinst07==-1 && SMSinst08==-1)// if none of the non-automatic in selected it mast remain automatic
SMSinst05=0;
inst09_CHECK=SMSinst09=SMSmessage.indexOf(inst9);//automatic
inst010_CHECK=SMSinst010=SMSmessage.indexOf(inst10);
inst011_CHECK=SMSinst011=SMSmessage.indexOf(inst11);
if(SMSinst010 ==-1 && SMSinst011==-1)// if none of the non-automatic in selected it mast remain automatic
SMSinst09=0;
inst012_CHECK=SMSinst012=SMSmessage.indexOf(inst12);//automatic
inst013_CHECK=SMSinst013=SMSmessage.indexOf(inst13);
inst014_CHECK=SMSinst014=SMSmessage.indexOf(inst14);
if(SMSinst013 ==-1 && SMSinst014==-1)// if none of the non-automatic in selected it mast remain automatic
inst012=0;
inst015_CHECK=SMSinst015=SMSmessage.indexOf(inst15);//automatic
inst016_CHECK=SMSinst016=SMSmessage.indexOf(inst16);
inst017_CHECK=SMSinst017=SMSmessage.indexOf(inst17);
if(SMSinst016 ==-1 && SMSinst017==-1)// if none of the non-automatic in selected it mast remain automatic
SMSinst015=0;
inst018_CHECK=SMSinst018=SMSmessage.indexOf(inst18);//automatic
inst019_CHECK=SMSinst019=SMSmessage.indexOf(inst19);
inst020_CHECK=SMSinst020=SMSmessage.indexOf(inst20);
if(SMSinst019 ==-1 && SMSinst020==-1)// if none of the non-automatic in selected it mast remain automatic
SMSinst018=0;
inst021_CHECK=SMSinst021=SMSmessage.indexOf(inst21);//automatic
inst022_CHECK=SMSinst022=SMSmessage.indexOf(inst22);
inst023_CHECK=SMSinst023=SMSmessage.indexOf(inst23);
if(SMSinst022 ==-1 && SMSinst023==-1)// if none of the non-automatic in selected it mast remain automatic
SMSinst021=0;
inst024_CHECK=SMSinst024=SMSmessage.indexOf(inst24);//automatic
inst025_CHECK=SMSinst025=SMSmessage.indexOf(inst25);
inst026_CHECK=SMSinst026=SMSmessage.indexOf(inst26);
if(SMSinst025 ==-1 && SMSinst026==-1)// if none of the non-automatic in selected it mast remain automatic
SMSinst024=0;
inst027_CHECK=SMSinst027=SMSmessage.indexOf(inst27);//automatic
inst028_CHECK=SMSinst028=SMSmessage.indexOf(inst28);
inst029_CHECK=SMSinst029=SMSmessage.indexOf(inst29);
if(SMSinst028 ==-1 && SMSinst029==-1)// if none of the non-automatic in selected it mast remain automatic
SMSinst027=0;
SMSmessage="";//SMSmessage now is empty until next sms
}//if valid
}// if SMS.length()
Serial.println("SMS instructions");
if(inst00)
{
String statSoil1,statSoil2,statSoil3;
/* YL, Soil's humadity Sensors results */
}//Loop ends
/*Functions */
/*
void Serialcom()
{
delay(500);
while(Serial.available()) // IDE serial l serial Serial1
{
Serial1.write(Serial.read());//Forward what Serial received to Software Serial Port
}
while(Serial1.available()) //serialSerial1 l serial dial IDE
{
Serial.write(Serial1.read());//Forward what Software Serial received to Serial Port
}
}
/*Functions */

DMA transfer corrupted by another channel (ATSAMC21)

I want to use DAM transfer for calculating CRC with ATSAMC21G17A MCU (E-revision).
I have already implemented 2 independent DMA channels controlling UART transfer, they are working good, I have no problems with them.
Now it's time to get CRC calculating working to calculate CRC of the Flash memory. I just use one timer to generate triggering events for DMA, I know the size of my firmware and just want to get it working. Timer works with period of 100usec.
But it doesn't really work, I get errors with another channels after starting DMA channel with CRC calculation, transfer process of another channel can be interrupted and doesn't work afterwards. It means it could transfer only some bytes, but not all of them. What am I doing wrong?
I have already read the whole errata about my MCU and don't find anything similar. I don't use link descriptors.
Here is my source code:
DMA initialization:
volatile bool DMA_TransferComplete[DMA_CHANNELS_NUM];
static DmacDescriptor dma_descr[DMA_CHANNELS_NUM] __attribute__((aligned(16))) SECTION_DMAC_DESCRIPTOR;
static DmacDescriptor writeback[DMA_CHANNELS_NUM] __attribute__((aligned(16))) SECTION_DMAC_DESCRIPTOR;
static DmacDescriptor descriptor __attribute__((aligned(16))) SECTION_DMAC_DESCRIPTOR;
/** \brief Initialize DMA module
*
* \return Nothing
*
*/
void DMA_Init(void)
{
uint8_t i;
MCLK->AHBMASK.reg |= MCLK_AHBMASK_DMAC;
DMAC->CTRL.reg &= ~DMAC_CTRL_DMAENABLE;
DMAC->CTRL.reg = DMAC_CTRL_SWRST;
DMAC->BASEADDR.reg = (uint32_t)dma_descr;
DMAC->WRBADDR.reg = (uint32_t)writeback;
DMAC->CTRL.reg = DMAC_CTRL_DMAENABLE | DMAC_CTRL_LVLEN(0xf);
for (i = 0; i < DMA_CHANNELS_NUM; i++)
DMA_TransferComplete[i] = true;
NVIC_EnableIRQ(DMAC_IRQn);
NVIC_SetPriority(DMAC_IRQn, 1);
}
Setup for DMA channel:
/** \brief Setup DMA transfer for selected channel
*
* \param [in] channel Number of the channel to act
* \param [in] settings Pointer to TDmaSettings structure with DMA settings
* \return Nothing
*
*/
void DMA_SetupChannel(uint8_t channel, TDmaSettings *settings)
{
uint16_t btctrlVal;
if (channel >= DMA_CHANNELS_NUM)
return;
/**< Setup channel */
DMAC->CHID.reg = DMAC_CHID_ID(channel);
DMAC->CHCTRLA.reg &= ~DMAC_CHCTRLA_ENABLE;
DMAC->CHCTRLA.reg = DMAC_CHCTRLA_SWRST;
DMAC->SWTRIGCTRL.reg &= (uint32_t)(~(1 << channel));
if (settings->trig_src == 0)
DMAC->CHCTRLB.reg = DMAC_CHCTRLB_LVL(settings->priority) | DMAC_CHCTRLB_TRIGACT_BLOCK;
else
DMAC->CHCTRLB.reg = DMAC_CHCTRLB_LVL(settings->priority) | DMAC_CHCTRLB_TRIGSRC(settings->trig_src) | DMAC_CHCTRLB_TRIGACT_BEAT;
/**< Enable interrupts */
DMAC->CHINTENSET.reg = DMAC_CHINTENSET_MASK;
/**< Prepare descriptor block */
descriptor.DESCADDR.reg = 0; // only one block to transfer, so 0
descriptor.BTCNT.reg = settings->len;
btctrlVal = DMAC_BTCTRL_VALID | DMAC_BTCTRL_BEATSIZE(settings->beat_size);
descriptor.DSTADDR.reg = (uint32_t)settings->dst_addr;
if (settings->dst_inc == true)
{
descriptor.DSTADDR.reg += settings->len;
btctrlVal |= DMAC_BTCTRL_DSTINC;
}
descriptor.SRCADDR.reg = (uint32_t)settings->src_addr;
if (settings->src_inc == true)
{
descriptor.SRCADDR.reg += settings->len;
btctrlVal |= DMAC_BTCTRL_SRCINC;
}
descriptor.BTCTRL.reg = btctrlVal;
memcpy(&dma_descr[channel], &descriptor, sizeof(DmacDescriptor));
}
Interrupt function for detection of "transfer complete" event:
/**< Interrupt for DMA transfer completion */
void DMAC_Handler(void)
{
uint8_t channel;
uint8_t old_channel;
uint32_t res;
/**< Get old channel number */
old_channel = DMAC->CHID.reg;
res = DMAC->INTSTATUS.reg;
/**< Processing all affected channels */
for (channel = 0; channel < DMA_CHANNELS_NUM; channel++)
{
if (res & (1 << channel))
{
/**< Set transfer complete flag */
DMA_TransferComplete[channel] = true;
/**< Select channel to work with */
DMAC->CHID.reg = DMAC_CHID_ID(channel);
/**< Clear all flags for DMA channel */
DMAC->CHINTFLAG.reg = (DMAC_CHINTENCLR_TCMPL | DMAC_CHINTENCLR_TERR | DMAC_CHINTENCLR_SUSP);
/**< Disable DMA transfer */
DMAC->CHCTRLA.reg &= ~DMAC_CHCTRLA_ENABLE;
}
}
DMAC->CHID.reg = old_channel;
}
Starting DMA transfer:
/** \brief Start DMA transfer, channel should be already initialized
*
* \param [in] channel Number of the channel to act
* \return Nothing
*
*/
void DMA_StartChannel(uint8_t channel)
{
if (channel >= DMA_CHANNELS_NUM)
return;
/**< Setup channel */
DMAC->CHID.reg = DMAC_CHID_ID(channel);
if (DMA_TransferComplete[channel] == false)
DMAC->CHCTRLA.reg &= ~DMAC_CHCTRLA_ENABLE;
/**< Start DMA transfer */
DMA_TransferComplete[channel] = false;
DMAC->CHCTRLA.reg |= DMAC_CHCTRLA_ENABLE;
}
Setup CRC calculation:
/** \brief Initialize CRC module
*
* \param
* \param
* \return Nothing
*
*/
void DMA_InitCRC(void)
{
/**< Power on timer */
MCLK->APBCMASK.reg |= DMA_CRC_TIMER_MCLK;
GCLK->PCHCTRL[DMA_CRC_TIMER_GCLK_ID].reg = GCLK_PCHCTRL_GEN_GCLK0_Val | (1 << GCLK_PCHCTRL_CHEN_Pos);
/**< Setup timer for 100usec events */
DMA_CRC_TIMER->COUNT8.CTRLA.reg = TC_CTRLA_SWRST;
while (DMA_CRC_TIMER->COUNT8.SYNCBUSY.reg & TC_SYNCBUSY_SWRST);
DMA_CRC_TIMER->COUNT8.CTRLA.reg |= (DMA_CRC_TIMER_PRESCALER << TC_CTRLA_PRESCALER_Pos) | TC_CTRLA_MODE_COUNT8;
DMA_CRC_TIMER->COUNT8.CTRLBSET.bit.DIR = 0;
DMA_CRC_TIMER->COUNT8.PER.reg = DMA_CRC_TIMER_TICK;
DMA_CRC_TIMER->COUNT8.COUNT.reg = 0;
DMA_CRC_TIMER->COUNT8.CTRLA.reg |= (TC_CTRLA_ENABLE);
DMAC->CTRL.reg &= ~DMAC_CTRL_CRCENABLE;
/**< Configure the CRC engine */
DMAC_CRCCTRL_Type crcctrl =
{
.bit.CRCSRC = DMAC_CRCCTRL_CRCSRC_IO_Val, /* I/O interface */
.bit.CRCPOLY = DMAC_CRCCTRL_CRCPOLY_CRC16_Val, /* CRC-16 (CRC-CCITT) */
.bit.CRCBEATSIZE = DMAC_CRCCTRL_CRCBEATSIZE_BYTE_Val, /* Byte bus access */
};
DMAC->CRCCTRL.reg = crcctrl.reg;
}
Start new CRC calculation:
/** \brief Start CRC conversion
*
* \param [in] crc_init CRC initial value
* \return Nothing
*
*/
void DMA_StartCRC(uint32_t crc_init)
{
/**< Clear the busy bit */
DMAC->CRCSTATUS.bit.CRCBUSY = 1;
DMAC->CTRL.bit.CRCENABLE = 0;
/**< Initialize start CRC value for the CRC16 */
DMAC->CRCCHKSUM.reg = crc_init;
/**< Enable the CRC engine */
DMAC->CTRL.bit.CRCENABLE = 1;
}
Get result of CRC calculation:
/** \brief Get CRC result from DMA module
*
* \return CRC as uint16_t
*
*/
uint16_t DMA_GetCRC(void)
{
return (uint16_t)DMAC->CRCCHKSUM.reg;
}
And now the source code of the thread with CRC calculation (I am using FreeRTOS):
/**< CRC initialization */
DMA_InitCRC();
/**< Setup DMA channel for transmission */
DmaSett.beat_size = DMAC_BTCTRL_BEATSIZE_BYTE_Val;
DmaSett.trig_src = TC1_DMAC_ID_OVF;
DmaSett.dst_addr = (void*)&DMAC->CRCDATAIN.reg;
DmaSett.src_addr = APP_ADDRESS;
DmaSett.src_inc = true;
DmaSett.dst_inc = false;
DmaSett.len = addr;
DmaSett.priority = 0;
DMA_SetupChannel(DMA_CHANNEL_CRC, &DmaSett);
DMA_StartCRC(CRC16_INIT_VAL);
DMA_StartChannel(DMA_CHANNEL_CRC);
while (1)
{
// some periodical actions
// ...
if (DMA_IsReady(DMA_CHANNEL_CRC) == true)
{
crc = DMA_GetCRC();
DMA_StartCRC(CRC16_INIT_VAL);
DMA_StartChannel(DMA_CHANNEL_CRC);
// do something with CRC here
// ...
}
}
Does anybody have any experiences with DMA module of ATSAMC21? Actually it runs normally with UART, but I can't solve this problem with CRC interaction for some days already.
I will be grateful for any ideas!

Resources