MSP430F6638 RTC_B RTCRDY bit never set - msp430

Using RTC_B
XIN is connected to a 32.768 kHz clock source (not oscillator)
XIN Bypass is used since no oscillator
Init code is as follows:
//Calendar mode, BCD coded, stop rtc, hourly interrupt
RTCCTL01 = RTCTEV_0 + RTCHOLD;
//no calibration
RTCCTL23 = 0;
//prescale setup
RTCPS0CTL = 0; // disable PS0 interrupts
//clear calendar
RTCHOUR = 0;
RTCMIN = 0;
RTCSEC = 0;
RTCDAY = 0;
RTCMON = 0;
RTCYEAR = 0;
//enable RTC
RTCCTL01 &= ~RTCHOLD;
After this I wait for the RTCRDY bit to get set but it never does
while( !(RTCCTL01 & RTCRDY) );
Note that the clock is being configured as follows:
// Enable XT1(32.768kHz) and XT2(4MHz) clock ports
XT1_XT2_PORT_SEL |= (XT1_ENABLE + XT2_ENABLE);
XT1_Bypass();
ret = SetVCore(3); // Set Vcore to accommodate for max. allowed
LFXT_Start(XT1DRIVE_3); // Enable XT1 and maximize drive strength
//! \note The system clock is derived from the internal reference clock,
//! which is set to 32768.
Init_FLL_Settle(MCLK_TICKPERSEC/1000, MCLK_TICKPERSEC/32768);

LFXT_Start() disables bypass mode and enables the oscillator.

Related

setting right ADC prescaler on the Arduino Due in timer and interrupt driven multi-channel ADC acquisition

I am trying to follow, adapt, understand (and clean up a bit) a variation around the code available there, for the Arduino Due: https://forum.arduino.cc/index.php?topic=589213.0 . I do not like the forum format, as things end up buried deep, so asking here instead. Unfortunately this means that there is quite a lot of explanations before the question. If you think this is wrong to post it here, let me know, and I can move.
Basically, the idea is to log several ADC channels in a buffer, using timer-based triggering. There is a bit of setup:
// sample rate in Hz
constexpr int sample_rate = 1000;
constexpr uint8_t channels[] = {7, 6, 5, 4, 3};
constexpr int nbr_channels = sizeof(channels);
Then time counter 0 channel 2 is set at the right frequency for triggering the ADC conversion:
// use time counter 0 channel 2 to generate the ADC start of conversion signal
// i.e. this sets a rising edge with the right frequency for triggering ADC conversions corresponding to sample_rate
// for more information about the timers: https://github.com/ivanseidel/DueTimer/blob/master/TimerCounter.md
// NOTE: TIOA2 should not be available on any due pin https://github.com/ivanseidel/DueTimer/issues/11
void tc_setup() {
PMC->PMC_PCER0 |= PMC_PCER0_PID29; // TC2 power ON : Timer Counter 0 channel 2 IS TC2
TC0->TC_CHANNEL[2].TC_CMR = TC_CMR_TCCLKS_TIMER_CLOCK2 // clock 2 has frequency MCK/8, clk on rising edge
| TC_CMR_WAVE // Waveform mode
| TC_CMR_WAVSEL_UP_RC // UP mode with automatic trigger on RC Compare
| TC_CMR_ACPA_CLEAR // Clear TIOA2 on RA compare match
| TC_CMR_ACPC_SET; // Set TIOA2 on RC compare match
constexpr int ticks_per_sample = F_CPU / 8 / sample_rate; // F_CPU / 8 is the timer clock frequency, see MCK/8 setup
constexpr int ticks_duty_cycle = ticks_per_sample / 2; // duty rate up vs down ticks over timer cycle; use 50%
TC0->TC_CHANNEL[2].TC_RC = ticks_per_sample;
TC0->TC_CHANNEL[2].TC_RA = ticks_duty_cycle;
TC0->TC_CHANNEL[2].TC_CCR = TC_CCR_SWTRG | TC_CCR_CLKEN; // Software trigger TC2 counter and enable
}
Finally this can be used to trigger the ADC:
// start ADC conversion on rising edge on time counter 0 channel 2
// perform ADC conversion on several channels in a row one after the other
// report finished conversion using ADC interrupt
void adc_setup() {
PMC->PMC_PCER1 |= PMC_PCER1_PID37; // ADC power on
ADC->ADC_CR = ADC_CR_SWRST; // Reset ADC
ADC->ADC_MR |= ADC_MR_TRGEN_EN | // Hardware trigger select
ADC_MR_PRESCAL(1) | // the pre-scaler: as high as possible for better accuracy, while still fast enough to measure everything
// see: https://arduino.stackexchange.com/questions/12723/how-to-slow-adc-clock-speed-to-1mhz-on-arduino-due
ADC_MR_TRGSEL_ADC_TRIG3; // Trigger by TIOA2 Rising edge
ADC->ADC_IDR = ~(0ul);
ADC->ADC_CHDR = ~(0ul);
for (int i = 0; i < nbr_channels; i++)
{
ADC->ADC_CHER |= ADC_CHER_CH0 << channels[i];
}
ADC->ADC_IER |= ADC_IER_EOC0 << channels[nbr_channels - 1];
ADC->ADC_PTCR |= ADC_PTCR_RXTDIS | ADC_PTCR_TXTDIS; // Disable PDC DMA
NVIC_EnableIRQ(ADC_IRQn); // Enable ADC interrupt
}
and the ADC output can be captured in the corresponding ISR:
void ADC_Handler() {
for (size_t i = 0; i < nbr_channels; i++)
{
SOME_BUFFER[i] = static_cast<volatile uint16_t>( * (ADC->ADC_CDR + channels[i]) & 0x0FFFF ); // get the output
}
}
I think this is quite understandable, but I have one question: the setting of the pre-scaler.
if I understand well discussions online, the pre-scaler should be set so that frq_ADC >= sample_rate * nbr_channels, basically because the chip is just multiplexing the ADC through several channels
if I understand well, we want to set such pre-scaler value as high as possible given the previous constraint, so that the ADC frequency is as low as possible, because this improves ADC conversion quality
Is that right?
The problem is that I am confused about how to set the pre-scaler, and what value corresponds to what, because what I find in the datasheet disagree with some other online responses I read.
From the datasheet https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf : "The ADC clock range is between MCK/2, if PRESCAL is 0, and MCK/512, if PRESCAL is set to 255 (0xFF).". This is consistent with what I find on page 1334: "ADCClock = MCK / ( (PRESCAL+1) * 2 )". But page 1318, it is written that the conversion rate is 1MHz. Then how is that compatible with having a MCK frequency of 84MHz on the Due? 84/2 = 48MHz, 84/512 = 0.164MHz, the high freq value is too high.
Then to add to the confusion I have found this issue: https://arduino.stackexchange.com/questions/12723/how-to-slow-adc-clock-speed-to-1mhz-on-arduino-due/21054#21054 that also seem to conflict with the 1MHz upper bound.
Any idea where I misunderstand something? (and any more comments around the general working of the program?).
Ok, so I did some tests with the code, checking when I was missing some conversions depending on the timer frequency and the prescaler value. The code is a bit long, so I post it at the end of the answer. Basically:
// pre-scalor analysis using 5 channels;
// quantities indicated are sampling frequency of the 5 channels
// i.e. necessary ADC sampling frequency is 5 x higher, and value
// of the prescaler ps
// --------------------
// 100kHz ps 1 ok
// 100kHz ps 2 ok
// 100kHz ps 3 fail
// 100kHz ps 255 fail
// 100kHz ps 256 ok
// this indicates: prescaler is 8 bits from 0 to 255, after this wraps up
// ADC frequency is max something like 1MHz in practice: 5 * 100 * 2 (may loose a bit
// due to other interrupts hitting ours?)
// --------------------
// 10kHz ps 38 ok
// 10kHz ps 39 fail
// 10 * 5 * 40 = 2000kHz: ADC is lower than 2MHz
// --------------------
// 1kHz ps 255 ok
// --------------------
I think this indicates that:
the pre-scaler value is well an 8 bits int, between 0 and 255, as it wraps up at 256
I have difficultie matching the results to the formula in the datasheet. I guess this is because there is some overhead switching channels etc (?). For example:
the results are consistent with ```ADC_freq = 1MHz / ( ps ) at the highest frequencies, but I suppose this is because there is a bit of overhead switching channels
the results are consistent with ```ADC_freq = 2MHz / ( ps ) at 10 kHz, and at 1kHz, even using the highest prescaler is fine.
The code I was using is the following, and the criterion for deciding that things fail is that the code reports a drop in the effective sample frequency over the 5 channels:
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// timer driven ADC convertion captured by interrupt on n adc_channels for Arduino Due
//
// this is for Arduino Due only!
//
// the interrupt based ADC measurement is adapted from:
// https://forum.arduino.cc/index.php?topic=589213.0
// i.e. adc_setup(), tc_setup(), ADC_handler() are inspired from the discussion there.
//
// written with VSCode + Platformio and Due board setup
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// make my linter happy
#include "Arduino.h"
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
// some vital ADC grabbing setup
// sample rate in Hz, should be able to go up to several 10s ok kHz at least
constexpr int adc_sample_rate = 1000;
// size of the data buffers "in time"
// i.e. how many consecutive measurements we buffer for each channel
constexpr size_t adc_buffer_nbr_consec_meas = 5;
// the adc_channels to read, in uC reference, NOT in Arduino Due pinout reference
// for a mapping, see: https://components101.com/microcontrollers/arduino-due
// i.e. A0 is AD7
// A1 AD6
// A2 AD5
// A3 AD4
// A4 AD3
// A5 AD2
// A6 AD1
// A7 AD0
constexpr uint8_t adc_channels[] = {7, 6, 5, 4, 3};
constexpr int nbr_adc_channels = sizeof(adc_channels);
// the buffer containing the measurements for all adc_channels over several measurements in time
volatile uint16_t adc_meas_buffer[adc_buffer_nbr_consec_meas][nbr_adc_channels];
// flag when a full vector of conversions is available
volatile bool adc_flag_conversion = false;
// time index of the current measurement in the adc reads buffer
volatile size_t crrt_adc_meas_buffer_idx = 0;
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
// some non-vital printing config
// a bit of time tracking, just to analyze how good performance
unsigned long current_us = 0;
unsigned long previous_us = 0;
unsigned long delta_us = 0;
float delta_us_as_s = 0;
float delta_us_as_ms = 0;
int nbr_readings_since_reduced_time_stats = 0;
unsigned long current_reduced_time_stats_us = 0;
unsigned long previous_reduced_time_stats_us = 0;
float delta_reduced_time_stats_us_as_s = 0;
float effective_logging_frequency = 0;
// decide what to print on serial
constexpr bool print_reduced_time_stats = true;
constexpr bool print_time_stats = false;
constexpr bool print_full_buffer = false;
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
// low level functions for setting clock and ADC
// start ADC conversion on rising edge on time counter 0 channel 2
// perform ADC conversion on several adc_channels in a row one after the other
// report finished conversion using ADC interrupt
// tests about pre-scaler: formula should be:
// pre-scalor analysis using 5 channels;
// quantities indicated are sampling frequency of the 5 channels
// i.e. necessary ADC sampling frequency is 5 x higher, and value
// of the prescaler ps
// --------------------
// 100kHz ps 1 ok
// 100kHz ps 2 ok
// 100kHz ps 3 fail
// 100kHz ps 255 fail
// 100kHz ps 256 ok
// this indicates: prescaler is 8 bits from 0 to 255, after this wraps up
// ADC frequency is max something like 1MHz in practice: 5 * 100 * 2 (may loose a bit
// due to other interrupts hitting ours?)
// --------------------
// 10kHz ps 38 ok
// 10kHz ps 39 fail
// 10 * 5 * 40 = 2000kHz: ADC is lower than 2MHz
// --------------------
// 1kHz ps 255 ok
// --------------------
// CCL: use ps 2 at 100kHz with 5 channels, 20 at 10kHz, 200 at 1kHz
void adc_setup()
{
PMC->PMC_PCER1 |= PMC_PCER1_PID37; // ADC power on
ADC->ADC_CR = ADC_CR_SWRST; // Reset ADC
ADC->ADC_MR |= ADC_MR_TRGEN_EN | // Hardware trigger select
ADC_MR_PRESCAL(200) | // the pre-scaler: as high as possible for better accuracy, while still fast enough to measure everything
// see: https://arduino.stackexchange.com/questions/12723/how-to-slow-adc-clock-speed-to-1mhz-on-arduino-due
// unclear, asked: https://stackoverflow.com/questions/64243073/setting-right-adc-prescaler-on-the-arduino-due-in-timer-and-interrupt-driven-mul
ADC_MR_TRGSEL_ADC_TRIG3; // Trigger by TIOA2 Rising edge
ADC->ADC_IDR = ~(0ul);
ADC->ADC_CHDR = ~(0ul);
for (int i = 0; i < nbr_adc_channels; i++)
{
ADC->ADC_CHER |= ADC_CHER_CH0 << adc_channels[i];
}
ADC->ADC_IER |= ADC_IER_EOC0 << adc_channels[nbr_adc_channels - 1];
ADC->ADC_PTCR |= ADC_PTCR_RXTDIS | ADC_PTCR_TXTDIS; // Disable PDC DMA
NVIC_EnableIRQ(ADC_IRQn); // Enable ADC interrupt
}
// use time counter 0 channel 2 to generate the ADC start of conversion signal
// i.e. this sets a rising edge with the right frequency for triggering ADC conversions corresponding to adc_sample_rate
// for more information about the timers: https://github.com/ivanseidel/DueTimer/blob/master/TimerCounter.md
// NOTE: TIOA2 should not be available on any due pin https://github.com/ivanseidel/DueTimer/issues/11
void tc_setup()
{
PMC->PMC_PCER0 |= PMC_PCER0_PID29; // TC2 power ON : Timer Counter 0 channel 2 IS TC2
TC0->TC_CHANNEL[2].TC_CMR = TC_CMR_TCCLKS_TIMER_CLOCK2 // clock 2 has frequency MCK/8, clk on rising edge
| TC_CMR_WAVE // Waveform mode
| TC_CMR_WAVSEL_UP_RC // UP mode with automatic trigger on RC Compare
| TC_CMR_ACPA_CLEAR // Clear TIOA2 on RA compare match
| TC_CMR_ACPC_SET; // Set TIOA2 on RC compare match
constexpr int ticks_per_sample = F_CPU / 8 / adc_sample_rate; // F_CPU / 8 is the timer clock frequency, see MCK/8 setup
constexpr int ticks_duty_cycle = ticks_per_sample / 2; // duty rate up vs down ticks over timer cycle; use 50%
TC0->TC_CHANNEL[2].TC_RC = ticks_per_sample;
TC0->TC_CHANNEL[2].TC_RA = ticks_duty_cycle;
TC0->TC_CHANNEL[2].TC_CCR = TC_CCR_SWTRG | TC_CCR_CLKEN; // Software trigger TC2 counter and enable
}
// ISR for the ADC ready readout interrupt
// push the current ADC data on all adc_channels to the buffer
// update the time index
// set flag conversion ready
void ADC_Handler()
{
for (size_t i = 0; i < nbr_adc_channels; i++)
{
adc_meas_buffer[crrt_adc_meas_buffer_idx][i] = static_cast<volatile uint16_t>(*(ADC->ADC_CDR + adc_channels[i]) & 0x0FFFF);
}
crrt_adc_meas_buffer_idx = (crrt_adc_meas_buffer_idx + 1) % adc_buffer_nbr_consec_meas;
adc_flag_conversion = true;
}
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
// a simple script: setup and print information
void setup()
{
Serial.begin(115200);
delay(100);
adc_setup();
tc_setup();
}
void loop()
{
if (adc_flag_conversion == true)
{
adc_flag_conversion = false;
if (print_reduced_time_stats)
{
nbr_readings_since_reduced_time_stats += 1;
if (nbr_readings_since_reduced_time_stats == adc_sample_rate)
{
current_reduced_time_stats_us = micros();
delta_reduced_time_stats_us_as_s = static_cast<float>(current_reduced_time_stats_us - previous_reduced_time_stats_us) / 1000000.0;
effective_logging_frequency = static_cast<float>(adc_sample_rate) / delta_reduced_time_stats_us_as_s;
previous_reduced_time_stats_us = current_reduced_time_stats_us;
Serial.print(F("Effective logging freq over nbr spls that should correspond to 1 second: "));
Serial.println(effective_logging_frequency);
nbr_readings_since_reduced_time_stats = 0;
}
}
if (print_time_stats)
{
current_us = micros();
delta_us = current_us - previous_us;
delta_us_as_s = static_cast<float>(delta_us) / 1000000.0;
delta_us_as_ms = static_cast<float>(delta_us) / 1000.0;
Serial.println(F("ADC avail at uS"));
Serial.println(micros());
Serial.println(F("elapsed us"));
Serial.println(delta_us);
Serial.println(F("elapsed ms"));
Serial.println(delta_us_as_ms);
Serial.println(F("elapsed s"));
Serial.println(delta_us_as_s);
Serial.println(F("updated idx:"));
size_t last_modified_buffer_idx;
if (crrt_adc_meas_buffer_idx > 0){
last_modified_buffer_idx = crrt_adc_meas_buffer_idx - 1;
}
else{
last_modified_buffer_idx = nbr_adc_channels - 1;
}
Serial.println(last_modified_buffer_idx);
previous_us = current_us;
}
if (print_full_buffer)
{
for (size_t i = 0; i < nbr_adc_channels; i++)
{
Serial.print(F(" ADC "));
Serial.print(adc_channels[i]);
Serial.println(F(" meas in time:"));
for (size_t j = 0; j < adc_buffer_nbr_consec_meas; j++)
{
Serial.print(adc_meas_buffer[j][i]);
Serial.print(F(" "));
}
Serial.println();
}
}
}
}

Arduino timer4 custom PWM issue

I made a nice code which generates fast PWM with 50% duty cycle and I can change the frequency with a potentiometer. It outputs straight and inverted channels with some dead time. I am using Arduino Micro aka ATmega32U4. The code is actually "Atmel" code. Code is working fine until I power Arduino Micro off and then on again.
I have programmed the code and registers so that the frequency is changeable from 10kHz to 100kHz. But after power on/off the frequency changes from 5kHz to 50kHz. After this has happened I have to program the board again using Arduino IDE, to make it work correctly. Again after power on/off it has changed. I am quite sure that one of the registers is overwritten by the "Arduino hardware abstraction layer" or however we should name it. I have not yet read out all the registers so I do not know which one is overwritten. I guess it's the prescaler.
How do I prevent this from happening? Should I write the register contents somewhere else? Or should I write it few times to be sure?
Why or how this is happening anyway?
Here's the code:
#define OSC1 5
#define OSC2 13
uint8_t read_reg1;
uint8_t read_reg2;
int pot, freq;
void setup() {
pinMode(OSC1, OUTPUT);
pinMode(OSC2, OUTPUT);
Serial.begin(9600);
cli(); // disable global interrupts
TCCR4A=0; // clear register
TCCR4B=0x06; // configure prescaler to 64 (CK = CLK / 64 = 1.5 MHz)
TCCR4C=0;
TCCR4D=0; // select Fast PWM operation (0 << WGM41)|(0 << WGM40)
PLLFRQ=(PLLFRQ&0xCF)|0x30; // select clock source and frequency
OCR4C=150; // select PWM frequency
OCR4A=150/2; // set duty cycle
DT4 = 0x55; // set dead times. DT = (1 / 48Mhz) * 0...15
// enable interrupt on timer4 overflow
TIMSK4|=(1 << TOIE4);
// This register write has to be after others. Otherwise the PWM generation will not work. I do not know why.
TCCR4A=0x42; // COM4A1..0 = 01, OC4A and !OC4A connected. PWM4A = 1 (activate channel A PWM output)
sei(); // enable global interrupts
}
void loop() {
//cli();
pot = analogRead(A0);
freq = map(pot, 0, 1023, 14, 166);
//sei();
/*
Serial.print("Pot value: ");
Serial.print(pot);
Serial.print("\tFreq value: ");
Serial.println(1500000/freq);
*/
}
ISR(TIMER4_OVF_vect){
OCR4C = freq;
OCR4A = freq / 2;
}
I am not sure exactly why you got different behavior right after programming, but the bootloader that the Arduino Micro uses (Caterina) does not perform a full reset after it runs, so changes that the bootloader made to the AVR's registers are often visible to the user's sketch.
I was able to fix the problem by removing the line that modifies PLLFRQ. Here is a simplified version of your code that always produces 3.31 kHz PWM:
void setup()
{
pinMode(5, OUTPUT);
pinMode(13, OUTPUT);
TCCR4A = 0;
TCCR4B = 0x06; // configure prescaler to 64 (CK = CLK / 64 = 1.5 MHz)
TCCR4C = 0;
TCCR4D = 0; // select Fast PWM operation (0 << WGM41)|(0 << WGM40)
OCR4C = 150; // select PWM frequency
OCR4A = 150 / 2; // set duty cycle
DT4 = 0x55; // set dead times. DT = (1 / 48Mhz) * 0...15
// This register write has to be after others.
// Otherwise the PWM generation will not work. I do not know why.
// COM4A1..0 = 01, OC4A and !OC4A connected.
// PWM4A = 1 (activate channel A PWM output)
TCCR4A = 0x42;
}
void loop()
{
}
It's not a great idea to mess with the PLL postscaler since it will probably affect every other Arduino library that uses timers, including the USB stack.

RS485: Transmission issue from microcontroller

I have an issue related to "Transmission" from microcontroller. Microcontroller is able to receive, but unable to transmit.
this is an additional issue to my previously asked question [here]
Below is the max485 interface with microcontroller :
Here is my code snapshot :
// RS485
TRISBbits.TRISB6 = INPUT_PIN; // RX - RB6/RP38 PIN<42>
TRISBbits.TRISB7 = OUTPUT_PIN; // TX - RB7/RP39 PIN<43>
TRISBbits.TRISB8 = OUTPUT_PIN; // !RE/DE Control Pin RB8/RP40 PIN<44>
// RS485 Config
#define RS485_TX PORTBbits.RB6 // RS485 Transmitter
#define RS485_RX LATBbits.LATB7 // RS485 Reciever
#define RS485_CTRL LATBbits.LATB8 // RS485 Control Pin
// UART ISR
void __attribute__((interrupt, no_auto_psv)) _U4RXInterrupt(void)
{
rs485Char = U4RXREG;
RS485_CTRL = 1; // Enable driver
U4TXREG = rs485Char;
RS485_CTRL = 0; // disable driver RE/DO
}
void InitRs485(void){
// configure U1MODE
U4MODEbits.UARTEN = 0; // Bit15 TX, RX DISABLED, ENABLE at end of func
U4MODEbits.URXINV = 1; // 1:URXINV Idle state is '0' ; 0=UxRX Idle state is '1';
U4MODEbits.ABAUD = 0; // Bit5 No Auto baud (would require sending '55')
U4MODEbits.BRGH = 0; // Bit3 16 clocks per bit period
U4MODEbits.PDSEL = 0; // 0 : 8 bit,no parity; 1 : 8 bit,even parity; 2 : 8 bit,odd parity; 3 : 9 bit,no Parity
U4MODEbits.STSEL = 1; // 1 : 2 Stop bits; 0 : 1 Stop bits
U4MODEbits.LPBACK = 0; // Lookback disable
U4STAbits.URXISEL = 0; // Interrupt flag bit is set when a character is received
// Load a value into Baud Rate Generator.
U4BRG = BRGVAL_RS485; // 60Mhz osc, 9600 Baud
// Load all values in for U1STA SFR
U4STAbits.UTXISEL1 = 0; // Bit15 Int when Char is transferred (1/2 config!)
U4STAbits.UTXISEL0 = 0; // Bit13 Other half of Bit15
U4STAbits.UTXINV = 1; // 1:UxTX Idle state is '0' ; 0=UxTX Idle state is '1';
U4STAbits.UTXBRK = 0; // Bit11 Disabled
U4STAbits.UTXEN = 0; // Bit10 TX pins controlled by peripheral
U4STAbits.URXISEL = 0; // Bits6,7 Int. on character received
IPC22bits.U4RXIP = 7;
IPC22bits.U4TXIP = 7;
IFS5bits.U4TXIF = 0; // Clear the Transmit Interrupt Flag
IEC5bits.U4TXIE = 0; // Enable Transmit Interrupts
IFS5bits.U4RXIF = 0; // Clear the Receive Interrupt Flag
IEC5bits.U4RXIE = 0; // Enable Receive Interrupts
RPOR2bits.RP39R = 0x1D; // dsPic33EP512GM604 => RP39 as U4TX PIN<43>
_U4RXR = 38; // dsPic33EP512GM604 => RP38 as U4RX PIN<42>
U4MODEbits.UARTEN = 1; // And turn the peripheral on
U4STAbits.UTXEN = 1;
// Hardware control bits
IEC5bits.U4RXIE = 1;
IFS5bits.U4RXIF = 0;
RS485_CTRL = 0; // disable driver; Receive Enable
}
In above code, I have a UART Receive Interrupt routine.
Whenever any character is received, UART ISR receives it, but unable to transmit anything back.
In my ISR, I am trying to send back the character received.
This issue might be related to the max485 control pins (!RE/DE), which is referred as RS485_CTRL in my code.
So, I tried to rectify the issue as below :
If ISR is written as
rs485Char = U4RXREG;
RS485_CTRL = 1; // Enable driver
U4TXREG = rs485Char;
then microcontroller transmit 2Bytes, first one is the character recieved, second byte is a false byte ie.0x00.Thereafter no character is received by the ISR.
If ISR is written as :
rs485Char = U4RXREG;
RS485_CTRL = 0; // Disable driver
U4TXREG = rs485Char;
RS485_CTRL = 1; // Enable driver
than it transmit a first character recieved. But there after ISR gets into infinite loop ie. receives a NULL character and transmits a NULL character.
As per the RS485 implementation rules,
RS485_CTRL (!RE/DE) should be 0 to receive data
RS485_CTRL (!RE/DE) should be 1 to transmit data.
My microcontroller is acting as a SLAVE, so by default I have kept it into listening mode. But when data is received I am unable to transmit.
Pls help me get my mistake identified ???
As per the suggestion given by #linuxfan, Correct ISR should be as below :
// UART ISR
void __attribute__((interrupt, no_auto_psv)) _U4RXInterrupt(void)
{
rs485Char = U4RXREG;
RS485_CTRL = 1; // Enable driver
U4TXREG = rs485Char;
while(!U4STAbits.TRMT); // wait until character is transffered successfully
RS485_CTRL = 0; // disable driver RE/DO
}
Now my code is working fine as expected.
The LTE-485 (RS-485 line driver) has a "driver enable pin" which must be asserted in order to transmit. You must assert it just before starting to send a character, and you must de-assert it after the last byte has finished transmission (you de-assert it in order to be able to receive data, or to let some other device to drive the bus. If you don't want to receive, and you don't have any other device willing to transmit, you can keep it asserted).
In your code there is:
RS485_CTRL = 1; // Enable driver
U4TXREG = rs485Char;
You enable the driver with RS485_CTRL=1, then you load the UART shift register, but perhaps you don't wait the time all the data is shifted out.
In order to wait for the data to shift out, you can load a timer which will fire after a fixed time: the time a character, 10 bits probably, takes to be shifted out at the baud rate you programmed. Each time you transmit a character, start this timer. When the timer expires, disable the OE (output driver enable).
Another way is to wait for the reception of the character you just sent out. You load the transmit register; when all the bits are shifted out, you will receive the character (RS-485 is a bus). At that time, you can disable the transmitter if you want. Of course, this is not very good if you want to transmit a stream of characters back-to-back. Moreover, in your hardware setup you can't do that because you disable the receiver (the receiver enable and driver enable are shorted together).
But you can do what I think is the best. When you transmit a char, enable the driver of the interface OE; then use the TX interrupt of your UART to transmit the next character (if any), or de-assert the driver if there is nothing more to transmit. Beware to use the right transmitting interrupt: some UART (I don't know the one you are using) has buffering - you need the interrupt that fires when the datum has shifted out, not the one which says "you can load more data".
NOTE ASIDE: you are using a DB9 connector, using the pins 2 and 3, and labelling them TX and RX. Well, there is NO TX and RX wires in the RS-485: the two wires are named A and B, and both carry the same, balanced signal. These wires are used to receive data, when left floating, and the same wires are used to transmit data, if driven by the LTC-485 driver. You can very well enable the transmitting driver and keep to "listen" on the wires. You will receive back what you just transmitted (and this can also diagnose that the wires are shorted or the driver is blown). You can choose to use a connector often used for RS-232, and you can also choose to use the same pins 2 and 3 as the RS-232, but in no way an RS-485 can be assimilated to an RS-232.

Using Atmega TCNT1

I'm trying to use an arduino uno to show some students how to make their own 'auto tune' however the code that I wrote is not outputting any signal. The goal is to sample values into an array at one rate and output the data from the array(FIFO)at a slower rate. My understanding is that TCNT1 increments each clock tick, I'm using 16 MHz in my case, and that I can base if logic on the value of TCNT1, I use a mod function here to take and store a single adc value and then play that value to the dac at a later time. acdT dacT represent my timing logic. I've built an external DAC to read only 8 (of 10) bit values from d0-d7 (PORTD). Why am I not seeing a signal?
int i = 0;
int j = 0;
int adcT = 328; // 329 clock tics
int dacT = 349; // 350 clock tics
int buff[15]; // 16 length buffer to store adc values
void setup ()
{
PRR &= ~(1<<PRADC); //ADC turned on
ADMUX = 0x60; //AVcc, left adjusted, ADC0 pin
ADCSRA = 0xC0;//ADC Enabled, no auto trigger
DDRD=0xFF; // set portd to d0 thru d7 digital pins
DDRC=0x00; // accept input from any analog input
TCCR1B |= 1<<CS10; // sets the clock to the system clock ie no pre scaler
}
void loop ()
{
if((TCNT1%acdT == 0) || TCNT1 == 0) // execute at 0 and mod329 clock tics
{
ADCSRA|=(1<<ADSC); // take one adc reading
while(!(ADCSRA & (1<<ADIF))); // wait until the reading is complete
ADCSRA|=(1<<ADIF); //reset adc for next command
buff[i] = ADCH; // take the adc value into the array
i++ // increment
}
if((TCNT1%dacT == 0)) %% TCNT1 ~= 0// execute at mod350 clock tics
{
PORTD = buff[j]; // send the adc reading to digital output
j++;
}
if(TCNT1 == 5262 ) // LCM/3 of 329(16samples) and 350(15samples)
{
TCNT1 = 0;// reset ticker
i = 0;
j = 0;
}
if(TCNT1 == 336)
{
PORTD = buff[15]; // play 16th adc sample to clear array
}
}
TCCR1B |= 1<<CS10; // sets the clock to the system clock ie no pre scaler
And there's your problem. You're attempting to find the modulus of a counter that runs faster than your code. Use the output capture and other features of the timer to trigger interrupts and reset the timer at the appropriate times instead of trying to catch a passing bullet with your bare hands.

Reading Soft_Uart & Hardware Uart # same time

OK, so i have accomplished creating a software and hardware UART on PIC18f8680 in MikroC compiler. The Soft_Uart uses timer0 for interrupt and breaks the Soft_UART_read() line by a function called Soft_uart_Break().
everything is working fine, when i read a single character from both uart. but when i send a string on hardware uart, the string doesn't gets reads properly by these lines;
UART1_Read_Text(buffer, "OK", 100);
UART1_Write_Text(buffer);
I've found out whats causing this problem. that is, my main while loop gets stuck in Soft_UART_read() until it gets break by an interrupt. while its stuck over there, the hardware uart doesn't gets proper time to read the whole string, so as a result it displays some of the characters of that string.
how can i overcome this ? do i need to use a separate interrupt for hardware uart aswel ? or what ? any help would be highly appreciated.
here is a snip of my code;
void main() {
INTCON.GIE=1; //globle interrupt enable
INTCON.PEIE=1; //peripharel interrupt enable
INTCON.TMR0IF = 0x0; //Clear timer0 overflow interrupt flag
INTCON.TMR0IE = 1; //enable the timer0 by setting TRM0IE flag
T0CON.TMR0ON = 1; // Timer0 On/Off Control bit: 1=Enables Timer0 / 0=Stops Timer0
T0CON.T08BIT = 0; // Timer0 8-bit/16-bit Control bit: 1=8-bit timer/counter / 0=16-bit timer/counter
T0CON.T0CS = 0; // TMR0 Clock Source Select bit: 0=Internal Clock (CLKO) / 1=Transition on T0CKI pin
T0CON.T0SE = 0; // TMR0 Source Edge Select bit: 0=low/high / 1=high/low
T0CON.PSA = 1; // Prescaler Assignment bit: 0=Prescaler is assigned; 1=NOT assigned/bypassed
T0CON.T0PS2 = 0; // bits 2-0 PS2:PS0: Prescaler Select bits
T0CON.T0PS1 = 1;
T0CON.T0PS0 = 1;
TMR0H = 0xBD; // preset for Timer0 MSB register
TMR0L = 0xCD; // preset for Timer0 LSB register
while(1) {
data1 = Soft_UART_Read(&error);
Soft_UART_Write(data1);
if (data1 == 'b') {
for(x = 0; x <= strlen(alive); x++) {
Soft_UART_Write(alive[x]);
}
}
if (UART1_Data_Ready()) { // If data is received,
UART1_Read_Text(buffer, "OK", 100); // reads text until 'OK' is found
UART1_Write_Text(buffer); // sends back text
/*if (uart_rd == 'a') {
UART1_Write_Text("\rSensor 1 data\r");
}*/
//else
//UART1_Write(uart_rd); // and send data via UART
}
}
}
I had the same issue. Some of the example code and documentation in the MikroC manual seems to contradict itself.
The prototype is:
void UARTx_Read_Text(char *Output, char *Delimiter, char Attempts);
Your delimiter should be:
char delimit[] = "OK";
UART1_Read_Text(&dataIn,&delimit,attempts);
If you know the size of the data being received attempts should correspond to this.

Resources