SPI issues while using STM32 as slave - stm32

I am using STM32L496RG and have configured it as a slave as follows
/* SPI1 init function */
void MX_SPI1_Init(void)
{
hspi1.Instance = SPI1;
hspi1.Init.Mode = SPI_MODE_SLAVE;
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_2;
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi1.Init.CRCPolynomial = 7;
hspi1.Init.CRCLength = SPI_CRC_LENGTH_DATASIZE;
hspi1.Init.NSSPMode = SPI_NSS_PULSE_DISABLE;
if (HAL_SPI_Init(&hspi1) != HAL_OK)
{
Error_Handler();
}
}
I am simply trying to receive data from ESP32 (master) and transmit some data back to ESP32.
void state_standby()
{
#ifdef ESP_PRESENT
if(HAL_SPI_Receive(&hspi1,(uint8_t*)cmd_from_esp, sizeof(cmd_from_esp), 200)!=HAL_OK){
Error_Handler();
}
else{
if (cmd_from_esp[0] == 'S' && cmd_from_esp[1] == 'T' && cmd_from_esp[2] == 'A' && cmd_from_esp[3] == 'R' && cmd_from_esp[4] == 'T'){
if (HAL_SPI_Transmit(&hspi1,(uint8_t*)cmd_from_esp,sizeof(cmd_from_esp),200)!= HAL_OK){
Error_Handler();
}
set_operating_state(TEST_SET);
}
}
#else
set_operating_state(ACTIVE);
flash_page_count = 0;
esp_page_count = 0;
#endif
}
But when I run my code, even though nothing is being received, my code goes into the Error_Handler function inside HAL_SPI_Receiveand goes to state 0x03 (HAL_TIMEOUT). But, nevertheless, when it receives data from ESP32, it does change its state is able to receive the data properly. But the problem I am facing is during my transmission. If I receive START in STM32, I send the same thing back to ESP32, but on the ESP32, I receive STARS. I am not sure if it this is because of HAL_ERROR or due to coding on ESP32 which is below -
for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (serverClients[i] && serverClients[i].connected()){
if(serverClients[i].available()){
//get data from the telnet client and push it to the UART
while(serverClients[i].available())
{
data_array[j]=(serverClients[i].read());
j++;
}
for(m = 0;m<j-2;m++)
vspiCommand();
j=0;
}
}
else {
if (serverClients[i]) {
serverClients[i].stop();
}
}
}
void vspiCommand() {
//Serial.println("in vspi");
//use it as you would the regular arduino SPI API
vspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
digitalWrite(VSPI_SS, LOW); //pull SS slow to prep other end for transfer
{
received_data[m] = vspi->transfer(data_array[m]);
//vspi->transfer(data_array[m]);
// Serial.print(data_array[m]);
// Serial.print('\t');
Serial.print(received_data[m]);
Serial.print('\t');
Serial.println(m);
}
delayMicroseconds(10);
digitalWrite(VSPI_SS, HIGH); //pull ss high to signify end of data transfer
vspi->endTransaction();
}
ESP32 receives data through my phone into data_array buffer and sends it to STM32, which in turn is sending the received data back to ESP32 which it is trying to read.
EDIT - I have modified the code a bit. Now, I am using HAL_SPI_Receive_ITand it stops hanging on that error. Made the following change in Slave side.
while (1)
{
if(HAL_SPI_Receive_IT(&hspi1,(uint8_t*)buffer,sizeof(buffer))!=HAL_OK){
Error_Handler();
}
while(HAL_SPI_GetState(&hspi1) != HAL_SPI_STATE_READY);
}
}
void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi)
{
if(HAL_SPI_Transmit(&hspi1,(uint8_t*)buffer,sizeof(buffer),200)!=HAL_OK){
Error_Handler();
}
And following changes in master side -
for(i = 0; i < MAX_SRV_CLIENTS; i++){
if (serverClients[i] && serverClients[i].connected()){
if(serverClients[i].available()){
//get data from the telnet client and push it to the UART
while(serverClients[i].available())
{
// read the bytes incoming from the client:
char thisChar = serverClients[i].read();
inData += thisChar;
data_array[j]=thisChar;
j++;
// echo to the server what's been received to confirm we have the string
if (thisChar == '\n')
{
// Serial.print("\nreceived:");
// Serial.print(inData);
for(int i=0;i<(j-2);i++)
{
vspi->beginTransaction(SPISettings(spiClk, MSBFIRST, SPI_MODE0));
digitalWrite(VSPI_SS, LOW); //pull SS slow to prep other end for transfer
{
received_data[i] = vspi->transfer(data_array[i]);
// Serial.print(data_array[m]);
// Serial.print('\t');
Serial.print(received_data[i]);
Serial.print('\t');
Serial.println(i);
}
digitalWrite(VSPI_SS, HIGH); //pull ss high to signify end of data transfer
vspi->endTransaction();
}
serverClients[i].write(received_data, (j-2));
j=0;
}
}
}
The slave(STM32) is able to receive the data properly, but the master(ESP32) receives the proper data only alternately. For example, if I send hello, it receives eeeee(second character of whichever data I'm trying to send). If I send hello again, it receives hello. . (In the image, you can see the slave received data in buffer array and master received data in COM2 port.

Related

STM32 FATFS, How to proper remount SD card using SPI?

I am using a SD card for data logging. I am using the free fatfs file system from chan and SPI to communicate with the SD card. However I ran into problems when reenserting the card. It no longer works. More specifically the f_mount() function fails in in the disk_initialize() function because it is not recognized as a SDv2 card, altough it is. The first time the function is called (when booting the STM32 controller) this function returns that the card is a SDv2, after taking out the sd card, reinserting and then mounting it again it fails to detect the card.
I have tried to umount it before using f_unmount(), also I cleaned the memory of the FATFs object on the stask.
Before each write I enable powersupply to the sd card and disable it after finish of writing. This works also perfectly fine. as long as I do not reinsert the card. it seems so strange. I also tryied to reinit the SPI before each f_mount. Also does not help.
Following code works fine , but after reinserton of sd card it works no longer:
HAL_SPI_DeInit(&hspi1);
HAL_GPIO_WritePin(__SD_EN_GPIO_Port, __SD_EN_Pin, GPIO_PIN_RESET);
osDelay(10);
while(LightisIniting() == true);
/* reset physical driver */
memset(&SDFatFs, 0, sizeof(FATFS));
f_unmount("0");
osDelay(1);
/* check filenumber */
if ((errorcode = SD_Read_Filenumber()) != NO_ERROR) {
return errorcode;
}
if ((errorcode = SD_Write_Filenumber()) != NO_ERROR) {
return errorcode;
}
static uint8_t SD_Read_Filenumber()
{
char init_data[20];
uint8_t new_file_flag = 0;
uint8_t errorcode = 0;
uint16_t bytesread;
char * pEnd;
errorcode = SD_InitFATFS();
if (errorcode == NO_ERROR) errorcode = SD_File_Open(&SDFileInit, "DATA.INI", FA_OPEN_ALWAYS | FA_READ);
if (errorcode == NO_ERROR) errorcode = SD_File_Read(&SDFileInit, init_data, 20, &bytesread);
if (errorcode == ERROR_SD_READ_DATA_LEN)
{
filenumber = 0; // empty (new) data.ini-file, so set filenumber to 0
new_file_flag = 1;
errorcode = NO_ERROR;
}
else
{
if (errorcode == 0) filenumber = strtol(init_data, &pEnd, 10);
}
if (errorcode == NO_ERROR) errorcode = f_close(&SDFileInit);
if ((errorcode == NO_ERROR) && (new_file_flag)) errorcode = SD_Write_Filenumber();
if (errorcode > 0) filenumber = 0;
return errorcode;
}
static uint8_t SD_Write_Filenumber()
{
char init_data[20];
uint8_t errorcode = 0;
errorcode = SD_InitFATFS();
snprintf(init_data, 10, "%u", filenumber);
if (errorcode == NO_ERROR) errorcode = SD_File_Open(&SDFileInit, "DATA.INI", FA_CREATE_ALWAYS | FA_WRITE);
if (errorcode == NO_ERROR) errorcode = SD_File_Write(&SDFileInit, init_data, strlen(init_data));
if (errorcode == NO_ERROR) errorcode = f_close(&SDFileInit);
return errorcode;
}
int SD_Initialize() {
uint8_t errorcode = 0;
HAL_GPIO_WritePin(__SD_EN_GPIO_Port, __SD_EN_Pin, GPIO_PIN_RESET);
osDelay(1);
while(LightisIniting() == true);
/* check filenumber */
if ((errorcode = SD_Read_Filenumber()) == NO_ERROR) {
filenumber++;
if ((errorcode = SD_Write_Filenumber()) != NO_ERROR) {
return errorcode;
}
}
else {
return errorcode;
}
return 0;
}

STM32 timer can't capture PWM input

my board:STM32 H743 after configure the advanced timer to capture pwm input,i can get the pwm frequency. but if i use hal_init() in the
main function,can't get, why? i add led in the interupt , now led not on, means ,can get into call back function.show my codes:
main:
HAL_Init();
SystemClock_Config();
TIMx_Configuration();
TIM8_Configuration();
configuration part:
tim2 just let led toggle 1s in callback function
void TIMx_Configuration(void)
{
//TIMx_GPIO_Config();
HAL_NVIC_SetPriority(GENERAL_TIM_IRQn, 0, 1);
HAL_NVIC_EnableIRQ(GENERAL_TIM_IRQn);
GENERAL_TIM_CLK_ENABLE();
TIM_TimeBaseStructure.Instance = GENERAL_TIM;
TIM_TimeBaseStructure.Init.Period = 10000 - 1;
TIM_TimeBaseStructure.Init.Prescaler = 240000 - 1;
HAL_TIM_Base_Init(&TIM_TimeBaseStructure);
HAL_TIM_Base_Start_IT(&TIM_TimeBaseStructure);
}
void TIM8_Configuration()
{
//set priority
HAL_NVIC_SetPriority(MOTORIC_TIM_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(MOTORIC_TIM_IRQn);
TIM_IC_InitTypeDef TIM_ICInitStructure;
TIM_SlaveConfigTypeDef TIM_SlaveConfigStructure;
MOTORIC_TIM_CLK_ENABLE();
motoric_htimx_bldcm.Instance = MOTORIC_TIM;
motoric_htimx_bldcm.Init.Period = 100;
// TIMxCLK = HCLK=240MHz
// timer frequency=TIMxCLK/(TIM_Prescaler+1)=1MHz
motoric_htimx_bldcm.Init.Prescaler = MOTOR_ICPWM_PRESCALER_COUNT - 1;
motoric_htimx_bldcm.Init.ClockDivision=TIM_CLOCKDIVISION_DIV1;
motoric_htimx_bldcm.Init.CounterMode=TIM_COUNTERMODE_UP;
//motoric_htimx_bldcm.Init.RepetitionCounter=0;
HAL_TIM_IC_Init(&motoric_htimx_bldcm);
configure timer ic mode*
TIM_ICInitStructure.ICPolarity = TIM_ICPOLARITY_RISING;
TIM_ICInitStructure.ICSelection = TIM_ICSELECTION_DIRECTTI;
TIM_ICInitStructure.ICPrescaler = TIM_ICPSC_DIV1;
TIM_ICInitStructure.ICFilter = 0x0;
HAL_TIM_IC_ConfigChannel(&motoric_htimx_bldcm,&TIM_ICInitStructure,TIM_CHANNEL_1);
HAL_TIM_IC_ConfigChannel(&motoric_htimx_bldcm,&TIM_ICInitStructure,TIM_CHANNEL_2);
HAL_TIM_IC_ConfigChannel(&motoric_htimx_bldcm,&TIM_ICInitStructure,TIM_CHANNEL_3);
HAL_TIM_IC_ConfigChannel(&motoric_htimx_bldcm,&TIM_ICInitStructure,TIM_CHANNEL_4);
TIM_SlaveConfigStructure.SlaveMode = TIM_SLAVEMODE_RESET;
TIM_SlaveConfigStructure.InputTrigger = TIM_TS_TI1FP1;
HAL_TIM_SlaveConfigSynchronization(&motoric_htimx_bldcm,&TIM_SlaveConfigStructure);
//four channel capture
every channel use ic it mode,input frequency is about 1.5khz
HAL_TIM_IC_Start_IT(&motoric_htimx_bldcm,TIM_CHANNEL_1);
HAL_TIM_IC_Start_IT(&motoric_htimx_bldcm,TIM_CHANNEL_2);
HAL_TIM_IC_Start_IT(&motoric_htimx_bldcm,TIM_CHANNEL_3);
HAL_TIM_IC_Start_IT(&motoric_htimx_bldcm,TIM_CHANNEL_4);
}
just led,show the interrupt is ok
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if(htim->Instance == GENERAL_TIM)
{
LED1_TOGGLE;
}
}
void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{
//get capture value
if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_1)
{
LED1_TOGGLE;
IC1Value = HAL_TIM_ReadCapturedValue(&motoric_htimx_bldcm,TIM_CHANNEL_1);
IC2Value = HAL_TIM_ReadCapturedValue(&motoric_htimx_bldcm,TIM_CHANNEL_2);
if (IC1Value != 0)
{
//to count frequency
DutyCycle = (float)((IC2Value+1) * 100) / (IC1Value+1);
Frequency = 240000000/24000/(float)(IC1Value+1);
}
else
{
if not get ,zero
DutyCycle = 0;
Frequency = 0;
}
}
}
finally, this question is solved.
it's not about hal_init(),the reason is that:my pwm capture configuration is configured to slave mode,need to change to master mode .like this:
TIM_MasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
TIM_MasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
HAL_TIMEx_MasterConfigSynchronization(&motoric_htimx_bldcm, &TIM_MasterConfig);

STM32 UART DMA can receive first time correct then it receive nothing

I'm trying to use dma with uart in stm32f746 nucleo.
In receiving mode I can receive correct data in first use. When i try to receive again, receiving buffer doesn't change its initial values before receiving although I can get receive complete signal callback every time.
/* Main Loop */
while(1)
{
HAL_GPIO_TogglePin(LED_PORT,LED_GREEN); // Led Example
HAL_Delay(200);
pRxData[0]=5;
pRxData[1]=0;
// HAL_UART_Receive_IT(&UartHandle,pRxData,2);
if( HAL_UART_Receive_DMA(&UartHandle,pRxData,2)==HAL_OK); // UART-DMA-IT Example
{
while (UartReady != SET) // wait for msg len
{
HAL_GPIO_WritePin(LED_PORT,LED_GREEN,1);
HAL_Delay(20);
HAL_GPIO_WritePin(LED_PORT,LED_GREEN,0);
HAL_Delay(400);
}
UartReady = RESET; // reset transmition flag
LEN = pRxData[0]+pRxData[1]*256; // calc msg length
if ( LEN > 0 )
{
pTxData[0]= 25;//LEN; // ACK
//HAL_UART_Transmit_IT(&UartHandle,pTxData,1);
if(HAL_UART_Transmit_DMA(&UartHandle,pTxData,1)==HAL_OK);
{
while (UartReady != SET)
{
HAL_Delay(1);
}
UartReady = RESET;
if(HAL_UART_Receive_IT(&UartHandle,pRxData,LEN)==HAL_OK)
{
//HAL_UART_Receive_DMA(&UartHandle,pRxData,LEN);
while (UartReady != SET) // waiting loop for msg
{
HAL_GPIO_WritePin(LED_PORT,LED_GREEN,1);
HAL_Delay(300);
HAL_GPIO_WritePin(LED_PORT,LED_GREEN,0);
HAL_Delay(50);
}
UartReady = RESET;
if (MBU_StrCompareNC(pRxData,"LED_ON_BLUE",LEN)==0)
{
HAL_GPIO_WritePin(LED_PORT,LED_BLUE,1);
}
if (MBU_StrCompareNC(pRxData,"LED_OFF_BLUE",LEN)==0)
{
HAL_GPIO_WritePin(LED_PORT,LED_BLUE,0);
}
if (MBU_StrCompareNC(pRxData,"LED_ON_RED",LEN)==0)
{
HAL_GPIO_WritePin(LED_PORT,LED_RED,1);
}
if (MBU_StrCompareNC(pRxData,"LED_OFF_RED",LEN)==0)
{
HAL_GPIO_WritePin(LED_PORT,LED_RED,0);
}
}
HAL_UART_Abort(&UartHandle);
}
}
}
}
}

Why "HAL_I2C_Master_Transmit" writes 2 bytes of data in each loop

I'm using HAL library for stm32f4 (V1.7.1) and trying to understand how HAL_I2C_Master_Transmit works. This function transmits a "master to slave" packet on SDA line.
In the stm32f4xx_hal_i2c.c code after sending slave address there is a loop (while(hi2c->XferSize > 0U)) that sends bytes which we want to be transmitted to slave. This loop works until all bytes are transmitted. But there is a question that "why the function wants to transmit TWO bytes in each loop?" There is an IF in loop (if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U))) that checks if the previous byte is currently transferred then send the the next byte!
I don't know what is the reason of existing this IF when in the next loop other bytes can be transmitted?!
HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t
DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint32_t tickstart = 0x00U;
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
if(hi2c->State == HAL_I2C_STATE_READY)
{
/* Wait until BUSY flag is reset */
if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET,
I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK)
{
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
{
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
/* Disable Pos */
hi2c->Instance->CR1 &= ~I2C_CR1_POS;
hi2c->State = HAL_I2C_STATE_BUSY_TX;
hi2c->Mode = HAL_I2C_MODE_MASTER;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferSize = hi2c->XferCount;
/* Send Slave Address */
if(I2C_MasterRequestWrite(hi2c, DevAddress, Timeout, tickstart) != HAL_OK)
{
if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
{
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
}
else
{
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_TIMEOUT;
}
}
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
while(hi2c->XferSize > 0U)
{
/* Wait until TXE flag is set */
if(I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
{
if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
{
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
return HAL_ERROR;
}
else
{
return HAL_TIMEOUT;
}
}
/* Write data to DR */
hi2c->Instance->DR = (*hi2c->pBuffPtr++);
hi2c->XferCount--;
hi2c->XferSize--;
if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U))
{
/* Write data to DR */
hi2c->Instance->DR = (*hi2c->pBuffPtr++);
hi2c->XferCount--;
hi2c->XferSize--;
}
/* Wait until BTF flag is set */
if(I2C_WaitOnBTFFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
{
if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
{
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
return HAL_ERROR;
}
else
{
return HAL_TIMEOUT;
}
}
}
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
hi2c->State = HAL_I2C_STATE_READY;
hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}

Get Xbee response from Serial and send to a browser

I am trying to do some experiments with Arduino, Ethernet Shield and Xbee Shield.
I demonstrate my set up board like this:
Group 1: Arduino Uno + Xbee shield : broadcast the signal
Group 2: Arduino Uno + Xbee shield + Ethernet shield: receive the signal from
group 1, get the signal strength from AT command and print it into the browser.
The problem here is I can't get the result after sending to the Serial my ATDB command, actually, I am not sure it did worked as I expected.
Here is the code that I used to retrieve the signal strength.
int data;
void setup()
{
Serial.begin(9600);
}
void receiver_checker(){
delay(1200);
Serial.print("+++");
delay(1200);
bool bOK = false;
while (Serial.available() > 0) {
Serial.write(Serial.read());
bOK = true;
}
if(bOK)
{
Serial.println();
Serial.println("ATDB");
delay(100);
while (Serial.available() > 0) {
Serial.write(Serial.read());
}
Serial.println();
}
Serial.println();
}
void loop()
{
while(Serial.available() > 0){
data = Serial.read();
if(data == '1'){
// Broadcaster 1
//Serial.println("1------------------");
receiver_checker();
}
}
}
This part worked as I expected, it printed out in hex number the signal strength of the last package that it received.
Here is the code I combined the previous one and the server part from Web Server tutorial:
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xCA, 0xFE, 0x00, 0x00, 0x00, 0x02
};
IPAddress ip(1, 1, 1, 2);
int data;
int count = 0;
char result;
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
// Serial.print("server is at ");
// Serial.println(Ethernet.localIP());
}
void loop() {
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
// Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// Serial.write(c);
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close"); // the connection will be closed after completion of the response
client.println("Refresh: 5"); // refresh the page automatically every 5 sec
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
if (Serial.available() > 0) {
// read the oldest byte in the serial buffer:
data = Serial.read();
// if it's a capital H (ASCII 72), turn on the LED:
if (data == '1') {
count += 1;
client.print("The number of times:");
client.print(count);
result = receiver_checker();
client.print("========================");
client.print(result);
client.print("========================");
}
}
client.println("</html>");
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
Serial.println("client disconnected");
}
}
char receiver_checker(){
char signal;
delay(1200);
Serial.print("+++");
delay(1200);
bool bOK = false;
while (Serial.available() > 0) {
Serial.write(Serial.read());
bOK = true;
}
if(bOK)
{
Serial.println();
Serial.println("ATDB");
delay(100);
while (Serial.available() > 0) {
signal = Serial.read();
}
Serial.println();
}
Serial.println();
return signal;
}
If there is another way to interact with the Xbee shield not go through Serial like I ask and get response directly, please let me know!
Your receiver_checker() function is reading characters back from the XBee module, and just returning the last character received, which is likely a carriage return or line feed.
Update the function to return an int, and replace your while (Serial.available() > 0) with the following:
signal = (int) strtoul(Serial.readString().c_str(), 0, 16);
That's for when the XBee returns a hexadecimal value. If it's returning a decimal value, change the 16 parameter to a 10.