Unable to enter into a particular switch case - c

The first case of switch is to initialize the values, when i enter into the function the switch is not going to case INI_QUEUE, instead its going to CHECK_QUEUE or ENABLE_QUEUE.
below is my code and debug snippet.
can anyone please tell me, what is the problem which is making it not to go to INI_QUEUE
main.c file
int main(void)
{
/* USER CODE BEGIN 1 */
char buffer[2] = { 0 };
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART2_UART_Init();
MX_TIM14_Init();
/* USER CODE BEGIN 2 */
// HAL_TIM_Base_Start_IT(&htim14);
__HAL_UART_ENABLE_IT(&huart2,UART_IT_RXNE);
// HAL_UART_Receive_IT(&huart2, (uint8_t*) buffer, 1);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
// HAL_UART_Receive_IT(&huart2, (uint8_t*) buffer, 1);
fn_cirQ();
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
typedef enum{
INI_QUEUE, CHECK_COM, EN_QUEUE, DE_QUEUE, UART_SEND
}Qstate;
void init_queue(queues *q, int max_size){
q->size =max_size;
q->values = malloc(sizeof(int)*q->size);
q->num = 0;
q->front = 0;
q->rare = 0;
}
void fn_cirQ()
{
queues q1;
static Qstate queuestates = INI_QUEUE;
switch (queuestates)
{
case INI_QUEUE:
init_queue(&q1, SIZE);
queuestates = CHECK_COM;
break;
case CHECK_COM:
if(Q_state == 0xFF)
{
queuestates = EN_QUEUE;
}
else if(Q_state == 0x00)
{
queuestates = DE_QUEUE;
}
else if(Q_state != 0x55)
{
HAL_UART_Transmit_IT(&huart2, (uint8_t*) errormsg, 20);
}
break;
case EN_QUEUE:
en_queue(&q1, temp[1]);
Q_state = 0x55;
j = 0;
queuestates = UART_SEND;
break;
case DE_QUEUE:
dequeue(&q1);
Q_state = 0x55;
j=0;
queuestates = UART_SEND;
break;
case UART_SEND:
HAL_UART_Transmit_IT(&huart2, (uint8_t*)&q1, sizeof(q1));
queuestates = CHECK_COM;
break;
}
}
[debug window,queuestates is assigned with CHECK_COM state instead of INI_QUEUE]

The initialization of a static variable is only done once, at program start-up. So the first time the function is called, it will go to the INI_QUEUE case.
From there on, any next time the function is called it will go the queue state set by the previous call.
But the first time it will go to INI_QUEUE.

Related

How do I copy values from one integer array into another integer array using only the keyboard to fill them?

I am trying to store values received from a non-blocking UART protocol. I enter characters from my keyboard and they are stored in an array called buffer that holds the value. I then want to fill a new array called newbuffer using the value from buffer array and then clear the value in buffer array so it is ready to receive another value from the keyboard.
Here is my initialization:
uint8_t buffer[2] = {0}; //initialize array for receiving keyboard input
uint8_t newbuffer[256] = {0}; //initialize array to store keyboard input from buffer array
int i = 0; //array index variable
UartHandle.Instance = USARTx;
UartHandle.Init.BaudRate = 9600;
UartHandle.Init.WordLength = UART_WORDLENGTH_9B;
UartHandle.Init.StopBits = UART_STOPBITS_1;
UartHandle.Init.Parity = UART_PARITY_EVEN;
UartHandle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
UartHandle.Init.Mode = UART_MODE_TX_RX;
UartHandle.Init.OverSampling = UART_OVERSAMPLING_16;
Here is the callback routine after I have entered my first character. I could really use some help with this part!!!
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
//Prevent unused argument(s) compilation warning
UNUSED(huart);
for (i = 0; i < sizeof(newbuffer); i++)
{
newbuffer[i] = buffer[0]; //put value entered from keyboard into newbuffer array
memset(buffer, 0, sizeof(buffer)); //clear buffer array for next value
HAL_UART_Receive_IT (&UartHandle, buffer, 1); //call interrupt that handles entering keyboard values
}
printf("%d", newbuffer);
}
This is the interrupt function for getting keyboard values, in case you need to see that.
static HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart)
{
uint16_t *tmp;
/* Check that a Rx process is ongoing */
if (huart->RxState == HAL_UART_STATE_BUSY_RX)
{
if (huart->Init.WordLength == UART_WORDLENGTH_9B)
{
tmp = (uint16_t *) huart->pRxBuffPtr;
if (huart->Init.Parity == UART_PARITY_NONE)
{
*tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x01FF);
huart->pRxBuffPtr += 2U;
}
else
{
*tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x00FF);
huart->pRxBuffPtr += 1U;
}
}
else
{
if (huart->Init.Parity == UART_PARITY_NONE)
{
*huart->pRxBuffPtr++ = (uint8_t)(huart->Instance->DR & (uint8_t)0x00FF);
}
else
{
*huart->pRxBuffPtr++ = (uint8_t)(huart->Instance->DR & (uint8_t)0x007F);
}
}
if (--huart->RxXferCount == 0U)
{
/* Disable the UART Data Register not empty Interrupt */
__HAL_UART_DISABLE_IT(huart, UART_IT_RXNE);
/* Disable the UART Parity Error Interrupt */
__HAL_UART_DISABLE_IT(huart, UART_IT_PE);
/* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */
__HAL_UART_DISABLE_IT(huart, UART_IT_ERR);
/* Rx process is completed, restore huart->RxState to Ready */
huart->RxState = HAL_UART_STATE_READY;
#if (USE_HAL_UART_REGISTER_CALLBACKS == 1)
/*Call registered Rx complete callback*/
huart->RxCpltCallback(huart);
#else
/*Call legacy weak Rx complete callback*/
HAL_UART_RxCpltCallback(huart);
#endif /* USE_HAL_UART_REGISTER_CALLBACKS */
return HAL_OK;
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
THANKS IN ADVANCE :)
Have you realized that you are copying exactly 1 byte in the for loop inside HAL_UART_RxCpltCallback, whereas array buffer is two bytes in size ?
This sentence: newbuffer[i] = buffer[0]; is just copying the first byte.
If you are reading from the keyboard you are probably getting scan codes. Scan codes are not all one byte, but many of them. Depending on the keys they can be up to three bytes: https://en.wikipedia.org/wiki/Scancode.
I solved the problem. The issue was with having the logic in a for loop. Since the size of newbuffer is 256, the program would not exit the for loop unless all of the characters had been entered and newbuffer was full. By taking my logic out of the for loop, the function could complete and return to main to be recalled in the main loop when the next character was entered.
I also added a flag variable so that I can print the string that was entered when the user types the carriage return button.
Receive Callback Routine:
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
//Prevent unused argument(s) compilation warning
UNUSED(huart);
newbuffer[i] = buffer[0] //put value entered from keyboard into newbuffer array
if (newbuffer[i] == '\r') //if user enters a carriage return the input will be flagged and trigger the while loop to print the string
{
flag = 1;
}
else
{
flag = 0;
}
memset(buffer, 0, sizeof(buffer)); //clear buffer array to receive next keyboard value
i++; //increment newbuffer index
HAL_UART_Receive_IT (&UartHandle, buffer, 1); //call interrupt that handles entering keyboard values
Main:
int main(void)
{
HAL_Init();
/* Configure the system clock to 180 MHz */
SystemClock_Config();
/* Initialize BSP Led for LED2 */
BSP_LED_Init(LED2);
UartHandle.Instance = USARTx;
UartHandle.Init.BaudRate = 9600;
UartHandle.Init.WordLength = UART_WORDLENGTH_9B;
UartHandle.Init.StopBits = UART_STOPBITS_1;
UartHandle.Init.Parity = UART_PARITY_EVEN;
UartHandle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
UartHandle.Init.Mode = UART_MODE_TX_RX;
UartHandle.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&UartHandle) != HAL_OK)
{
/* Initialization Error */
Error_Handler();
}
NVIC_SetPriority(USART3_IRQn, (1u << __NVIC_PRIO_BITS) - 5u); //set interrupt priority
NVIC_EnableIRQ(USART3_IRQn);
/*INTERRUPT METHOD*/
HAL_UART_Receive_IT (&UartHandle, buffer, 1); //call UART receive interrupt to get keyboard input
//Infinite loop
while (1)
{
//output a message in Hyperterminal requesting keyboard input
printf("\n\rEnter your string: ");
NVIC_DisableIRQ(USART3_IRQn);
if (flag == 1)
{
printf("%s", newbuffer); //string is printed if user enters a carriage return
flag = 0; //reset flag so the interrupt routine can look for another carriage return
memset(newbuffer, 0, sizeof(newbuffer)); //clear newbuffer so it is ready to store a new string
i = 0; //reset index so newbuffer begins storing its new string starting at newbuffer[0]
}
NVIC_EnableIRQ(USART3_IRQn);
HAL_Delay (1000);
}

CAN bus receiver don't receive

I am working with a PIC32MX795F512L. With below code I can transmit but cannot receive. How can it be possible I can transmit but I cannot receive? Any suggestions will be appreciated.
Here is the init code:
void CAN1Init(void) {
CAN_BIT_CONFIG canBitConfig;
UINT baudPrescalar;
PORTSetPinsDigitalIn(IOPORT_F, BIT_0);
PORTSetPinsDigitalOut(IOPORT_F, BIT_1);
// ODCFSET = BIT_1;
// change the CAN1 RX register from anlog to digital
// PORTSetPinsDigitalIn(IOPORT_F, BIT_0);
// PORTSetPinsDigitalOut(IOPORT_F, BIT_1);
CANEnableModule(CAN1, TRUE);
// Set the CAN_en pin to low, which is at RC3
mPORTCClearBits(BIT_3);
PORTSetPinsDigitalOut(IOPORT_C, BIT_3);
CANSetOperatingMode(CAN1, CAN_CONFIGURATION);
while (CANGetOperatingMode(CAN1) != CAN_CONFIGURATION);
canBitConfig.phaseSeg2Tq = CAN_BIT_3TQ;
canBitConfig.phaseSeg1Tq = CAN_BIT_3TQ;
canBitConfig.propagationSegTq = CAN_BIT_3TQ;
canBitConfig.phaseSeg2TimeSelect = TRUE;
canBitConfig.sample3Time = TRUE;
canBitConfig.syncJumpWidth = CAN_BIT_2TQ;
// baudPrescalar = CANCalcBitClockPrescalar(&canBitConfig,80000000,250000);
CANSetSpeed(CAN1, & canBitConfig, SYS_FREQ, CAN_BUS_SPEED);
/* Step 3: Assign the buffer area to the
* CAN module.
*/
CANAssignMemoryBuffer(CAN1, CAN1MessageFifoArea, (2 * 8 * 16));
CANConfigureChannelForTx(CAN1, CAN_CHANNEL0, 8, CAN_TX_RTR_DISABLED, CAN_LOW_MEDIUM_PRIORITY);
CANConfigureChannelForRx(CAN1, CAN_CHANNEL1, 8, CAN_RX_FULL_RECEIVE);
//CANConfigureFilter (CAN1, CAN_FILTER0, 0x000, CAN_SID);
//CANConfigureFilterMask (CAN1, CAN_FILTER_MASK0, 0x7FF, CAN_SID, CAN_FILTER_MASK_IDE_TYPE);
// CANLinkFilterToChannel (CAN1, CAN_FILTER0, CAN_FILTER_MASK0, CAN_CHANNEL1);
// CANEnableFilter (CAN1, CAN_FILTER0, TRUE);
CANEnableChannelEvent(CAN1, CAN_CHANNEL1, CAN_RX_CHANNEL_NOT_EMPTY, TRUE);
CANEnableModuleEvent(CAN1, CAN_RX_EVENT, TRUE);
INTSetVectorPriority(INT_CAN_1_VECTOR, INT_PRIORITY_LEVEL_4);
INTSetVectorSubPriority(INT_CAN_1_VECTOR, INT_SUB_PRIORITY_LEVEL_0);
INTEnable(INT_CAN1, INT_ENABLED);
/* Step 7: Switch the CAN mode
* to normal mode. */
CANSetOperatingMode(CAN1, CAN_NORMAL_OPERATION);
mPORTEToggleBits(BIT_6 | BIT_7);
while (CANGetOperatingMode(CAN1) != CAN_NORMAL_OPERATION);
CANSetTimeStampValue(CAN1, 0x00);
printf("CAN BUS is working\n");
}
Edit: main part of the code:
void RxMsgProcess(void)
{
if(isCAN1MsgReceived == FALSE) // This flag to make sure there is an interrupt from receiving a new message, if it's true then there are new packet
{
return;
}
isCAN1MsgReceived = FALSE;
CANRxMessageBuffer * message2;
message2 = CANGetRxMessage(CAN1,CAN_CHANNEL1);
printf(" received\n");
CANUpdateChannel(CAN1, CAN_CHANNEL1);
CANEnableChannelEvent(CAN1, CAN_CHANNEL1, CAN_RX_CHANNEL_NOT_EMPTY, TRUE);
}
void __attribute__((vector(46), interrupt(ipl4), nomips16)) CAN1InterruptHandler(void)
{
/* Check if the source of the interrupt is
* RX_EVENT. This is redundant since only this
* event is enabled in this example but
* this shows one scheme for handling events. */
if((CANGetModuleEvent(CAN1) & CAN_RX_EVENT) != 0)
{
/* Within this, you can check which channel caused the
* event by using the CANGetModuleEvent() function
* which returns a code representing the highest priority
* pending event. */
if(CANGetPendingEventCode(CAN1) == CAN_CHANNEL1_EVENT)
{
CANEnableChannelEvent(CAN1, CAN_CHANNEL1, CAN_RX_CHANNEL_NOT_EMPTY, FALSE);
isCAN1MsgReceived = TRUE;
}
}
INTClearFlag(INT_CAN1);
}

Global variable being reset after each call

In my project I'm using a global variable but it's not working as expected because it is initialized everytime it's executed and honestly I don't know what could be going on.
The variable is cookingSignalReceived.
The program is structured as follows:
//File Controller.c:
while (1)
{
Controller_Run_State_Machine();
}
void Controller_Run_State_Machine(void)
{
/* start of activity code */
Inputs_ReadSensors();
Comms_CheckReceivedData();
Controller_UpdateSTM();
}
The problem is inside Comms file:
//File Comms.c
uint8_t cookingSignalReceived = 0;
void Comms_CheckReceivedData(void)
{
/* start of activity code */
uint8_t uartDataAvailable = Comms_R_UART0_checkIfDataAvailable();
if (uartDataAvailable == 1)
{
Comms_ParseReceivedCommand();
}
}
void Comms_ParseReceivedCommand(void)
{
/* start of activity code */
/* UserCode{499E2AA6-1F61-4753-9221-77F85E7B5D92}:YjMeKqu95e */
uint8_t CRC_check_OK = 0;
uint8_t* buffer;
/* UserCode{499E2AA6-1F61-4753-9221-77F85E7B5D92} */
Comms_R_UART0_resetFlag_dataAvailable();
buffer = Comms_R_UART0_getBuffer();
CRC_check_OK = Comms_crcCheck(buffer);
if (CRC_check_OK == 1)
{
Comms_processMessage(buffer); //<-- Variable is used in this function
}
}
Global variable is used inside Comms_processMessage(). The issue is that every time that the function is called, the global variable is set to the initial value. Do you find anything strange here?
EDITED:
void Comms_processMessage(uint8_t* buffer)
{
/* UserCode{BCB3B791-2DF9-492b-B53B-6FEB24BD8F77}:eyCoSfmCKb */
uint8_t message = buffer[0];
uint8_t param1 = buffer[1];
uint8_t param2 = buffer[2];
//---------------------------------------------------------------------
// START COOKING 1ST STEP REQUEST
//---------------------------------------------------------------------
if (message == MSG_COOK_1ST && param1 == START_PARAM)
{
// Wait for second frame
cookingSignalReceived = 1;
#ifdef DEBUG
R_UART0_Send("Cook 1st step!!", sizeof(char) * 15);
#endif
}
//---------------------------------------------------------------------
// START COOKING 2ND STEP REQUEST
//---------------------------------------------------------------------
else if (message == MSG_COOK_2ND && param1 == START_PARAM)
{
// Wait for second frame
if (cookingSignalReceived == 1)
{
Controller_signalsBufferEnqueue(cookingSignal);
}
#ifdef DEBUG
R_UART0_Send("Cook 2nd step!!", sizeof(char) * 15);
#endif
}
}
Note that my original idea was to use a local static variable but I was having the same issue so I tried with a global variable.
In certain cases the MCUs restart because unrecoverable errors or bad hardware settings. This should be the problem! A cause of this MCUs behaviour may be also bad pointers management.

pic32mx230 spi numbers of bytes

This one below i make new code for pic32mx230 SPI module harmony design i need to send 96 bytes
register values and every 3 bytes starting CS will Low to High can anyone help
us where i am wrong?
`APP_DATA appData;
static uint8_t __attribute__ ((aligned (8))) app_spi_tx_buffer[128] =0xD4,0x1E,
0x00
0xD4,0x1D,0x80,\
0xD4,0x1C,0x09,\
0xD4,0x1B,0x00,\
0xD4,0x1A,0x00,\
0xD4,0x19,0x64,\
0xD4,0x18,0x18,\
0xD4,0x17,0x00,\
0xD4,0x16,0x80,\
0xD4,0x15,0x00,\
0xD4,0x14,0x00,\
0xD4,0x13,0x00,\
0xD4,0x12,0x00,\
0xD4,0x11,0x00,\
0xD4,0x10,0x00,\
0xD4,0x0F,0x00,\
0xD4,0x0E,0x80,\
0xD4,0x0D,0xE8,\
0xD4,0x0C,0x18,\
0xD4,0x0B,0x00,\
0xD4,0x0A,0x01,\
0xD4,0x09,0xF0,\
0xD4,0x08,0x00,\
0xD4,0x07,0x00,\
0xD4,0x06,0x53,\
0xD4,0x05,0x00,\
0xD4,0x04,0x01,\
0xD4,0x03,0x04,\
0xD4,0x02,0xAA,\
0xD4,0x01,0xAA,\
0xD4,0x00,0xAB,\
0xD4,0x1B,0x00,\
0xD4,0x1D,0x81};
void Modulator_SPI_Enable ( void )
{
MOD_SPI_CS_SELECT(SPI_SLAVE_1_CS_PORT_ID,SPI_SLAVE_1_CS_PORT_PIN); //start clock from here
TIME_DelayUs(1);
MOD_SPI_CS_DESELECT(SPI_SLAVE_1_CS_PORT_ID,SPI_SLAVE_1_CS_PORT_PIN);
TIME_DelayUs(1);
MOD_SPI_CS_SELECT(SPI_SLAVE_1_CS_PORT_ID,SPI_SLAVE_1_CS_PORT_PIN); //start clock from here
TIME_DelayUs(1);
MOD_SPI_CS_DESELECT(SPI_SLAVE_1_CS_PORT_ID,SPI_SLAVE_1_CS_PORT_PIN);
TIME_DelayUs(1);
MOD_SPI_CS_SELECT(SPI_SLAVE_1_CS_PORT_ID,SPI_SLAVE_1_CS_PORT_PIN);
TIME_DelayUs(1);
MOD_SPI_CS_DESELECT(SPI_SLAVE_1_CS_PORT_ID,SPI_SLAVE_1_CS_PORT_PIN);
TIME_DelayUs(1);
MOD_SPI_CS_SELECT(SPI_SLAVE_1_CS_PORT_ID,SPI_SLAVE_1_CS_PORT_PIN);
TIME_DelayUs(1);
MOD_SPI_CS_DESELECT(SPI_SLAVE_1_CS_PORT_ID,SPI_SLAVE_1_CS_PORT_PIN);
TIME_DelayUs(1);
TIME_DelayMs(20);
}
/* state machine for the SPI */
static void SPI_Task(void)
{
unsigned char i;
/* run the state machine here for SPI */
switch (appData.spiStateMachine)
{
default:
case APP_SPI_STATE_START:
/* set the state to 'wait' early so that the interrupt doesn't
finish fast and write the state and then is overwritten */
appData.spiStateMachine = APP_SPI_STATE_WAIT;
MOD_SPI_CS_DESELECT(SPI_SLAVE_1_CS_PORT_ID,SPI_SLAVE_1_CS_PORT_PIN); //start clock from here
for (i=0; i<3; i++)
{
app_spi_tx_buffer[i];
MOD_SPI_CS_SELECT(SPI_SLAVE_1_CS_PORT_ID,SPI_SLAVE_1_CS_PORT_PIN);
}
appData.drvSPIBufferHandle = DRV_SPI_BufferAddWrite(appData.handleSPI0,
app_spi_tx_buffer, sizeof(app_spi_tx_buffer),
0, 0);
if (DRV_SPI_BUFFER_HANDLE_INVALID == appData.drvSPIBufferHandle)
{
/* try again if we get a bad handle */
appData.spiStateMachine = APP_SPI_STATE_START;
}
break;
case APP_SPI_STATE_WAIT:
{
if ( DRV_SPI_BufferStatus(appData.drvSPIBufferHandle) & DRV_SPI_BUFFER_EVENT_COMPLETE)
{
appData.spiStateMachine = APP_SPI_STATE_DONE;
}
}
break;
case APP_SPI_STATE_DONE:
break;
}
}
void APP_Initialize ( void )
{
/* Place the App state machine in its initial state. */
appData.state = APP_STATE_INIT;
Modulator_SPI_Enable();
MOD_SPI_CS_DESELECT(SPI_SLAVE_2_CS_PORT_ID,SPI_SLAVE_2_CS_PORT_PIN);
TXDIS_DSELECT();
MOD_SPI_CS_SELECT(SPI_SLAVE_1_CS_PORT_ID,SPI_SLAVE_1_CS_PORT_PIN); // CS will be low
appData.handleSPI0 = DRV_HANDLE_INVALID;
/* TODO: Initialize your application's state machine and other
* parameters.
*/
}
void APP_Tasks ( void )
{
/* Check the application's current state. */
switch ( appData.state )
{
/* Application's initial state. */
case APP_STATE_INIT:
{
bool appInitialized = true;
if (DRV_HANDLE_INVALID == appData.handleSPI0)
{
appData.handleSPI0 = DRV_SPI_Open(0, DRV_IO_INTENT_WRITE);
appInitialized &= (DRV_HANDLE_INVALID != appData.handleSPI0);
}
if (appInitialized)
{
/* initialize the SPI state machine */
appData.spiStateMachine = APP_SPI_STATE_START;
appData.state = APP_STATE_SERVICE_TASKS;
}
break;
}
case APP_STATE_SERVICE_TASKS:
{
/* run the state machine for servicing the SPI */
SPI_Task();
break;
}
/* TODO: implement your application state machine.*/
/* The default state should never be executed. */
default:
{
/* TODO: Handle error in application's state machine. */
break;
}
}
}
Thanks
Nome
Sometimes the best answer is the simplest:
unsigned char buff={0xD4,0x04,0x03,0x02,0x01,0x1E};
unsigned char i;
SPI1CON = 0x8020; // SPI on and SPI Master see 61106G.pdf PIC32 FRM
for(i = 0; i < 6; i++)
{
/* CS = HIGH */
SPI1BUF=buff[i];
while(SPI1STATbits.SPIBUSY);
// read the SDI line
unsigned char x = SPI1BUF;
/* CS = LOW */
}
You'll need to choose the right SPIXCON for the SPI bus you are attached to in your schematic.
EDIT:
I will not do you project for you, here is my example with a bit more example code.
unsigned char buff[128]={0xD4,0x04,0x03,0x02,0x01,0x1E.....};
unsigned char i;
SPI1CON = 0x8020; // SPI on and SPI Master see 61106G.pdf PIC32 FRM
unsigned char j = 0;
for(i = 0; i < 128; i++)
{
/* CS = HIGH */
if (j == 0)
MOD_SPI_CS_DESELECT(SPI_SLAVE_1_CS_PORT_ID,SPI_SLAVE_1_CS_PORT_PIN);
SPI1BUF=buff[i];
while(SPI1STATbits.SPIBUSY);
// read the SDI line
unsigned char x = SPI1BUF;
if ( j == 2)
{
j = 0;
MOD_SPI_CS_SELECT(SPI_SLAVE_1_CS_PORT_ID,SPI_SLAVE_1_CS_PORT_PIN);
}
else
j++;
/* CS = LOW */
}

Bluetooth communications with C

I want to write 2 programs with C , one work on Robot1, the other work on Robot2.
So I want the program to send a signal from Robot1 via Bluetooth to Robot2 and Robot2 handles and accepts this signal (message)and reply to Robot1.
how to code this?
please I need any kind of help.
API OF my Robots:
/* function for serial communication */
void SerWrite(unsigned char *data,unsigned char length)
{
unsigned char i = 0;
UCSRB = 0x08; // enable transmitter
while (length > 0) {
if (UCSRA & 0x20) { // wait for empty transmit buffer
UDR = data[i++];
length --;
}
}
while (!(UCSRA & 0x40));
for (i = 0; i < 0xFE; i++)
for(length = 0; length < 0xFE; length++);
}
void SerRead(unsigned char *data, unsigned char length,unsigned int timeout)
{
unsigned char i = 0;
unsigned int time = 0;
UCSRB = 0x10; // enable receiver
/* non blocking */
if (timeout != 0) {
while (i < length && time++ < timeout) {
if (UCSRA & 0x80) {
data[i++] = UDR;
time = 0;
}
}
if (time > timeout) data[0] = 'T';
}
/* blocking */
else {
while (i < length) {
if (UCSRA & 0x80)
data[i++] = UDR;
}
}
}
-------------------------------------------------------------------------------------------Bluetooth Model...code...
#include "asuro.h"
void Sekunden(unsigned int s) //Unterprogramm für Sekundenschleife (maximal 65s)
{
unsigned int t; // Definierung t als Vorzeichenloses int
for(t=0;t<s*1000;t++) // 1000*s durchlaufen
{
Sleep(72); // = 1ms
}
}
int main (void)
{
unsigned char daten[2], merker=0; //Speicher bereitstellen, merker für start/stop
Init();
UBRRL = 0x67; //4800bps # 8MHz
Marke: // Endlosschleife
SerRead(daten,1,0); // Daten einlesen
switch (daten[0]) //und verarbeiten
{
case 0x38: MotorDir(FWD,FWD); // Vorwärts
MotorSpeed(merker*120,merker*120);
SerWrite("Vor \r",22);
break;
case 0x36: MotorDir(FWD,FWD); // Links
MotorSpeed(merker*120,merker*170);
SerWrite("Links \r",22);
break;
case 0x37: MotorDir(RWD,RWD); // Rückwärts
MotorSpeed(merker*120,merker*120);
SerWrite("Zurueck \r",22);
break;
case 0x34: MotorDir(FWD,FWD); // Rechts
MotorSpeed(merker*170,merker*120);
SerWrite("Rechts \r",22);
break;
case 0x35: if(merker==1)
{
MotorDir(FREE,FREE);// Stop
MotorSpeed(0,0);
SerWrite("Stop \r",22);
merker=0;
break;
}
else
{
MotorDir(FWD,FWD);// Start
MotorSpeed(120,120);
SerWrite("Start \r",22);
merker=1;
break;
}
}
i want to run this programm on my Robot.
Robot 2 needs to call SerRead with, lets say, a pointer to an empty buffer (length one or so), length one and zero as timeout. Afterwards, let it call SerWrite with a pointer to your buffer and length one.
Robot 1 should first call SerWrite with one byte of data and then wait for the result of a call to SerRead.

Resources