what does mean by __even_in_range(UCA0IV,0x08) - interrupt-handling

I found this part from the example code for UART for MSP430FR57xx from TI.
I don't understand what __even_in_range(UCA0IV,0x08) does mean?
#pragma vector=USCI_A0_VECTOR
__interrupt void USCI_A0_ISR(void)
{
switch(__even_in_range(UCA0IV,0x08))
{
case 0:break; // Vector 0 - no interrupt
case 2: // Vector 2 - RXIFG
while (!(UCA0IFG&UCTXIFG)); // USCI_A0 TX buffer ready?
UCA0TXBUF = UCA0RXBUF; // TX -> RXed character
break;
case 4:break; // Vector 4 - TXIFG
default: break;
}
}

The interrupt vector register never has a value that is odd, or larger than eight. So if you tell the compiler about this, it is possible to generate slightly more efficient code by leaving out the checks for those values, and by implementing the cases with a simple jump table.

Related

How to optimize the code for reading SPI through ARDUINO in SLAVE mode

Not important:
I am doing a project to integrate a bluetooth module into a car radio pioneer. I understand perfectly well that it's easier to buy a new one =) but it's not interesting. At the moment, the byproduct was an adapter on arduino of resistor buttons, which the pioneer did not understand. The same adapter also controls the bluetooth board, it can switch the track forward and backward (there is no button on the steering wheel for pause). Now I want the bluetooth to turn on only in AUX mode. But there is a problem, which mode can be understood only by reading the signal from the SPI bus of the commutation microcircuit. I was able to read this data using arduino nano. I do not have an analyzer, but it is not necessary that I would understand something additional with it.
Essence of the question:
Using the scientific poke method, I found sequences indicating the launch of a particular mode, for example:
10110011
1
111
1000000
I'm sure I'm doing it wrong, but in the meantime I get duplicate results. But, when I try to detect them using IF, the nano speed is not enough and the chip starts to pass data.
#include "SPI.h"
bool flag01, flag02, flag03, flag11, flag12, flag13, flag31, flag32, flag33;
void setup (void)
{
Serial.begin(9600);
pinMode(MISO, OUTPUT);
SPCR |= _BV(SPE);
SPI.attachInterrupt();
}
// Вызываем функцию обработки прерываний по вектору SPI
// STC - Serial Transfer Comlete
ISR(SPI_STC_vect)
{
// Получаем байт из регистра данных SPI
byte c = SPDR;
Serial.println(c, BIN);
if (c == 0b1) {
Serial.println("1 ok");
flag11 = true;
} else {
flag11 = false;
}
if (c == 0b11 && flag11) {
Serial.println("11 ok");
flag12 = true;
} else {
flag12 = false;
flag11 = false;
}
if (c == 0b1100000 && flag11 && flag12) {
Serial.println("1100000 ok");
flag13 = true;
} else {
flag13 = false;
flag12 = false;
flag11 = false;
}
}
void loop(void)
{}
I myself am scared to look at this code, but I cannot think of anything better. It seems like I heard about some kind of buffer, but I don't know how to screw it to this solution. After all, the data packets go with dropping the CS signal and I can’t figure out how to determine the beginning and end of the packet from the commands in order to write it to a buffer or array and only then go through it with a comparison.
I will be grateful if someone will tell me at least in which direction to move.
There is also esp8266, but there is a limitation on the size of a data packet of 32 bits in a slave mode and I do not know how to get around it correctly.
So, actually the question.
How can I optimize the code so that the arduino has time to process the data and I can catch the pattern?
Perhaps, if we implement reading of data of arbitrary length on esp8266, or at least fill them to the required length, it would help me. But I still can't figure it out with the spi.slave library.
First you should keep your ISR as short as possible, certainly don't use Serial print inside the ISR.
Secondly, if you don't know exactly how long the data is, then you need to have a buffer to capture the data and try to determine the data length first before you trying to analysis it.
volatile uint8_t byteCount = 0;
volatile bool dataReady = false;
byte data[32];
// SPI interrupt routine
ISR (SPI_STC_vect)
{
data[byteCount++] = SPDR;
dataReady = true;
}
void setup (void)
{
// your SPI and Serial setup code
}
void loop (void)
{
// for determine the data stream length
if (dataReady) {
Serial.println(byteCount);
dataReady = false;
}
}
Once you know how long the data stream is (let assumed it is 15-byte long), you can then change your sketch slightly to capture the data and analysis it.
volatile uint8_t byteCount = 0;
volatile bool dataReady = false;
byte data[32];
// SPI interrupt routine
ISR (SPI_STC_vect)
{
data[byteCount++] = SPDR;
if (byteCount == 15)
dataReady = true;
}
void loop (void)
{
if (dataReady) {
dataReady = false;
// do your analysis here
}
}

Print Oxygen Saturation with Arduino

#include <Wire.h>
#include "MAX30100_PulseOximeter.h"
#define REPORTING_PERIOD_MS 1000
// PulseOximeter is the higher level interface to the sensor
// it offers:
// * beat detection reporting
// * heart rate calculation
// * SpO2 (oxidation level) calculation
PulseOximeter pox;
uint32_t tsLastReport = 0;
// Callback (registered below) fired when a pulse is detected
void onBeatDetected()
{
Serial.println("Beat!");
}
void setup()
{
Serial.begin(115200);
Serial.print("Initializing pulse oximeter..");
// Initialize the PulseOximeter instance
// Failures are generally due to an improper I2C wiring, missing power supply
// or wrong target chip
if (!pox.begin()) {
Serial.println("FAILED");
for(;;);
} else {
Serial.println("SUCCESS");
}
// The default current for the IR LED is 50mA and it could be changed
// by uncommenting the following line. Check MAX30100_Registers.h for all the
// available options.
// pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA);
// Register a callback for the beat detection
pox.setOnBeatDetectedCallback(onBeatDetected);
}
void loop()
{
// Make sure to call update as fast as possible
pox.update();
// Asynchronously dump heart rate and oxidation levels to the serial
// For both, a value of 0 means "invalid"
if (millis() - tsLastReport > REPORTING_PERIOD_MS) {
Serial.print("Heart rate:");
Serial.print(pox.getHeartRate());
Serial.print("bpm / SpO2:");
Serial.print(pox.getSpO2());
Serial.println("%");
tsLastReport = millis();
}
}
I want to output oxygen saturation with Arduino.
If you run it and turn on the serial monitor, only the Initializing pulse oximeter works, and no data is transmitted after that.
I want to output the values ​​of oxygen saturation and pulse received from the sensor once per second on the serial monitor.

Interrupt / Stack Pointers / PIC Microcontroller

I am currently working with the PIC16F1829 micro controller. However, I am stuck on interrupt routine appropriate execution method. I want the interrupt routine to exit out of the infinite loop in all of the functions (LED animations), that are listed as different switch cases in the main() superloop. Should I use a global variable that the function would check and change it after interrupt flag has been detected or can I just use the stack pointers for this purpose? I have currently the ISR written using the stack pointer manipulation, but could you please let me know if this is the good approach?
void interrupt ISR(void){
if (TMR0IF && TMR0IE){ // (16MHz / (4 * 16 * 256)) [ 1.024 ms ]
TMR0IF = 0; // Clear Overflow Flag
if (++counter > 4531){ // 19531 * 1.024 ms [ ~ 20 sec ]
LED_Animation++; // Change the animation at a fixed time interval
counter = 0;
while (STKPTR > 1){ // STKPTR incremented due to an Interrupt
TOSH = 0; // TOSH:TOSL points to the Top of a Stack [ 0x00 ]
TOSL = 0;
STKPTR--; // Current value of the Stack Pointer
}
}
}
}
void main(){
STKPTR++; // Save this location in the stack
Sys_Init();
while(1){
switch(LED_Animation) {
case 0: LED_LizzardFeed(); break;
case 1: LED_Paparazzi(); break;
case 2: LED_FillnClear(); break;
case 3: LED_Slide(); break;
case 4: LED_MeetUp(); break;
case 5: LED_Chaser(); break;
default: LED_Animation = 0;
}
}
Your implementation using stack frame manipulation does not work on a PIC16F1829. These controllers use a separate memory space for the call stack.
To implement what you have suggested would require saving a copy of the 32-level call stack to the general RAM memory and restoring a copy of the 32-level call stack for the next routine in the animations list. This is possible be seems a bit too inefficient.
Please study the concept of protothreads, the are a useful method to achieve concurrent behavior in a resource limited controllers on a single execution thread.

Write UART on PIC18

I need help with the uart communication I am trying to implement on my Proteus simulation. I use a PIC18f4520 and I want to display on the virtual terminal the values that have been calculated by the microcontroller.
Here a snap of my design on Proteus
Right now, this is how my UART code looks like :
#define _XTAL_FREQ 20000000
#define _BAUDRATE 9600
void Configuration_ISR(void) {
IPR1bits.TMR1IP = 1; // TMR1 Overflow Interrupt Priority - High
PIE1bits.TMR1IE = 1; // TMR1 Overflow Interrupt Enable
PIR1bits.TMR1IF = 0; // TMR1 Overflow Interrupt Flag
// 0 = TMR1 register did not overflow
// 1 = TMR1 register overflowed (must be cleared in software)
RCONbits.IPEN = 1; // Interrupt Priority High level
INTCONbits.PEIE = 1; // Enables all low-priority peripheral interrupts
//INTCONbits.GIE = 1; // Enables all high-priority interrupts
}
void Configuration_UART(void) {
TRISCbits.TRISC6 = 0;
TRISCbits.TRISC7 = 1;
SPBRG = ((_XTAL_FREQ/16)/_BAUDRATE)-1;
//RCSTA REG
RCSTAbits.SPEN = 1; // enable serial port pins
RCSTAbits.RX9 = 0;
//TXSTA REG
TXSTAbits.BRGH = 1; // fast baudrate
TXSTAbits.SYNC = 0; // asynchronous
TXSTAbits.TX9 = 0; // 8-bit transmission
TXSTAbits.TXEN = 1; // enble transmitter
}
void WriteByte_UART(unsigned char ch) {
while(!PIR1bits.TXIF); // Wait for TXIF flag Set which indicates
// TXREG register is empty
TXREG = ch; // Transmitt data to UART
}
void WriteString_UART(char *data) {
while(*data){
WriteByte_UART(*data++);
}
}
unsigned char ReceiveByte_UART(void) {
if(RCSTAbits.OERR) {
RCSTAbits.CREN = 0;
RCSTAbits.CREN = 1;
}
while(!PIR1bits.RCIF); //Wait for a byte
return RCREG;
}
And in the main loop :
while(1) {
WriteByte_UART('a'); // This works. I can see the As in the terminal
WriteString_UART("Hello World !"); //Nothing displayed :(
}//end while(1)
I have tried different solution for WriteString_UART but none has worked so far.
I don't want to use printf cause it impacts other operations I'm doing with the PIC by adding delay.
So I really want to make it work with WriteString_UART.
In the end I would like to have someting like "Error rate is : [a value]%" on the terminal.
Thanks for your help, and please tell me if something isn't clear.
In your WriteByte_UART() function, try polling the TRMT bit. In particular, change:
while(!PIR1bits.TXIF);
to
while(!TXSTA1bits.TRMT);
I don't know if this is your particular issue, but there exists a race-condition due to the fact that TXIF is not immediately cleared upon loading TXREG. Another option would be to try:
...
Nop();
while(!PIR1bits.TXIF);
...
EDIT BASED ON COMMENTS
The issue is due to the fact that the PIC18 utilizes two different pointer types based on data memory and program memory. Try changing your declaration to void WriteString_UART(const rom char * data) and see what happens. You will need to change your WriteByte_UART() declaration as well, to void WriteByte_UART(const unsigned char ch).
Add delay of few miliseconds after line
TXREG = ch;
verify that pointer *data of WriteString_UART(char *data) actually point to
string "Hello World !".
It seems you found a solution, but the reason why it wasn't working in the first place is still not clear. What compiler are you using?
I learned the hard way that C18 and XC8 are used differently regarding memory spaces. With both compilers, a string declared literally like char string[]="Hello!", will be stored in ROM (program memory). They differ in the way functions use strings.
C18 string functions will have variants to access strings either in RAM or ROM (for example strcpypgm2ram, strcpyram2pgm, etc.). XC8 on the other hand, does the job for you and you will not need to use specific functions to choose which memory you want to access.
If you are using C18, I would highly recommend you switch to XC8, which is more recent and easier to work with. If you still want to use C18 or another compiler which requires you to deal with program/data memory spaces, then here below are two solutions you may want to try. The C18 datasheet says that putsUSART prints a string from data memory to USART. The function putrsUSART will print a string from program memory. So you can simply use putrsUSART to print your string.
You may also want to try the following, which consists in copying your string from program memory to data memory (it may be a waste of memory if your application is tight on memory though) :
char pgmstring[] = "Hello";
char datstring[16];
strcpypgm2ram(datstring, pgmstring);
putsUSART(datstring);
In this example, the pointers pgmstring and datstring will be stored in data memory. The string "Hello" will be stored in program memory. So even if the pointer pgmstring itself is in data memory, it initially points to a memory address (the address of "Hello"). The only way to point to this same string in data memory is to create a copy of it in data memory. This is because a function accepting a string stored in data memory (such as putsUSART) can NOT be used directly with a string stored in program memory.
I hope this could help you understand a bit better how to work with Harvard microprocessors, where program and data memories are separated.

I2C slave receiver on stm32f4

I try to implement a i2c slave receiver interrupt service routine on a stm32f4.
Here is my smart piece of code.
void I2C2_EV_IRQHandler()
{
switch (I2C_GetLastEvent(I2C2))
{
//The address sent by the master matches the own address of the peripheral
case I2C_EVENT_SLAVE_RECEIVER_ADDRESS_MATCHED:
//The slave stretches SCL low until ADDR is
//cleared and DR filled with the data to be sent
I2C_ClearFlag(I2C2,I2C_FLAG_ADDR);
break;
//The application is expecting a data byte to be received
case I2C_EVENT_SLAVE_BYTE_RECEIVED:
I2C_ReceiveData(I2C2);
break;
//The application is expecting the end of the communication
//Make sure that both ADDR and STOPF flags are cleared
//if both are found set.
case I2C_EVENT_SLAVE_STOP_DETECTED:
if(I2C_GetFlagStatus(I2C2,I2C_FLAG_ADDR) == SET)
I2C_ClearFlag(I2C2,I2C_FLAG_ADDR);
if(I2C_GetFlagStatus(I2C2,I2C_FLAG_STOPF) == SET)
I2C_ClearFlag(I2C2,I2C_FLAG_STOPF);
}
}
The interrupt becomes called and I2C_EVENT_SLAVE_RECEIVER_ADDRESS_MATCHED case is entered.
The SCL is low now. The reference manual says if I clear the address flag, the clock will continue and data will be sent (Page 579 - Slave receiver). In my opinion the interrupt always becomes called if any data arrives and next state will be I2C_EVENT_SLAVE_BYTE_RECEIVED.
I can not find any example from stm or via google. Can anybody help me or show me an example.
now it works. My problem was that I was not able to reset the ADDR and the STOPF register with the given commands out of reference manual. But if do it in a loop it works fine for me. Here my working Interrupt Routine.
void I2C3_EV_IRQHandler()
{
switch (I2C_GetLastEvent(I2C3))
{
case I2C_EVENT_SLAVE_RECEIVER_ADDRESS_MATCHED:
STM_EVAL_LEDOn(LED3);
STM_EVAL_LEDOff(LED5);
break;
case I2C_EVENT_SLAVE_BYTE_RECEIVED:
STM_EVAL_LEDToggle(LED4);
STM_EVAL_LEDOff(LED3);
I2C_InputBuffer[I2C_InputBufferIndex++] = I2C_ReceiveData(I2C3);
break;
case I2C_EVENT_SLAVE_STOP_DETECTED:
STM_EVAL_LEDOn(LED6);
STM_EVAL_LEDOff(LED4);
break;
}
I2C_CleanADDRandSTOPF();
if(I2C_InputBufferIndex > MOTOR_PACKAGE_SIZE-1)
{
motorHandleEvent(I2C_InputBuffer);
I2C_InputBufferIndex = 0;
uint8_t resetIndex;
for(resetIndex = 0; resetIndex < MOTOR_PACKAGE_SIZE; resetIndex ++)
I2C_InputBuffer[resetIndex] = 0;
}
}
inline void I2C_CleanADDRandSTOPF()
{
while ((I2C3->SR1 & I2C_SR1_ADDR) == I2C_SR1_ADDR)
{
volatile uint32_t temp;
temp=I2C3->SR1;
temp=I2C3->SR2;
}
while ((I2C3->SR1&I2C_SR1_STOPF) == I2C_SR1_STOPF)
{
volatile uint32_t temp;
temp=I2C3->SR1;
I2C3->CR1 |= 0x1;
}
}
The hardware is doing clock stretching to ensure that the slave is keeping up with the master. The slave first waits to get an address match. Then you get interrupt while SCL is held low. This allows slave to basically provide flow control to the master. The master detects that SCL is being held low by slave and it will wait for it to be released before master sends any more data. So you won't get additional interrupts on data being received because the master won't send any more data until you let SCL go high. You can read about clock stretching here http://en.wikipedia.org/wiki/I%C2%B2C