Transmitting 10bit data through The UART of PIC16F877A - c

I'm beginner to micro controller technology. I want to transmit the 10-bit output I got from an Analog to Digital Conversion, but only 8 bits can be sent via the UART. How can I send 10 bits?
Please help me to write C code to solve this problem. My code so far is given below. The compiler used is XC8.
#pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOREN = ON // Brown-out Reset Enable bit (BOR enabled)
#pragma config LVP = OFF // Low-Voltage (Single-Supply) In-Circuit Serial Programming Enable bit (RB3 is digital I/O, HV on MCLR must be used for programming)
#pragma config CPD = OFF // Data EEPROM Memory Code Protection bit (Data EEPROM code protection off)
#pragma config WRT = OFF // Flash Program Memory Write Enable bits (Write protection off; all program memory may be written to by EECON control)
#pragma config CP = OFF // Flash Program Memory Code Protection bit (Code protection off)
#define _XTAL_FREQ 4000000
#include <stdio.h>
#include <stdlib.h>
#include <htc.h>
void uart_init(void);
void TX(unsigned char TX_BYTE);
void configure_pins();
unsigned char read_input(unsigned char channel);
void main()
{
__delay_ms(2);
while (1) {
TRISB = 0; //configuring portB as output
TRISC = 0;
TRISA = 1;
configure_pins(); //calling methods
unsigned char x = read_input(0);
uart_initialize();
assign_data_to_tx_pin(x);
}
}
void configure_pins(){
ADCON1 = 0b10000000; //The result is right justified
}
unsigned char read_input(unsigned char channel){ // converting the Analog input to digital
ADCON0=0b00000000;
CHS0=0; // AN0 is selected
CHS1=0; // "
CHS2=0; // "
ADON = 1;
GO_DONE = 1;
while (GO_DONE);
ADON = 0;
return ((ADRESH >> 2) + ADRESL); // return the result of conversion
}
void uart_initialize(void) // initializing the UART for data transmission
{
TRISC = 0; //configuring portC as output
TXSTA = 0b100000000;
TXEN = 1; //enable transmission mode
SPEN = 1; //enable UART
BRGH = 0; //enable low baud
SPBRG = 6; //set baud rate as 9600
SYNC = 0; //enable asynchronous transmission
RCIE = 1;
GIE = 1;
PEIE = 1;
}
void assign_data_to_tx_pin(unsigned char converted_data) { // assigning the data to the Tx pin for transmission
while(!TRMT) {
unsigned char a = converted_data;
TXREG = a;
TXREG = a >> 2;
PORTCbits.RC6 = TXREG;
__delay_ms(100); // Delay
}
}

Typical UARTs do not allow for more than 8 bits of data per transmission. Some allow 9. Sending 10 bits may be available on select UARTS using 9 bits and controlling the parity, but that is rare.
Instead recommend to send the data as 2 transmission with a bit set aside to denote which half is sent.
Send_ADC(void){
ADCON0=0b00000000;
CHS0=0; // AN0 is selected
CHS1=0; // "
CHS2=0; // "
ADON = 1;
GO_DONE = 1;
while (GO_DONE);
ADON = 0;
unsigned adc10 = ((ADRESH >> 2) + ADRESL);
assign_data_to_tx_pin((adc10 % 32) * 2 + 0); // 00lllll0
assign_data_to_tx_pin((adc10 / 32) * 2 + 1); // 00hhhhh1
}
On receiver side, insure bytes received are in the proper byte order. This will re-construct the received data in the proper order, even if reception does not start in phase or if a byte was lost in communication.
// return 0: success, else 1
int ReadSerialADC(unsigned *data) {
unsigned adc;
unsigned low = read_from_comport();
if (low %2) return 1;
low /= 2;
unsigned high = read_from_comport();
if (high %2 == 0) return 1;
high /= 2;
*data = high * 32 + low;
return 0;
}

You are reading a 10-bit ADC result with like this
return ((ADRESH>>2)+ADRESL);
But the function is return unsigned char, it should be unsigned int
unsigned int read_input(unsigned char channel)
and the calling function is also throwing away two bits with
unsigned char x=read_input(0);
which should be
unsigned int x=read_input(0);
Having read a 10-bit value into a (presumably) 16-bit variable, you now have to transmit it to the serial port. Let's do this by sending the most significant 8 bits first.
TX (x >> 8);
TX (x & 0xFF);
Then at the receiver end you read the two bytes and put them back together
unsigned adcval = RX() << 8;
adcval |= RX();

Related

SPI Communication between STM32 and ADXL345

I am trying to use the SPI communication to read data from the ADXL345 accelerometer. I configured the different pins and SPI in master mode, and tried reading the x, y and z axis accelerations.
My issue is that the SPI readings are always 0. I tried debugging to find the issue and I realized that RXNE is never set even though I'm transmitting data and I don't really get why.
I'm using STM32F103 Board.
Here's my code:
#include "Driver_GPIO.h"
#include "stm32f10x.h"
uint8_t RxData[6];
int x,y,z;
float x_acc,y_acc,z_acc;
void GPIO_Config (void)
{
MyGPIO_Struct_TypeDef NSS={GPIOA,4,Out_OD}; // Output Open Drain
MyGPIO_Struct_TypeDef SCK={GPIOA,5,AltOut_Ppull}; // Alternate Output Push-Pull
MyGPIO_Struct_TypeDef MISO={GPIOA,6,In_Floating}; // Input Floating
MyGPIO_Struct_TypeDef MOSI={GPIOA,7,AltOut_Ppull}; // Alternate Output Push-Pull
RCC->APB2ENR |= RCC_APB2ENR_IOPAEN; //enable GPIOA clk
MyGPIO_Init(&NSS);
MyGPIO_Init(&SCK);
MyGPIO_Init(&MISO);
MyGPIO_Init(&MOSI);
}
void SPI_Enable (void)
{
SPI1->CR1 |= (SPI_CR1_SPE); // SPE=1, Peripheral enabled
}
void SPI_Disable (void)
{
SPI1->CR1 &= ~(SPI_CR1_SPE); // SPE=0, Peripheral Disabled
}
void CS_Enable (void)
{
GPIOA->BSRR |= GPIO_BSRR_BR9;
}
void CS_Disable (void)
{
GPIOA->BSRR |= GPIO_BSRR_BS9;
}
void SPI_Config(void){
RCC->APB2ENR |= RCC_APB2ENR_SPI1EN; // Enable SPI1 CLock
SPI1->CR1 |= SPI_CR1_CPOL| SPI_CR1_CPHA; // CPOL=1, CPHA=1
SPI1->CR1 |= SPI_CR1_MSTR; // Master Mode
SPI1->CR1 |= (SPI_CR1_BR_0)| (SPI_CR1_BR_1); // BR[2:0] = 400: fPCLK/16, PCLK2 = 72MHz, SPI clk = 3.375MHz
SPI1->CR1 &= ~SPI_CR1_LSBFIRST; // LSBFIRST = 0, MSB first
SPI1->CR1 |= (SPI_CR1_SSM) | (SPI_CR1_SSI); // SSM=1, SSI=1 -> Software Slave Management
SPI1->CR1 &= ~SPI_CR1_RXONLY; // RXONLY = 0, full-duplex
SPI1->CR1 &= ~SPI_CR1_DFF; // DFF=0, 8 bit data
SPI1->CR2 = 0;
}
void SPI_Transmission(uint8_t *data, int size){
uint8_t clear;
//check flag TxE //
int i=0;
while (i<size)
{
while (!((SPI1->SR)&(SPI_SR_TXE))){}; // buffer is empty
*(volatile uint8_t *)&SPI1->DR = data[i];
i++;
}
while (!((SPI1->SR)&(SPI_SR_TXE))){}; // buffer is empty
while (((SPI1->SR)&(SPI_SR_BSY))){}; // buffer not communicating
clear= SPI1->DR; // empty Overrun flag
clear= SPI1->SR;
}
void SPI_Receive (uint8_t *data,int size)
{
while (size)
{
while (((SPI1->SR)&(SPI_SR_BSY))) {}; // buffer not communicating
*(volatile uint8_t *)&SPI1->DR = 0; // dummy data
while (!((SPI1->SR) &(SPI_SR_RXNE))){};
// buffer is not empty
*data++= *(volatile uint8_t *)&SPI1->DR;
size--;
}
}
void adxl345_write (uint8_t address, uint8_t value)
{
uint8_t data[2];
data[0] = address|0x40; // multibyte write
data[1] = value;
CS_Enable (); // pull the cs pin low
SPI_Transmission (data,2); // write data to register
CS_Disable (); // pull the cs pin high
}
void adxl345_read (uint8_t address, uint8_t *RxData)
{
address |= 0x80; // read operation
address |= 0x40; // multibyte read
CS_Enable (); // pull the pin low
SPI_Transmission (&address,1); // send address
SPI_Receive (RxData,6); // receive 6 bytes data
CS_Disable ();; // pull the pin high
}
void adxl345_init (void)
{
adxl345_write (0x31, 0x01); // data_format range= +- 4g
adxl345_write (0x2d, 0x00); // reset all bits
adxl345_write (0x2d, 0x08); // power_cntl measure and wake up 8hz
}
int main(void)
{
GPIO_Config();
SPI_Config();
SPI_Enable();
adxl345_init();
do{
adxl345_read(0x32,RxData);
x = ((RxData[1]<<8)|RxData[0]); // DATA X0, X1
y = ((RxData[3]<<8)|RxData[2]); // DATA Y0, Y1
z = ((RxData[5]<<8)|RxData[4]); // DATA Z0, Z1
// Scale Factor for Xout, Yout and Zout is 7.8 mg/LSB for a +-4g, 10-bit resolution
// ==> multiply by 0.0078 to get real acceleration values
x_acc= x * 0.0078;
y_acc= y * 0.0078;
z_acc= z * 0.0078;
}while(1);
}
As already stated you have a lot of issues here
Why NSS pin is configured open-drain? Typically CS lines are push-pull. I don't know the schematics, but this is the first time I see an open-drain CS
In GPIO_Config NSS is pin 4, yet pin 9 is toggled from CS_Enable
If F1 series there is separate clocking bit for the alternate functions, it's not enabled
It is also weird that you are telling that RXNE is always zero and the readings returns zero. Your code should stuck in while loops if RXNE stays zero
I will not analyze magic numbers as I do not have time check every number in the RM. But you have many obvious issues.
Deley or readback is required after enabling the peripheral clock. You instantly set the registers which is wrong. Add __DSB(); or readback (for example (void)RCC->APB2ENR;). Same for all peripherals

PIC32 UART: U1RXREG Register Never Contains Any Values Other Than 0

I've attached an image showing my oscilloscope readout which is from the code below. Context: I have a Pi and a PIC which need to communicate through UART connection. I've implemented my own flow control which can be seen in the image attached [RTS = Yellow Trace, CTS = Blue Trace, Rx = Green Trace]. The code runs through and is caught in the final switch case statement which turns on an LED. But when i debug the code, no values (well the only value which is read is zero) are read in. At first i thought that i'd configured my PIC clock wrong (which is used to derive the baud rate), but i don't think this is the case. Second i through the FIFO buffer was full of zeros only and considering that i'm sending only four packets of information to the PIC, and my FIFO is 4 registers deep that this was the reason why non of the information was appearing. So i executed a code which removes the dummy bytes but this did not work.
All that is received:
0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0><0> etc
I got the right settings selected: baud rate: 9600 data bits: 8 parity: none stop bits: 1
If anyone is willing to spend some time looking at my code, can you see any obvious errors?
https://i.stack.imgur.com/aQoAL.jpg
Minimum Reproducible Example
# include <xc.h>
# include <math.h>
# include <stdio.h>
# include <stdio.h>
//Configuration Bits
#pragma config FNOSC = FRCPLL // Internal Fast RC Oscillator (8MHz)
#pragma config FPLLIDIV = DIV_2 // Divide FRC before PLL (Now 4MHz)
#pragma config FPLLMUL = MUL_20 // PLL Multiply (Now 80MHz)
#pragma config FPLLODIV = DIV_2 // Divide After PLL (Now 40MHz)
#pragma config FPBDIV = DIV_1 // Pheripheral Bus Clock (At 40KHz)
#pragma config FWDTEN = OFF // Watchdog Timer Disabled
#pragma config ICESEL = ICS_PGx2 // ICE/ICD Comm Channel Select
#pragma config JTAGEN = OFF // Disable JTAG
#pragma config FSOSCEN = OFF // Disable Secondary Oscillator
//*****************************UART Functions***********************************
void UART_Config (void) // Baude Rate of 9600, 8-Bit Data , 1 Stop Bit
{
U1MODEbits.BRGH = 0;
U1BRG = 259; //U1BRG = (40M/ (16 * 9.6k))) - 1
U1MODEbits.SIDL = 0; // Continue operation in SLEEP mode
U1MODEbits.IREN = 0; // IrDA is disabled
U1MODEbits.RTSMD = 0; // U1RTS pin is in Flow Control mode
U1MODEbits.UEN = 0b00; // U1TX, U1RX are enabled
U1MODEbits.WAKE = 1; // Wake-up enabled
U1MODEbits.LPBACK = 0; // Loopback mode is disabled
U1MODEbits.RXINV = 0; // U1RX IDLE state is '1'
U1MODEbits.PDSEL = 0b00; // 8-bit data, no parity
U1MODEbits.STSEL = 0; // 1 stop bit
U1STAbits.UTXINV = 0; // U1TX IDLE state is '1'
U1MODEbits.ON = 1; // UART1 is enabled
U1STAbits.URXEN = 1; // UART1 receiver is enabled
U1STAbits.UTXEN = 1; // UART1 transmitter is enabled
}
void Send_UART_Data(unsigned int c) // PIC Sending Data for Pi to Read
{
U1STAbits.UTXEN = 1; // Make sure transmitter is enabled
// while(CTS) // Optional CTS (Clear to Send) use
while(U1STAbits.UTXBF); // Wait while buffer is full
U1TXREG = c; // Transmit character
}
int Read_UART_Data (void) // PIC Reading Sent Data from Pi
{
int c;
while(!U1STAbits.URXDA) // Wait for information to be received
c = (int)U1RXREG; // Convert Character to Value
return c;
}
ADC_To_UART (unsigned int ADC)
{
unsigned int temp_A = 0x00;
unsigned int temp_B = 0x00;
// Splitting a 10 Bit Word Into 2 Bytes [aa aaaa aabb]
// Start Bit = 1 , Stop Bit = 0
// UART Transmission Pattern [1 aaaa aaaa 0 0000 00 bb]
temp_A = ADC >> 2; // MSB(8 Bits) ~ ADC[9:2] [aaaa aaaa]
temp_B = ADC & 0x003; // LSB(2 Bits) ~ ADC[1:0] [0000 00bb]
Send_UART_Data(temp_A);
Send_UART_Data(temp_B);
}
[enter image description here][1]
//*********************Enumerated Variable Declaration**************************
//Program Flow Control
enum Comm_State {Phase1A, Phase1B, Phase1C, Phase1D, Phase1E, Phase2A, Phase2B, Phase2C, Phase2D, Phase2E, Phase2F, Phase2G};
//******************************************************************************
//********************************MAIN******************************************
int main( )
{
//***************************Configuration**********************************
// I/O Definitions
#define UART_TRIS_RX TRISBbits.TRISB13 // UART RX - Reciever Pin (PPS)
#define UART_TRIS_TX TRISBbits.TRISB15 // UART TX - Transmission Pin (PPS)
#define UART_TRIS_CTS_PIC TRISAbits.TRISA4 // UART CTS_1 - Clear to Send - Output [CTS PIC]
#define UART_TRIS_RTS_PIC TRISBbits.TRISB4 // UART RTS_1 - Ready to Send - Output [RTS PIC]
#define UART_TRIS_CTS_PI TRISAbits.TRISA3 // UART CTS_2 - Clear to Send - Input [CTS PI]
#define UART_TRIS_RTS_PI TRISAbits.TRISA2 // UART_RTS_2 - Ready to Send - Input [RTS PI]
#define SPI_TRIS_SCK TRISBbits.TRISB14 // SPI SCK - Serial Clock Pin (PPS?)
#define SPI_TRIS_SDO TRISBbits.TRISB6 // SPI SDO - Serial Data Out Pin (PPS?)
#define SPI_TRIS_CS_1 TRISBbits.TRISB8 // SPI CS1 - DAC 2 Chip Select Pin (PPS?)
#define SPI_TRIS_CS_2 TRISBbits.TRISB7 // SPI CS2 - DAC 1 Chip Select Pin (PPS?)
#define AN4_TRIS TRISBbits.TRISB2 // Analogue Read 3
#define AN3_TRIS TRISBbits.TRISB1 // Analogue Read 2
#define AN2_TRIS TRISBbits.TRISB0 // Analogue Read 1
#define V_REF_TRIS_Plus TRISAbits.TRISA0 // Analogue V_REF(+) (Forms VRange)
#define V_REF_TRIS_Minus TRISAbits.TRISA1 // Analogue V_REF(-) (Forms VRange)
#define Reg_Enable_TRIS_D TRISBbits.TRISB9 // Regulator Digital Control (Output)
#define Reg_Enable_TRIS_M TRISBbits.TRISB12 // Regulator Button (Input)
// Port Input/Output Configuration [TRISB]
TRISB = 0x1004; // All of PortB set as Outputs Except for RB12 (Reg Enable) and RB2 (Input -> Analogue Input (Voltage)) (Port B) = (0000 ... 0100)
TRISA = 0x0003; // Set up A0 [Pin 2] and A1 [Pin 3] as V_REF(+) and V_REF(-) Respectively (Port B) = (0000 ... 0011)
UART_TRIS_RX = 1; // UART Receiver ~ Input
UART_TRIS_TX = 0; // UART Transmission ~ Output
UART_TRIS_CTS_PIC = 0; // UART "CTS_PIC" ~ Output
UART_TRIS_RTS_PIC = 0; // UART "RTS_PIC" ~ Output
UART_TRIS_CTS_PI = 1; // UART "CTS_PI" ~ Input
UART_TRIS_RTS_PI = 1; // UART "RTS_PI" ~ Input
SPI_TRIS_SCK = 0; // SPI Clock ~ Output
SPI_TRIS_SDO = 0; // SPI Data Output ~ Output
SPI_TRIS_CS_1 = 0; // SPI Chip Select 1 ~ Output
SPI_TRIS_CS_2 = 0; // SPI Chip Select 2 ~ Output
AN4_TRIS = 1; // Analogue Read In ~ Input
AN3_TRIS = 1; // Analogue Read In ~ Input
AN2_TRIS = 1; // Analogue Read In ~ Input
V_REF_TRIS_Plus = 1; // V_Ref(+) ~ Input
V_REF_TRIS_Minus = 1; // V_Ref(-) Differential Measurements ~ Input
Reg_Enable_TRIS_D = 0; // Regulator Digital Control (Output)
Reg_Enable_TRIS_M = 1; // Regulator Switch Control (Input)
// Peripheral Pin Select Configurations
U1RXR = 0x0011; // UART PPS Mapping
RPB15R = 0x0001; // UART PPS Mapping
// Analogue Pin Configurations
ANSELB = 0x0028; // RB0 RB1 RB2 = AN2 AN3 AN4 [0001 1100]
ANSELA = 0x0000; // Set all Analogue Inputs of Port A Off
//**************Sub-System Configurations*********************************//
// UART Control Configure
UART_Config(); //UART Control Configure
#define PIC_CTS LATAbits.LATA4 // Output Set Definition [1]
#define PIC_RTS LATBbits.LATB4 // Output Set Definition [2]
#define PI_CTS PORTAbits.RA3 // Input Read Definition [2]
#define PI_RTS PORTAbits.RA2 // Input Read Definition [1]
// Analogue Control Configure
ADC_Config(); // Configure ADC
AD1CON1SET = 0x8000; // Enable ADC
//***************Variable Declarations************************************//
enum Comm_State Communication_State = Phase1A; //Controller Variable
unsigned int temp1 = 0;
unsigned int Comms_Flag_1 = 0;
unsigned int ConFlag = 1;
unsigned int i = 1;
unsigned int UART_ADC_CV_1 = 0;
unsigned int UART_ADC_CV_2 = 0;
unsigned int ADC_CV = 0;
unsigned int UART_ADC_CC_1 = 0;
unsigned int UART_ADC_CC_2 = 0;
unsigned int ADC_CC = 0;
unsigned int DAC_CV = 0;
float I_CC = 0;
float V_CV = 0;
//***************Program Flow - Switch State Controlled*******************//
while(1)
{
switch (Communication_State)
{
case Phase1A: // Check For Pi Ready to Send CV ADC Value
//PIC_CTS = 0;
//Pic_Refresh();
PIC_RTS = 0;
PIC_CTS = 1;
if (PI_RTS == 1)
{
PIC_CTS = 0;
Communication_State = Phase1B;
}
break;
case Phase1B: // Receive CV ~ 12 Bit ADC Value [Two Data Packets with 0.01 Second Delay]
ConFlag = 1;
i = 1;
while (ConFlag == 1)
{
if (PI_RTS == 1 && i == 1)
{
UART_ADC_CV_1 = Read_UART_Data(); //Data Packet 1 Returned - MSB(Bit 15) to Bit 8
i++;
}
else if (PI_RTS == 1 && i == 2)
{
UART_ADC_CV_2 = Read_UART_Data(); //Data Packet 2 Returned - Bit (7)) to LSB(Bit 0)
}
else
{
ConFlag = 0;
}
}
Communication_State = Phase1C;
break;
case Phase1C: // Check for CC Value
delay(); //Ensure that Pi_RTS has gone low after sending last Transmission (Prevents Code from Running Away)
PIC_CTS = 1;
if (PI_RTS == 1)
{
PIC_CTS = 0;
Communication_State = Phase1D;
}
break;
case Phase1D: // Receive CC Value [Two Data Packets with 0.01 Second Delay]
ConFlag = 1;
i = 1;
while (ConFlag == 1)
{
if (PI_RTS == 1 && i == 1)
{
UART_ADC_CC_1 = Read_UART_Data(); //Data Packet 1 Returned - MSB(Bit 15) to Bit 8
i++;
}
else if (PI_RTS == 1 && i == 2)
{
UART_ADC_CC_2 = Read_UART_Data(); //Data Packet 2 Returned - Bit (7)) to LSB(Bit 0)
}
else
{
ConFlag = 0;
}
}
Communication_State = Phase1E;
break;
case Phase1E: // Calculations
// CV Calculations
temp1 = UART_ADC_CV_1 << 8;
ADC_CV = temp1 + UART_ADC_CV_2;
V_CV = ADC_CV * (4.096/4096);
DAC_CV = ADC_CV | 4096;
Comms_Flag_1 = SPI_Transfer(DAC_CV ,1); // Data Transmitted to DAC 1, Upon Transmission LED Turns Green (No Acknowledgement)
// CC Calculations
temp1 = UART_ADC_CC_1 << 8;
ADC_CC = temp1 + UART_ADC_CC_2;
I_CC = ADC_CC * (4.096/4096);
Communication_State = Phase2A;
break;
case Phase2A:
while(1)
{
LATBbits.LATB5 = 1;
}
break;
}
}
return 1;
}
In Read_UART_Data, you have:
while(!U1STAbits.URXDA)
c = (int)U1RXREG;
I think you're missing a semicolon because this is actually:
while (!U1STAbits.URXDA)
c = (int) U1RXREG;
This means that c is set only when the UART receiver is not ready.
What I think you meant is:
while (!U1STAbits.URXDA);
c = (int) U1RXREG;

Speed measurement from lidar sensor for automatic braking system

For a school project I have been working on a system that will automatically brake when there is danger. Only the requirements are more strict (safety) than just using a ping sensor and detecting a fixed distance. I am going to implement the speed of an incoming object as well.
On the internet I found this awesome 100Hz sample Lidar module that's very cheap. It uses UART with 2 header frames (0x59), after that a dataLowbyte and a dataHighbyte. Here is the datasheet for the module.
So I've started inputting coffee and outputting code (in C) on the atmega328P (Arduino).
As you can see here I've set up the code to read the sensor and process the data. The problem is that it gives back weird readings. Like a distance difference when I'm moving further away and when moving closer even though I stated it not to. Does anyone have experience using this module? Or maybe I misread something of the datasheet.
//Includes
//============================================================================================//
#include <avr/io.h>
#include <avr/interrupt.h>
#include <math.h>
//============================================================================================//
//Defines
//============================================================================================//
#define F_CPU 16000000 //CPU frequency
#define Baudrate 115200 //UART Baudrate
#define UBRR_VALUE (((F_CPU / (Baudrate * 8))) - 1) //UART Baudrate set in Arduino
// #define SafetyRating 8
// #define sampleTime 0x65 //Time between 2 samples in 10^-4. This value comes from testing (its 1,01ms)
//============================================================================================//
//Enums
//============================================================================================//
enum {Safe, Warning, Danger}State; //Possible States
//============================================================================================//
//Global variables
//============================================================================================//
uint8_t distanceL; //Distance (low value) data taken from the UART buffer coming from Lidar
uint8_t distanceH; //Distance (high value) data taken from the UART buffer coming from Lidar
uint16_t Distance; //Distance combined
uint8_t frameByteCount = 0; //To count which byte in the frame is current
uint16_t Speed; //Speed variable
//volatile uint8_t DangerLevel; //Danger indicator
//Function prototypes
//============================================================================================//
void calcSpeed(uint16_t Measurement); //Function to calculate the speed out of distance readings
void UART_Transmit(uint8_t data); //Funtion to send data via uart
//============================================================================================//
//Interrupts
//============================================================================================//
/*UART receive complete interrupt*/
ISR(USART_RX_vect) //Data taken from the UART buffer
{
uint8_t sample;
sample = UDR0; //Read a sample from the receiver buffer
if(frameByteCount == 3) //If its the 4th byte of the frame
{
frameByteCount = 0; //Reset the counter
distanceH = sample; //Read the distance data high byte
Distance = (8 << distanceH); //Combine the data low and data high
Distance |= distanceL;
calcSpeed(Distance); //Send the data to laptop for debugging purposes
}
if(frameByteCount == 2) //If its the 3rd byte in the frame read the distance data low byte
{
distanceL = sample;
frameByteCount++; //Increment the counter
}
if (sample == 0x59) //If a sample is a header increment a counter
{
frameByteCount++;
}
else if (frameByteCount != 2 && frameByteCount != 3) //If its not a header or distance data byte reset counter
{
frameByteCount = 0;
}
}
//============================================================================================//
//Timers and Counters
//============================================================================================//
/*Timer0 Counter, this decreases the danger level periodically so a really slow approach will not keep incrementing the danger level*/
ISR(TIMER0_OVF_vect)
{
// if (DangerLevel > 0)
// {
// DangerLevel--;
// }
}
//============================================================================================//
//Main
//============================================================================================//
int main(void)
{
DDRB |= 0x02; //For debugging purposes LED pin PB1 (pin 9) as output
UBRR0H = (UBRR_VALUE >> 8); //Setting the Baudrate register high value
UBRR0L = UBRR_VALUE; //Setting the Baudrate register low value
UCSR0A |= (1<<U2X0); //Setting the data sample to double speed to make Baudrate error less
UCSR0C |= (1<<UCSZ01) | (1<<UCSZ00); //Initializing UART, setting frame to 8 data bits
UCSR0B |= (1<<RXCIE0) | (1<<TXEN0) | (1<<RXEN0); //Setting receiver interrupt enable, transmitter enable and receiver enable... Transmitter for debugging purposes
TCCR0A = 0x00; //Timer0 Setup
TCCR0B |= 0x05; //Timer0 clock prescaler to 1024
TIMSK0 |= 0x01; //Timer0 overflow interrupt enable
sei(); //Set interrupts
State = Safe; //Set state to safe
while (1)
{
//checkState(DangerLevel);
}
}
//============================================================================================//
//Functions
//============================================================================================//
/*Calculate the danger level out of distance readings*/
void calcSpeed(uint16_t Measurement)
{
static uint8_t samplenumber = 0; //Sample tracker
static uint16_t value0 = 0; //First sample
static uint16_t value1 = 0; //Second sample
switch(samplenumber) //To store the measurements alternately
{
case 0:
value0 = Measurement; //Store first measurement
samplenumber = 1; //So next measurement goes to a different variable
break;
case 1:
value1 = Measurement; //Store 2nd measurement
samplenumber = 0; //So next measurement goes to a different variable
break;
default:
break;
}
if (samplenumber == 0 && value1 < value0) //When value0 is first and value1 is second and the object is closing in
{
Speed = value0 - value1;
}
else if (samplenumber == 1 && value0 < value1) //When value1 is first and value0 is second and the object is closing in
{
Speed = value1 - value0;
}
else
{
Speed = 0;
}
UART_Transmit(Speed); //I think sending an uint16_t over uint8_t uart is possible because 'Speed' is never greater than 255 when i'm testing it
}
/*Send data over UART when buffer is empty*/
void UART_Transmit(uint8_t data)
{
/* Wait for empty transmit buffer */
while ( !( UCSR0A & (1<<UDRE0)) )
;
/* Put data into buffer, sends the data */
UDR0 = data;
}
//============================================================================================//
I found it!
Distance = (8 << distanceH); //Combine the data low and data high
Distance |= distanceL;
Should be:
Distance = (distanceH << 8); //Combine the data low and data high
Distance |= distanceL;

MicroChip dsPic33, UART RX interrupt is not being called

Good afternoon,
I've configured my RX interrupt using the following simple function.
char c;
void __attribute__((interrupt, no_auto_psv)) _U1RXInterrupt( void )
{
IFS0bits.U1RXIF = 0; // Clear RX Interrupt flag
c = U1RXREG;
}
The problem is, UART transmits fine, but the interrupt service routine is never entered when it gets sent a character. I can trace with a scope that the character is actually sent without issues, but the interrupt does not get triggered.
The device used for communication is TTL-232R-3v3. The device is running at 3.3V
The actual model number of the dspic33 is p33FJ128MC802
The programming environment is Mplab 8 and the compiled is XC16
Is there a missing setting to perhaps enable the interrupt? What could be missing?
Thanks,
Here is the UART initialization code.
U1MODEbits.UARTEN = 0; // Bit15 TX, RX DISABLED, ENABLE at end of func
U1MODEbits.USIDL = 0; // Bit13 Continue in Idle
U1MODEbits.IREN = 0; // Bit12 No IR translation
U1MODEbits.RTSMD = 0; // Bit11 Simplex Mode
U1MODEbits.UEN = 0; // Bits8,9 TX,RX enabled, CTS,RTS not
U1MODEbits.WAKE = 0; // Bit7 No Wake up (since we don't sleep here)
U1MODEbits.LPBACK = 0; // Bit6 No Loop Back
U1MODEbits.ABAUD = 0; // Bit5 No Autobaud (would require sending '55')
U1MODEbits.URXINV = 0; // Bit4 IdleState = 1 (for dsPIC)
U1MODEbits.BRGH = 0; // Bit3 16 clocks per bit period
U1MODEbits.PDSEL = 0; // Bits1,2 8bit, No Parity
U1MODEbits.STSEL = 0; // Bit0 One Stop Bit
// U1BRG = (Fcy / (16 * BaudRate)) - 1
// U1BRG = (36850000 / (16 * 9600)) - 1
// U1BRG = 238.908854 //Round to 239
U1BRG = 239;
U1STAbits.UTXISEL1 = 0; //Bit15 Int when Char is transferred (1/2 config!)
U1STAbits.UTXINV = 0; //Bit14 N/A, IRDA config
U1STAbits.UTXISEL0 = 0; //Bit13 Other half of Bit15
U1STAbits.UTXBRK = 0; //Bit11 Disabled
U1STAbits.UTXEN = 0; //Bit10 TX pins controlled by periph
U1STAbits.UTXBF = 0; //Bit9 *Read Only Bit*
U1STAbits.TRMT = 0; //Bit8 *Read Only bit*
U1STAbits.URXISEL = 0; //Bits6,7 Int. on character recieved
U1STAbits.ADDEN = 0; //Bit5 Address Detect Disabled
U1STAbits.RIDLE = 0; //Bit4 *Read Only Bit*
U1STAbits.PERR = 0; //Bit3 *Read Only Bit*
U1STAbits.FERR = 0; //Bit2 *Read Only Bit*
U1STAbits.OERR = 0; //Bit1 *Read Only Bit*
U1STAbits.URXDA = 0; //Bit0 *Read Only Bit*
RPINR18bits.U1RXR = 0b00010;//7; //RX is Pin RP2
RPOR1bits.RP3R = 0b00011; //TX is pin RP3
U1MODEbits.UARTEN = 1; // And turn the peripheral on
U1STAbits.UTXEN = 1;
Check if the pin has additional functionality. Typically this is AD (analog pin). Make sure you turn off all analog, via the ADP or ANSEL registers (type and number varies depending on exact chip) E.g. I have this routine (I use both 33F and 33E and a high and low pincount one of both, hence the ifdefs)
void analogoff(void){
#if defined(__dsPIC33F__)
ADPCFG =0xFFFF;
AD1PCFGH=0xFFFF;
AD1PCFGL=0xFFFF;
#endif
#if defined(__dsPIC33E__)
#if !defined(__dsPIC33EP256MU806__)
ANSELA=0;
#endif
ANSELB=0;
ANSELC=0;
ANSELD=0;
ANSELE=0;
ANSELG=0;
#endif
}
Also, make absolutely sure the oscillator and thus the part's speed is correct, though if TX has the correct baudrate (scope!) that is probably ok.
My uart1 init:
U1BRG = brgval;
U1MODE = 0x8000; // Reset UART to 8-n-1, alt pins, and enable lowspeed (=bit 3)
U1MODEbits.USIDL =0; // disable module when device is idle.
U1MODEbits.IREN =0; // IRDA disable
U1MODEbits.RTSMD =0; // flow control mode (1= simplex mode)
U1MODEbits.UEN =0; // RTS en CTS controlled by PORTlatches
U1MODEbits.WAKE =0; // no wakeup enabled;
U1MODEbits.LPBACK=0; // loopback disabled
U1MODEbits.ABAUD =0; // no autobaud
#if !defined(__PIC24F__)
U1MODEbits.URXINV =0; // RXINV inversion RX. (0= idle = '1')
#endif
U1MODEbits.BRGH =1; // high speed.
U1MODEbits.PDSEL =0; // 8 bit no parity
U1MODEbits.STSEL =0; // 1 stopbit.
U1STA = 0x0440;
U1STAbits.URXISEL0=0;// Reset status register and enable TX & RX.
U1STAbits.URXISEL1=0; // rx interrupt on a char.
_U1RXIF=0; // Clear UART RX Interrupt Flag
_U1RXIE = 1; // Interruption active pour la reception
_U1RXIP=2;
_U1TXIP=2;
_U1TXIF=0;
_U1TXIE=0; // only enabled when actually sending
U1MODEbits.UARTEN=1;

AVR Butterfly UART - can't receive data

I am using the UART of Atmega169/AVR Butterfly for transmission to another board, baudrate 56700, no parity, 1 stopbit, no flow control. The oscillator is running at 7,3768Mhz (checked). I can transmit data successfully (checked with the other board and PC/HyperTerminal), but not receive any data - when running the debugger the configuration bits are all set correctly, but RXC is false constantly - I also checked if I can send data to myself (connected TXD to RXD and grounded), but without success. (Tried with ISR as well as polling)
Below are the relevant parts of the code, I hope you can deal with it - PORTB is used as output for testing with the oscilloscope (I know I could just use one pin, but there is nothing else on PORTB right now):
int main(void){
OSCCAL_Calibrate(); // calibrate the internal oscillator
int UBRR_VAL = ((F_CPU)/(BAUD*16)-1);
UART_Init(UBRR_VAL);
DDRB |= 0xFF;
PORTB = 0;
testCharSend();
while(1);
return 0;
}
void testCharSend()
{
char i = 'x';
while(1){
Uart_Tx(i);
}
}
void UART_Init(unsigned int baudrate)
{
// Set baud rate
UBRRH = (unsigned char)(baudrate>>8);
UBRRL = (unsigned char)baudrate;
UCSRA = 0;
// Enable receiver and transmitter
UCSRB = (1<<RXEN)|(1<<TXEN);
// Async. mode, 8bit, No parity, 1 stop bit (like CC2540)
UCSRC = (0<<UMSEL)|(0<<UPM0)|(0<<USBS)|(3<<UCSZ0)|(0<<UCPOL);
// enable receive interrupt
UCSRB |= (1<<RXCIE);
// flush UART
UART_Flush();
}
void UART_Flush( void )
{
unsigned char dummy;
while ( UCSRA & (1<<RXC) ) dummy = UDR;
}
void Uart_Tx(char data)
{
while (!(UCSRA & (1<<UDRE)));
UDR = data;
}
ISR (USART0_RX_vect)
{
PORTB ^= 0xFF;
char c = UDR;
}
OK, I tested the connections with an oscilloscope, the RXD line on the board was broken, switched the board and now it's working, so the code above is valid!

Resources