First ,thanks for the good suggestion from artless noise.
I choose sharing 3G - 4G-1 kernel space address with usr task (vaddr : 0 - 4G) to switch tasks.
I think tasks switching would be like this :
a clock interrupt comes when usr task is running in its own address space
branch to the 3G of usr address space (also it is kernel 3G space).
context saving
schedule ()
{
....
switch_ttb_base (ttb_base); // I think it is the key,(taskA --> TaskB)
// when ttb_base switched,address space is changed,
// it looks like TaskB is interrupted && arrives here.
// So,after context restored,it would return to TaskB
// which looks like TaskB is interrupted just now !
....
}
context restoring
branch to new usr task
So,to share the kernel 3G address ,I should copy the page_tbls from kernel 3G address to usr page_tbls.
Here is my code, (ARM920T,S3C2440)
#define INIT_L1_BASE (0x30100000) /* 16K */
#define INIT_L2_BASE (0x30104000) /* 64k */
#define KERNEL_IMG_SIZE (0x20000) /* 128 K */
#define KERNEL_CODE_START (0xC0000000) /* 3G start */
#define TTB_BASE (0x30000000)
#define PAGE_DIR (TTB_BASE)
#define TTB_FULL_SIZE (0x4000) /* 16K */
#define PAGE_TABLE (TTB_BASE+TTB_FULL_SIZE)
#define PAGE_DIR_SIZE (0x4000) /* 16k */
#define PAGE_TBL_SIZE (0x10000) /* 64K */
void copy_kernel_page_tbls (unsigned dest_ttb,unsigned vaddr,unsigned size)
{
if ((size & 0xFFFFF) || (vaddr & 0xFFFFF)) /* 1M alignment */
panic ( "trying to copy page tables with non-1M alignment !\n" );
volatile unsigned *_from_page_dir,*_to_page_dir;
_from_page_dir = (volatile unsigned *)(TTB_BASE);
_to_page_dir = (volatile unsigned *)dest_ttb;
unsigned l1_idx;
unsigned i = 0,j = 0,k = 0,page;
volatile unsigned *_to_page_tbl,*_from_page_tbl;
for (k = 0 ,size >>= 20 ; k < size ; k ++,vaddr += 0x100000 )
{
l1_idx = vaddr>>20;
if ( !(_from_page_dir[l1_idx] & ~0x3FF))
continue;
if ( !(_to_page_dir[l1_idx] & ~0x3FF) ) { /* if dest page dir unit is empty */
i = l1_idx & ~3;
if ((_to_page_dir[i+0] & ~0x3FF) || (_to_page_dir[i+1] & ~0x3FF)
|| (_to_page_dir[i+2] & ~0x3FF) || (_to_page_dir[i+3] & ~0x3FF) )
{
panic ( "page dir corrupts with l1_idx %d !\n",l1_idx );
}
if (!(page = find_free_page ()))
panic ( "no more free page !\n" ); /* alloc a page page dir*/
wordset ((void*)page,AP_FAULT_ALL|CB|TTB1_SPG,0x1000); /* set all be fault */
_to_page_dir[i+0] = (page + 0x000)|DOMAIN_SYS|TTB0_COARSE; /* small page 1st 1KB */
_to_page_dir[i+1] = (page + 0x400)|DOMAIN_SYS|TTB0_COARSE; /* small page 2nd 1KB */
_to_page_dir[i+2] = (page + 0x800)|DOMAIN_SYS|TTB0_COARSE; /* small page 3rd 1KB */
_to_page_dir[i+3] = (page + 0xC00)|DOMAIN_SYS|TTB0_COARSE; /* small page 4th 1KB */
}
_from_page_tbl = (volatile unsigned*)(_from_page_dir[l1_idx] & ~(0x3FF));
_to_page_tbl = (volatile unsigned*)(_to_page_dir[l1_idx] & ~(0x3FF));
/* continue copying .... */
for (j = 0 ; j < 256 ; j++ ) { /* 256 * 4K */
if (_from_page_tbl[j] & ~0xFFF)
_to_page_tbl[j] = _from_page_tbl[j]; /* FIXME : change attribute */
}
}
}
I call it like this
copy_kernel_page_tbls (INIT_L1_BASE,KERNEL_CODE_START,1<<30); /* 1G size */
the clock handler is
extern unsigned long __ticks;
#define __DEBUG__
static
void schedlue ( void )
{
// ..............
sync_dcaches ();
invalidate_icaches ();
invalidate_dcaches ();
invalidate_tlbs();
set_ttb_base(current_p->ttb_base);
}
void __do_timer0 (void)
{
static unsigned i = 0;
++ i;
current_p = task_st[i & 1]; /* just 2 tasks */
__ticks ++;
.....
.....
schedule ();
}
ARM just halt.I don't know why ? Any help appreciated !
I did a mmu test to test mmu cache operations
I switch ttb base with :
void change_ttb_base (unsigned ttb)
{
sync_dcaches ();
invalidate_icache ();
invalidate_dcaches ();
set_ttb_base (ttb);
invalidate_tlbs ();
}
on my s3c2440 board ,0x30000000 - 0x34000000 is the sdram address,I do the test on sdram address space,
ttb_base switched successfully!
but when the code run at the high 3G address ,after I called change_ttb_base (),ARM just halt.I guess,the code running in high 3G address need MMU address translation,I changed ttb_base and invalidate all i & d cache and tlbs ,so ARM core don't know what the next step is ,so just halt .....
Is that right ???
Related
I am a beginner with PIC microcontrollers and trying to learn through tutorials and simultaneously implement a project for which I need to program a PIC microcontroller. I have tried 3 different programs for UART transmission found on various tutorials and I am still having the same issue.
When I try to transmit a string, say "abcd", I only get adadadad.... on repeat. What might be the issue? I have checked the baud rates and it is correct. I have tried introducing delay but it doesnot help. Would greatly appreciate any suggestions. The UART transmission function is part of a frequency counter program that counts the frequency when it receives an interrupt and displays it on LCD. The value displayed on LCD is also to be transmitted via UART, but first I am trying to make it work for a random string "abcd". I am using proteus for simulations. Currently using the following functions for transmitting data string:
void UART_send_char(char bt)
{
while(!TXIF); // hold the program till TX buffer is free
TXREG = bt; //Load the transmitter buffer with the received value
}
void UART_send_string(char* st_pt)
{
while(*st_pt) //if there is a char
UART_send_char(*st_pt++); //process it as a byte data
}
Following is my main function:
void main() {
char op[12]; // Display string for ascii converted long.
char opdb[12]; // double buffer to stop flicker.
unsigned long freq = 0; // display frequency value to use.
unsigned short blinkc=0; // blink counter
int i,n,num;
unsigned char letter;
unsigned char test[]="abcd";
init_ports();
init_interrupts();
Lcd_Init ();
Lcd_Cmd ( _LCD_CLEAR );
Lcd_Cmd ( _LCD_CURSOR_OFF );
start_timer_count();
for(;;) {
if (update_LCD) {
INTCON.GIE = 0; // Disable All interrupts.
INTCON.PEIE = 0; // Disable All Extended interrupts.
freq = (st_TMR1L+(st_TMR1H<<8)+(st_TMR1_ovfl<<16));//*1000;
ltoa(freq, op, 10);
n=ltoa(freq, opdb, 10); // Build string in non display buffer
memcpy(op,opdb,n); // Copy digits
memset(&op[n],' ',12-n); // Blank the rest.
LCD_Out(1,1,"FREQ:");
LCD_Out(1,7,op);
UART_send_string("abcd"); //<-----------TRANSMISSION FUNCTION CALLED HERE
update_LCD=0;
TMR1_counter=0;
TMR0_counter=0;
start_timer_count();
}
if (toggle_LED) { // Also check for signal presence at TMR1.
blinkc=~blinkc;
if (blinkc==0) { setBit(PORTD,0); } else { resBit(PORTD,0); }
toggle_LED=0;
if (freq==0) {
for ( i=0;i<12;i++) { op[i]=' ';}
LCD_Out(1,7,op);
}
}
}
}
This is a complete, builds with MPLABX and XC8, application to show the PIC16F877A asynchronous UART working with the Microchip simulation tool:
/*
* File: main.c
* Author: dan1138
* Target: PIC16F877A
* Compiler: XC8 v2.32
* IDE: MPLABX v5.50
*
* Created on July 21, 2021, 1:29 PM
*
* PIC16F877A
* +----------:_:----------+
* VPP -> 1 : MCLR/VPP PGD/RB7 : 40 <> PGD
* <> 2 : RA0/AN0 PGC/RB6 : 39 <> PGC
* <> 3 : RA1/AN1 RB5 : 38 <>
* <> 4 : RA2/AN2 RB4 : 37 <>
* <> 5 : RA3/AN3 RB3 : 36 <>
* <> 6 : RA4 RB2 : 35 <>
* <> 7 : RA5/AN4 RB1 : 34 <>
* <> 8 : RE0/AN5 RB0 : 33 <>
* <> 9 : RE1/AN6 VDD : 32 <- 5v0
* <> 10 : RE2/AN7 VSS : 31 <- GND
* 5v0 -> 11 : VDD RD7 : 30 ->
* GND -> 12 : VSS RD6 : 29 ->
* 20.000MHz -> 13 : OSC1 RD5 : 28 ->
* 20.000MHz <- 14 : OSC2 RD4 : 27 ->
* <> 15 : RC0/SOSCO RX/DT/RC7 : 26 <>
* <> 16 : RC1/SOSCI TX/CK/RC6 : 25 <>
* <> 17 : RC2/CCP1 RC5 : 24 <>
* <> 18 : RC3/SCL SDA/RC4 : 23 <>
* <> 19 : RD0 RD3 : 22 <>
* <> 20 : RD1 RD2 : 21 <>
* +-----------------------:
* DIP-40
*
* Description:
*
* Unit test for the UART transmit output implementation.
*
* Test runs using the MPLABX v5.50 simulator.
*
* Read the Microchip documentation about how to setup the simulator to show UART output.
*
*/
#pragma config FOSC = HS /* Oscillator Selection bits (HS oscillator) */
#pragma config WDTE = OFF /* Watchdog Timer Enable bit (WDT disabled) */
#pragma config PWRTE = OFF /* Power-up Timer Enable bit (PWRT disabled) */
#pragma config BOREN = OFF /* Brown-out Reset Enable bit (BOR disabled) */
#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) */
/*
* Include defines for target specific Special Function Registers
*/
#include <xc.h>
/*
* Tell XC8 compiler what frequency this code sets for system oscillator
*/
#define _XTAL_FREQ 20000000UL
/*
* function to convert unsigned long to ASCII string
*/
void ultoa(void * str, unsigned long data, unsigned char radix)
{
char buffer[32];
char * outstr = 0;
unsigned char index;
unsigned char temp;
outstr = (char *)str;
if(outstr)
{
if((radix > 1) && (radix <= 16))
{
index = 0;
do
{
temp = data % radix;
data = data / radix;
temp = temp + '0';
if (temp > '9') temp = temp + ('A'-'9')-1;
buffer[index++] = temp;
} while (data);
do
{
*outstr++ = buffer[--index];
} while(index);
*outstr = 0;
}
}
}
/*
* Initialize UART
*/
void UART_Init(void)
{
/* Disable UART interrupts */
PIE1bits.TXIE = 0;
PIE1bits.RCIE = 0;
/* Turn off USART module */
RCSTA = 0;
TXSTA = 0;
SPBRG = (_XTAL_FREQ/(16UL * 9600UL) - 1);
TXSTAbits.BRGH = 1;
RCSTAbits.CREN = 1; /* Enable continuous receive */
TXSTAbits.TXEN = 1; /* Enables Transmission */
RCSTAbits.SPEN = 1; /* Enables Serial Port */
/*
* Flush UART receive buffer
*/
RCREG;
RCREG;
RCREG;
}
/*
* Send a character to serial interface
*/
void UART_Write(unsigned char data) {
while(!TRMT); /* Wait for buffer to be empty */
TXREG = data;
}
/*
* Send a string of characters to serial interface
*/
void UART_WriteString(char *pBuffer) {
if (pBuffer)
{
while(*pBuffer)
{
UART_Write(*pBuffer++);
}
}
}
/*
* Test if character is available from serial interface
*/
unsigned char UART_Data_Ready( void )
{
return (RCIF!=0?1:0);
}
/*
* Read a character from serial interface
* Returns a zero if successful.
* Returns non-zero on framing error or overrun error.
*/
unsigned char UART_Read(void *data)
{
unsigned char Result;
char * buffer = (char *)data;
Result = 0;
if (PIR1bits.RCIF)
{
unsigned char rxerr = 0;
if (RCSTAbits.OERR) {
rxerr = 1;
RCSTAbits.CREN = 0; /* reset receiver */
RCSTAbits.CREN = 1;
RCREG;
RCREG;
RCREG;
}
if (RCSTAbits.FERR) {
rxerr = 1;
RCREG; /* Discard character with framing error */
}
if (!rxerr) { /* No error detected during reception */
if(buffer) *buffer = RCREG;
Result = 1;
}
}
return Result;
}
/*
* Initialize this PIC
*/
void PIC_Init( void )
{
/* Disable all interrupt sources */
INTCON = 0;
PIE1 = 0;
PIE2 = 0;
/*
* Pull-ups off, INT edge low to high, WDT prescale 1:1
* TMR0 clock edge low to high, TMR0 clock = _XTAL_FREQ/4, TMR0 prescale 1:16
* TIMER0 will assert the overflow flag every 256*16 (4096)
* instruction cycles, with a 20MHz oscillator this is 0.8192 milliseconds.
*/
OPTION_REG = 0b11000011;
/* Make all GPIO pins digital */
CMCON = 0x07;
ADCON1 = 0x06;
}
/*
* Main application
*/
void main(void)
{
char output[40];
unsigned long Count;
/*
* Initialize application
*/
PIC_Init();
UART_Init();
UART_WriteString("PIC16F877A UART test build on " __DATE__ " at " __TIME__ "\r\n");
Count = 0;
/*
* Application process loop
*/
for(;;)
{
ultoa(output,Count,10);
UART_WriteString("Count: ");
UART_WriteString(output);
UART_WriteString("\r\n");
Count++;
}
/*
* Keep XC8 from whining about functions not being called
*/
UART_Data_Ready();
UART_Read(0);
}
I would expect this to work with your Proteus environment too.
It's on you to port this code to your project.
I'm having a strange behavior with the RTC on a stm32L476 with FreeRTOS.
It only reads the first time in RUN mode, RTC is working, because from run to run it saves the value of the internal register and is going up.
Also if I do DEBUG when I put breakpoint at stm32l4xx_hal_rtc.c at line 583:
tmpreg = (uint32_t)(hrtc->Instance->TR & RTC_TR_RESERVED_MASK);
*breakpoint* sTime->Hours = (uint8_t)((tmpreg & (RTC_TR_HT | RTC_TR_HU)) >> 16);
I can see the tmpreg and TR register how they update, and then when I click jump to next breakpoint witch is the same I saw the display updated.
So why it's not working when normal RUN?
Init code (cube MX generated):
void MX_RTC_Init(void)
{
RTC_TimeTypeDef sTime;
RTC_DateTypeDef sDate;
/**Initialize RTC Only
*/
hrtc.Instance = RTC;
hrtc.Init.HourFormat = RTC_HOURFORMAT_24;
hrtc.Init.AsynchPrediv = 127;
hrtc.Init.SynchPrediv = 255;
hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;
hrtc.Init.OutPutRemap = RTC_OUTPUT_REMAP_NONE;
hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
if (HAL_RTC_Init(&hrtc) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
/**Initialize RTC and set the Time and Date
*/
if(HAL_RTCEx_BKUPRead(&hrtc, RTC_BKP_DR0) != 0x32F2){
sTime.Hours = 0;
sTime.Minutes = 0;
sTime.Seconds = 0;
sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
sTime.StoreOperation = RTC_STOREOPERATION_RESET;
if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BIN) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
sDate.WeekDay = RTC_WEEKDAY_MONDAY;
sDate.Month = RTC_MONTH_JANUARY;
sDate.Date = 1;
sDate.Year = 0;
if (HAL_RTC_SetDate(&hrtc, &sDate, RTC_FORMAT_BIN) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
HAL_RTCEx_BKUPWrite(&hrtc,RTC_BKP_DR0,0x32F2);
}
}
void HAL_RTC_MspInit(RTC_HandleTypeDef* rtcHandle)
{
if(rtcHandle->Instance==RTC)
{
/* USER CODE BEGIN RTC_MspInit 0 */
/* USER CODE END RTC_MspInit 0 */
/* RTC clock enable */
__HAL_RCC_RTC_ENABLE();
/* USER CODE BEGIN RTC_MspInit 1 */
/* USER CODE END RTC_MspInit 1 */
}
}
task where clock is readed and printed all this task and functions are at the same menu.c:
void MenuTask(void const *argument){
for(;;){
/*
* Menus
*/
DrawMenu();
osDelay(100);
}
}
void DrawMenu(){
switch(menuTaskStatus){
/* Not important code */
case MENU_INFO:
menuInfoBar();
break;
}
}
I print on the LCD a bar with the clock in the middle
void menuInfoBar(){
//Clock
CheckClock();
if(updateNeeded.Clock){
DrawClock();
updateNeeded.Clock = 0;
}
}
Here is the problematic part, as you can see I have tried a wait for synchro but also didn't work. I have some doubts of how does this syncro and RTC reading works.
void CheckClock(){
RTC_TimeTypeDef timeVar;
// HAL_GPIO_TogglePin(LEDR_GPIO_Port, LEDR_Pin);
// if(HAL_RTC_WaitForSynchro(&hrtc) == HAL_OK){
while(HAL_RTC_GetTime(&hrtc,&timeVar,RTC_FORMAT_BIN)!= HAL_OK);
if(timeVar.Seconds != timeVarAnt.Seconds){
timeVarAnt.Minutes = timeVar.Minutes;
timeVarAnt.Hours = timeVar.Hours;
timeVarAnt.Seconds = timeVar.Seconds;
updateNeeded.Clock = 1;
}
// }
}
Here I only draw the clock on my display
void DrawClock(){
DISP_locate(49,0);
sprintf((char *)stringBuffer,"%02d:%02d:%02d",(int)timeVarAnt.Hours,(int)timeVarAnt.Minutes,(int)timeVarAnt.Seconds);
DISP_puts((char *)stringBuffer);
}
It's possible I can't read the RTC fast as 100ms?
some one could explain to me why is needed a syncronitzation? datasheet explains that if the clock is 7 time faster is ok, I'm using an 80Mhz APB1 clock
some tutorials and examples I've found the do the exact same I do, but they read on the main loop with osDelay() of many values. Is a problem using freeRTOS and reading from a task?
time has nothing to do I've tried with 5s delay and also don't works
Thanks
A little late may be but I ran into the same problem and it turns out that the HAL_GetTime(..) function has a quirk. HAL_RTC_GetDate() must be called after it to unlock the values.
You must call HAL_RTC_GetDate() after HAL_RTC_GetTime() to unlock the values
* in the higher-order calendar shadow registers to ensure consistency between the time and date values.
* Reading RTC current time locks the values in calendar shadow registers until current date is read.
This is written as a note in their documentation as well as in the source code of the RTC HAL driver.
Personally, I believe that ST's guys should've made a HAL_RTC_GetTimeAndDate() and spare us falling in this trap.
struct
{
unsigned TR;
}*rcc = (void *)0x56456546;
typedef struct
{
unsigned su :4;
unsigned st :2;
unsigned :1;
unsigned mu :4;
unsigned mt :2;
unsigned :1;
unsigned hu :4;
unsigned ht :2;
unsigned pm :1;
unsigned :9
}RCC_TR_T;
typedef struct
{
uint8_t seconds, minutes, hours, pm;
}TIME_T;
TIME_T *GetTime(TIME_T *time)
{
RCC_TR_T *tr = (RCC_TR_T *)&rcc -> TR;
time -> hours = tr -> hu + tr -> ht * 10;
time -> minutes = tr -> mu + tr -> mt * 10;
time -> seconds = tr -> su + tr -> st * 10;
time -> pm = tr -> pm;
return time;
}
This Answer don't answers why the ST "hal" don't works, but it solves what I need, that is using RTC.
This is my new CheckClock function:
void CheckClock(){
uint32_t tmpreg = (uint32_t) hrtc.Instance->TR;
/* Fill the structure fields with the read parameters */
timeVar.Hours = (uint8_t)((tmpreg & (RTC_TR_HT | RTC_TR_HU)) >> 16);
timeVar.Minutes = (uint8_t)((tmpreg & (RTC_TR_MNT | RTC_TR_MNU)) >>8);
timeVar.Seconds = (uint8_t)(tmpreg & (RTC_TR_ST | RTC_TR_SU));
if(timeVar.Seconds != timeVarAnt.Seconds){
HAL_GPIO_TogglePin(LEDR_GPIO_Port, LEDR_Pin);
timeVarAnt.Minutes = timeVar.Minutes;
timeVarAnt.Hours = timeVar.Hours;
timeVarAnt.Seconds = timeVar.Seconds;
updateNeeded.Clock = 1;
}
}
Thanks
EDIT 05/2018 :
void CheckClock(){
uint32_t tmpreg = (uint32_t) hrtc.Instance->TR;
timeVar.Hours = Bcd2ToByte((uint8_t)((tmpreg & (RTC_TR_HT | RTC_TR_HU)) >> 16));
timeVar.Minutes =Bcd2ToByte( (uint8_t)((tmpreg & (RTC_TR_MNT | RTC_TR_MNU)) >>8));
timeVar.Seconds =Bcd2ToByte( (uint8_t)(tmpreg & (RTC_TR_ST | RTC_TR_SU)));
if(timeVar.Seconds != timeVarAnt.Seconds){
timeVarAnt.Minutes = timeVar.Minutes;
timeVarAnt.Hours = timeVar.Hours;
timeVarAnt.Seconds = timeVar.Seconds;
IBS.updates.Clock = 1;
}
// }
}
//HAL_RTC_GetDate(&hrtc, &sDate, RTC_FORMAT_BIN);
char xsa[6];
char your_time[9];
sprintf(xsa,"%06x",(uint32_t)hrtc.Instance->TR);
sprintf((char*)your_time,"%c%c:%c%c:%c%c%c",xsa[0],xsa[1],xsa[2],xsa[3],xsa[4],xsa[5],'\0');
I'm trying to write a code for ADC DMA. In my perspective, I've initiated ADC correctly. But it doesn't work and it doesn't interrupt. What am I missing? I initiated ADC and Interrupt and I am willing to access data on the interrupt.
Here is my code:
void __irq ISR_adc(void)
{
volatile AT91PS_ADC pADC = AT91C_BASE_ADC;
unsigned int AdcStatus = AT91C_BASE_ADC->ADC_SR;
unsigned short* ADC_Ptr;
unsigned short* ADC_Ptr_Next;
printf("ADC is: %d\n",Buffer1[0]);
if(((AdcStatus & AT91C_ADC_RXBUFF) == AT91C_ADC_RXBUFF) &&
((AdcStatus & AT91C_ADC_ENDRX) == AT91C_ADC_ENDRX))
{//Both bit set when get the end of next buffer
pADC->ADC_RPR = (unsigned long) Buffer1; // Receive Pointer Register
pADC->ADC_RCR = AD_DATA_BUFFER_SIZE; // Receive Counter Register
pADC->ADC_RNPR = (unsigned long)0; // Receive Next Pointer Register
pADC->ADC_RNCR = 0 ; // Receive Next Counter Registe
}
else if((AdcStatus & AT91C_ADC_ENDRX) == AT91C_ADC_ENDRX)
{//ENDRX bit set when reach the end of buffer.
pADC->ADC_RNCR = AD_DATA_BUFFER_SIZE;
}
*AT91C_AIC_EOICR = 0; // end of interrupts
}
void Configure_AD(void)
{
int i;
volatile AT91PS_ADC pADC = AT91C_BASE_ADC; // create a pointer to USART0 structure
volatile AT91PS_AIC pAIC = AT91C_BASE_AIC; // pointer to AIC data structure
volatile AT91PS_PIO pPIO = AT91C_BASE_PIOA; // pointer to PIO data structure
volatile AT91PS_PMC pPMC = AT91C_BASE_PMC; // pointer to PMC data structure
#define AD_PRESCAL 1
#define AD_STARTUP 1
#define AD_SHTIM 2
// Enable peripheral clock
pPMC->PMC_PCER = 1 << AT91C_ID_ADC;
//Notice: After ADC_SR = 0xc000 after Reset;
pADC->ADC_CR = AT91C_ADC_SWRST; //Reset AD
//Rxternal trigger: TIOA2 output pulse; Get data using ISP.
pADC->ADC_MR = ((AD_SHTIM << 24) | (AD_STARTUP << 16) | (AD_PRESCAL <<8) | AT91C_ADC_TRGEN_EN | AT91C_ADC_TRGSEL_TIOA2);
pADC->ADC_CHER = AT91C_ADC_CH4; //channel 4 enable
//Configure PDC; Write Counter Register reset ADC_SR.
pADC->ADC_PTCR = AT91C_PDC_RXTDIS ;
pADC->ADC_RPR = (unsigned long)Buffer1; // Receive Pointer Register
pADC->ADC_RCR = AD_DATA_BUFFER_SIZE; // Receive Counter Register
pADC->ADC_RNPR = (unsigned long)0; // Receive Next Pointer Register
pADC-> ADC_RNCR = 0 ; // Receive Next Counter Register
pADC->ADC_PTCR = AT91C_PDC_RXTEN ; //Enable PDC
pADC->ADC_IER = AT91C_ADC_ENDRX | AT91C_ADC_RXBUFF; //enable interrupt on transfer complete
pAIC->AIC_IDCR = (1<<AT91C_ID_ADC);
pAIC->AIC_SVR[AT91C_ID_ADC] = (unsigned int)ISR_adc;
pAIC->AIC_SMR[AT91C_ID_ADC] = (AT91C_AIC_PRIOR_LOWEST | 0x4 );
pAIC->AIC_IECR = (1<<AT91C_ID_ADC);
}
I am not an expert c programmers and in the c code I m getting these kinds of errors. I got many and tried to sort them out but can not solve these. The code is as follows:
/*
* EEPROM.c
* interfacing microchip 24aa64f IC with atmel sam4e
*/
#include <asf.h>
#include "EEPROM_I2C.h"
#define DEVICE_ADDRESS 0x50 // 7-bit device identifier 0101000, (refer datasheet)
//#define EEPROM_NAME 24AA6F
#define I2C_FAST_MODE_SPEED 400000//TWI_BUS_CLOCK 400KHz
#define TWI_CLK_DIVIDER 2
#define TWI_CLK_DIV_MIN 7
#define TWI_CLK_CALC_ARGU 4
#define TWI_CLK_DIV_MAX 0xFF
/*************************** Main function ******************************/
int eeprom_main( void )
{
struct micro24 ptMicro24 ;
typedef struct twi_options twi_options_t;
typedef struct Twi_registers Twi;
char TxBuffer[128] ;
char RxBuffer[128] ;
int BufferIndex;
unsigned int PageCount;
unsigned int error = 0 ;
unsigned int i;
ptMicro24.PageSize = 32;
ptMicro24.NumOfPage = 128;
ptMicro24.EepromSize = 128*32;
ptMicro24.SlaveAddress = DEVICE_ADDRESS;
ptMicro24.EepromName = 64;
/***************************** CLOCK SETTINGS TO GET 400KHz **********************
* Set the I2C bus speed in conjunction with the clock frequency.
* param p_twi Pointer to a TWI instance.
* return value PASS\Fail New speed setting is accepted\rejected
**********************************************************************************/
uint32_t twi_set_speed(struct Twi_registers *Twi, uint32_t ul_speed, uint32_t ul_mck)
//uint32_t twi_set_speed(Twi *p_twi, uint32_t ul_speed, uint32_t ul_mck)
{
uint32_t ckdiv = 0; //clock divider is used to increase both TWCK high and low periods (16-18)
uint32_t c_lh_div; //CHDIV (0-7) and CLDIV (8-15)
if (ul_speed > I2C_FAST_MODE_SPEED) { //ul_speed is the desired I2C bus speed
return FAIL;
}
c_lh_div = ul_mck / (ul_speed * TWI_CLK_DIVIDER) - TWI_CLK_CALC_ARGU; //ul_mck main clock of the device
/* cldiv must fit in 8 bits, ckdiv must fit in 3 bits */
while ((c_lh_div > TWI_CLK_DIV_MAX) && (ckdiv < TWI_CLK_DIV_MIN))
{
ckdiv++; // Increase clock divider
c_lh_div /= TWI_CLK_DIVIDER; //Divide cldiv value
}
/* set clock waveform generator register */
Twi->TWI_CWGR =
TWI_CWGR_CLDIV(c_lh_div) | TWI_CWGR_CHDIV(c_lh_div) |
TWI_CWGR_CKDIV(ckdiv);
return PASS;
}
/************************************ Initialize TWI master mode ************************
* Set the control register TWI_CR by MSEN and SVDIS
* param p_opt Options for initializing the TWI module
* return TWI_SUCCESS if initialization is complete
* twi_options... structure contains clock speed, master clock, chip and smbus
*****************************************************************************************/
uint32_t twi_master_start(struct Twi_registers *Twi, struct twi_options_t *twi_options_t)
//uint32_t twi_master_start(Twi *p_twi, const twi_options_t *p_opt)
{
uint32_t status = TWI_SUCCESS; // status success return code is 0
// Enable master mode and disable slave mode in TWI_CR
Twi -> TWI_CR_START = TWI_CR_START;
Twi->TWI_CR_MSEN = TWI_CR_MSEN; // Set Master Enable bit
Twi->TWI_CR_SVDIS = TWI_CR_SVDIS; // Set Slave Disable bit
/* Select the speed */
//new//if (twi_set_speed(Twi->TWI_SR, twi_options_t->speed, twi_options_t->master_clk) == FAIL)
//if (twi_set_speed(Twi, twi_options_t->speed, twi_options_t->master_clk) == FAIL)
//{
//status = TWI_INVALID_ARGUMENT; /* The desired speed setting is rejected */
//}
if (twi_options_t->smbus == 0)
{
Twi->TWI_CR_QUICK == 0;
status = TWI_INVALID_ARGUMENT;
}
else
if (twi_options_t->smbus == 1)
{
Twi->TWI_CR_QUICK == 1;
status = TWI_SUCCESS;
}
return status;
}
/***************************** WriteByte Function ********************************
This function uses a two bytes internal address (IADR) along with
Internal word address of eeprom.
Return Value: None
***********************************************************************************/
void WriteByte (struct micro24 *ptMicro24, char Data2Write,
unsigned int Address)
//Data2Write is the data to be written n the eeprom
//struct <micro24 *ptMicro24> : Structure of Microchip 24AA Two-wire Eeprom
//unsigned int Address>: Address where to write
{
unsigned int WordAddress;
unsigned int SlaveAddress;
unsigned char p0=0;
TWI_CR_START ==1;
if (ptMicro24->EepromName == 64 )
{
if ( Address > 0xFFFF)
{
p0 = 1;
/* Mask the 17th bit to get the 16th LSB */
WordAddress = Address & 0xFFFF ;
SlaveAddress = ptMicro24->SlaveAddress + (p0<<16) ;
}
else {
SlaveAddress = ptMicro24->SlaveAddress ;
WordAddress = Address ;
}
}
TWI_CR_STOP ==1;
//TWI_WriteSingleIadr(TWI_IADR_IADR,SlaveAddress, WordAddress,
// TWI_MMR_IADRSZ_2_BYTE, &Data2Write); // declared as extern
// to write to internal address, utilizing internal address and master mode register
//}
/******************** Increase Speed Function *****************************
* TWI is accessed without calling TWI functions
/***************************************************************************/
int NumOfBytes, Count;
int status;
uint32_t Buffer;
/* Enable Master Mode of the TWI */
TWI_CR_MSEN == 1;
// Twi.TWI_CR_MSEN ==1;
//TWI_CR->TWI_CR_MSEN = TWI_CR_MSEN ;
/* Set the TWI Master Mode Register */
Twi->TWI_MMR = (SlaveAddress & (~TWI_MMR_MREAD) | (TWI_MMR_IADRSZ_2_BYTE));
/* Set the internal address to access the wanted page */
Twi -> TWI_IADR = WordAddress ;
/* Wait until TXRDY is high to transmit the next data */
status = TWI_SR_TXRDY;
while (!(status & TWI_SR_TXRDY))
status = TWI_SR_TXRDY;
/* Send the buffer to the page */
for (Count=0; Count < NumOfBytes ;Count++ )
{
Twi ->TWI_THR_TXDATA = Buffer++;
/* Wait until TXRDY is high to transmit the next data */
status = TWI_SR_TXRDY;
while (!(status & TWI_SR_TXRDY))
status = TWI_SR_TXRDY;
}
/* Wait for the Transmit complete is set */
status = TWI_SR_TXCOMP;
while (!(status & TWI_SR_TXCOMP))
status = TWI_SR_TXCOMP;
// add some wait function according to datasheet before sending the next data
// e.g: 10ms
// e.g: WaitMiliSecond (10);
}
/****************************** ReadByte Function **************************
This function uses a two bytes internal address (IADR) along with
Internal word address of eeprom.
Return Value: None
****************************************************************************/
char ReadByte (struct micro24 *ptMicro24,
unsigned int Address) //int Address to read
{
unsigned int WordAddress;
unsigned int SlaveAddress;
char Data2Read ;
unsigned char p0=0;
TWI_CR_START == 1;
//p_twi -> TWI_CR_START = TWI_CR_START;
if (ptMicro24->EepromName == 64)
{
if ( Address > 0xFFFF) {
p0 = 1;
// Mask the 17th bit to get the 16th LSB
WordAddress = Address & 0xFFFF ;
SlaveAddress = ptMicro24->SlaveAddress + (p0<<16) ;
}
else {
SlaveAddress = ptMicro24->SlaveAddress ;
WordAddress = Address ;
}
}
//TWI_ReadSingleIadr(TWI_IADR_IADR,SlaveAddress,WordAddress,
// TWI_MMR_IADRSZ_2_BYTE,&Data2Read);
// declared as extern
// to write to internal address, utilizing internal address and master mode register
return (Data2Read);
}
}
errors are:
(24,19): error: storage size of 'ptMicro24' isn't known
67,5): error: dereferencing pointer to incomplete type
Twi->TWI_CWGR =
error: expected identifier before '(' token
#define TWI_CR_START (0x1u << 0) /**< \brief (TWI_CR) Send a START Condition */
error: expected identifier before '(' token
#define TWI_CR_MSEN (0x1u << 2) /**< \brief (TWI_CR) TWI Master Mode Enabled */
error: expected identifier before '(' token
#define TWI_CR_SVDIS (0x1u << 5) /**< \brief (TWI_CR) TWI Slave Mode Disabled */
error: dereferencing pointer to incomplete type
if (twi_options_t->smbus == 0)
It seems missing the declaration of struct micro24, this may be the cause of first error: error: storage size of 'ptMicro24' isn't known.
The same for declaration of Twi_registers, that is causing other errors.
Either you forgot to declare these structs or to include an header file declaring them.
Hello I am learning how to use the Uart by using interrupts in Nios and I am not sure how to start. I have made it in polling, but I am not sure how to start using interrupts.
Any help would be appreciated
Here is my code
#include <stdio.h> // for NULL
#include <sys/alt_irq.h> // for irq support function
#include "system.h" // for QSYS defines
#include "nios_std_types.h" // for standard embedded types
#define JTAG_DATA_REG_OFFSET 0
#define JTAG_CNTRL_REG_OFFSET 1
#define JTAG_UART_WSPACE_MASK 0xFFFF0000
#define JTAG_UART_RV_BIT_MASK 0x00008000
#define JTAG_UART_DATA_MASK 0x000000FF
volatile uint32* uartDataRegPtr = (uint32*)JTAG_UART_0_BASE;
volatile uint32* uartCntrlRegPtr = ((uint32*)JTAG_UART_0_BASE +
JTAG_CNTRL_REG_OFFSET);
void uart_SendByte (uint8 byte);
void uart_SendString (uint8 * msg);
//uint32 uart_checkRecvBuffer (uint8 *byte);
uint32 done = FALSE;
void uart_SendString (uint8 * msg)
{
int i = 0;
while(msg[i] != '\0')
{
uart_SendByte(msg[i]);
i++;
}
} /* uart_SendString */
void uart_SendByte (uint8 byte)
{
uint32 WSPACE_Temp = *uartCntrlRegPtr;
while((WSPACE_Temp & JTAG_UART_WSPACE_MASK) == 0 )
{
WSPACE_Temp = *uartCntrlRegPtr;
}
*uartDataRegPtr = byte;
} /* uart_SendByte */
uint32 uart_checkRecvBuffer (uint8 *byte)
{
uint32 return_value;
uint32 DataReg = *uartDataRegPtr;
*byte = (uint8)(DataReg & JTAG_UART_DATA_MASK);
return_value = DataReg & JTAG_UART_RV_BIT_MASK;
return_value = return_value >> 15;
return return_value;
} /* uart_checkRecvBuffer */
void uart_RecvBufferIsr (void* context)
{
} /* uart_RecvBufferIsr */
int main(void)
{
uint8* test_msg = (uint8*)"This is a test message.\n";
//alt_ic_isr_register ( ); // used for 2nd part when interrupts are enabled
uart_SendString (test_msg);
uart_SendString ((uint8*)"Enter a '.' to exist the program\n\n");
while (!done)
{
uint8 character_from_uart;
if (uart_checkRecvBuffer(&character_from_uart))
{
uart_SendByte(character_from_uart);
}
// do nothing
} /* while */
uart_SendString((uint8*)"\n\nDetected '.'.\n");
uart_SendString((uint8*)"Program existing....\n");
return 0;
} /* main */
I am suppose to use the uart_RecvBufferIsr instead of uart_checkRecvBuffer. How can tackle this situation?
You will need to register your interrupt handler by using alt_ic_isr_register(), which will then be called when an interrupt is raised. Details can be found (including some sample code) in this NIOS II PDF document from Altera.
As far as modifying your code to use the interrupt, here is what I would do:
Remove uart_checkRecvBuffer();
Change uart_RecvBufferIsr() to something like (sorry no compiler here so can't check syntax/functioning):
volatile uint32 recv_flag = 0;
volatile uint8 recv_char;
void uart_RecvBufferIsr(void *context)
{
uint32 DataReg = *uartDataRegPtr;
recv_char = (uint8)(DataReg & JTAG_UART_DATA_MASK);
recv_flag = (DataReg & JTAG_UART_RV_BIT_MASK) >> 15;
}
The moral of the story with the code above is that you should keep your interrupts as short as possible and let anything that is not strictly necessary to be done outside (perhaps by simplifying the logic I used with the recv_char and recv_flag).
And then change your loop to something like:
while (!done)
{
if (recv_flag)
{
uart_SendByte(recv_byte);
recv_flag = 0;
}
}
Note that there could be issues with what I've done depending on the speed of your port - if characters are received too quickly for the "while" loop above to process them, you would be losing some characters.
Finally, note that I declared some variables as "volatile" to prevent the compiler from keeping them in registers for example in the while loop.
But hopefully this will get you going.