I'm trying to get started on a project using a PIC18F24J10. Attempting to use SDCC for this. At this point I've reduced my code to simply trying to nail down what is happening, as I've been seeing bizarre behavior for a while now and can't really proceed until I figure out what is going on. Not sure if this is my only problem at this point, but I have no idea why this is happening. Timer interrupt fires off, coupled with a #defined for loop causes LEDs on PORTC to blink maybe twice a second. If I just do a PORTC=0xFF and PORTC=0 this works fine. But it gets weird when I try to go much beyond that.
...
#define _RC0 31
#define _RC1 32
#define _RC2 33
#define _RC3 34
#define _RC4 35
#define _RC5 36
#define _RC6 37
#define _RC7 38
#define HI 1
#define LO 0
void why(unsigned char p, int z)
{
if(z == HI)
{
if(p == _RC0) PORTCbits.RC0 = 1;
else if(p == _RC1) PORTCbits.RC1 = 1;
else if(p == _RC2) PORTCbits.RC2 = 1;
else if(p == _RC3) PORTCbits.RC3 = 1;
else if(p == _RC4) PORTCbits.RC4 = 1;
else if(p == _RC5) PORTCbits.RC5 = 1;
else if(p == _RC6) PORTCbits.RC6 = 1;
else if(p == _RC7) PORTCbits.RC7 = 1;
}
else if(z == LO)
{
PORTC = 0b11110000;
}
else
{
PORTC = 0b10101010;
}
}
void timer_isr (void) __interrupt(1) __using (1)
{
TMR0H=0;
TMR0L=0;
why(_RC0, LO);
why(_RC1, LO);
why(_RC2, LO);
WAIT_CYCLES(5000);
why(_RC0, HI);
why(_RC1, HI);
why(_RC2, HI);
WAIT_CYCLES(5000);
}
void main(void)
{
WDTCONbits.SWDTE = 0;
WDTCONbits.SWDTEN = 0;
TRISC = 0b00000000;
PORTC=0b00000000;
INTCONbits.GIE = 1;
INTCONbits.PEIE = 1;
INTCONbits.TMR0IF = 0;
INTCONbits.TMR0IE = 1;
T0CONbits.T08BIT = 0;
T0CONbits.T0CS = 0;
T0CONbits.PSA = 1;
TMR0H = 0;
TMR0L = 0;
T0CONbits.TMR0ON = 1;
while(1)
{
}
}
In the code above, four of the LEDs should blink, while the other four stay on. Instead, the LEDs stay on in the 10101010 pattern that happens in the "else" block, which should happen when "why" is called with any value other than HI or LO. I never call it with anything else, so why does it ever reach that?
UPDATE - Further reduction, no more interrupts or unspecified includes/defines. This is now the entirety of the program, and I am still seeing the same behavior. Changed the pattern from 10101010 to 10101011 so that I could verify the chip is actually being programmed with the new code, and it appears to be.
#include "pic16/pic18f24j10.h"
#define WAIT_CYCLES(A) for(__delay_cycle = 0;__delay_cycle < A;__delay_cycle++)
int __delay_cycle;
#define HI 1
#define LO 0
void why(int z)
{
if(z == HI)
{
PORTC = 0b11111111;
}
else if(z == LO)
{
PORTC = 0b11110000;
}
else
{
PORTC = 0b10101011;
}
}
void main(void)
{
TRISC = 0b00000000;
PORTC=0b00000000;
while(1)
{
why(LO);
WAIT_CYCLES(5000);
why(HI);
WAIT_CYCLES(5000);
}
}
Once the interrupt is asserted it is never cleared. That results in timer_isr() being called repeatedly. No other code is ever reached. The TMR0IF bit must be cleared in software by the Interrupt Service Routine.
Keep in mind you not only need to spend less time in the ISR than the period of the timer - it’s a good practice to spend the minimum amount of time necessary.
Remove the delays and simply toggle a flag or increment a register. In your main while (1) loop monitor the flag or counter and make your calls to why() from there.
Related
I'am working on this project, it should be a light for a carport. There are two ways to turn the light on, via motion sensor or via a switch. The Led strip starts to turn on one led after another. It will stay on for a period of time and then a reversed animation starts and turns all LEDs to black. I'am using a for loop for this animation (it's the same one FastLed uses in the first light example). The error is only when the motion sensor is activate and while the for loop is running. I'am sorry for the bad integer names, could be confusing.
Thanks a lot!
Here is the Code:
(If you can't understand German,
- Bewegungsmelder = Motion sensor
- Schalter = Switch
// für die Leds
#define NUMfront_LEDS 150 //150 Leds
#define NUMinner_LEDS 35 //35 Leds
#define rightPIN 6 //Pin 6
#define leftPIN 5
#define innerrightPIN 8
#define innerleftPIN 7
#define CLOCK_PIN 13
// für die Schalter
#define schalter 2 //Pin 2
#define Bewegungsmelder 4 //Pin 4
int schalterval = 0;
int Bewegungsval = 0;
long Time = 0;
long Wait = 900000;
int On = 0;
CRGB leftLeds[NUMfront_LEDS];
CRGB rightLeds[NUMfront_LEDS];
CRGB innerleftLeds[NUMinner_LEDS];
CRGB innerrightLeds[NUMinner_LEDS];
void setup() {
// sanity check delay - allows reprogramming if accidently blowing power w/leds
Serial.begin(115200);
delay(2000);
FastLED.addLeds<WS2812B, rightPIN, RGB>(rightLeds, NUMfront_LEDS); // GRB ordering is typical
FastLED.addLeds<WS2812B, leftPIN, RGB>(leftLeds, NUMfront_LEDS);
FastLED.addLeds<WS2812B, innerrightPIN, RGB>(innerrightLeds, NUMinner_LEDS);
FastLED.addLeds<WS2812B, innerleftPIN, RGB>(innerleftLeds, NUMinner_LEDS);
Time = millis();
}
void loop() {
Serial.println("----------------------------------------------");
Serial.print(Wait);
Serial.print("----");
Serial.print(millis());
Bewegungsval = digitalRead(Bewegungsmelder);
schalterval = digitalRead(schalter);
Serial.println(Bewegungsval);
Serial.println(schalterval);
Serial.println("Space");
Schalter:
if (digitalRead(schalter) == 1) {
On = 0;
for (int blackLed = NUMfront_LEDS; blackLed > -1; blackLed = blackLed - 1) {
leftLeds[blackLed] = CRGB::White;
rightLeds[blackLed] = CRGB::White;
delay(19);
FastLED.show();
}
// Carport innen
fill_solid( innerrightLeds, NUMinner_LEDS, CRGB::White);
fill_solid( innerleftLeds, NUMinner_LEDS, CRGB::White);
//Leds aus
//Carport aussen
while (digitalRead(schalter) == 1) {
}
for (int whiteLed = 0; whiteLed < NUMfront_LEDS; whiteLed = whiteLed + 1) {
leftLeds[whiteLed] = CRGB::Black;
rightLeds[whiteLed] = CRGB::Black;
delay(19);
FastLED.show();
}
// Carport innen
fill_solid( innerrightLeds, NUMinner_LEDS, CRGB::Black);
fill_solid( innerleftLeds, NUMinner_LEDS, CRGB::Black);
FastLED.show();
}
else if (Bewegungsval == 1) {
//Carport aussen
if (On == 1) {
goto Skip;
}
for (int blackLed = NUMfront_LEDS; blackLed > -1; blackLed = blackLed - 1) {
leftLeds[blackLed] = CRGB::White;
rightLeds[blackLed] = CRGB::White;
delay(19);
FastLED.show();
}
// Carport innen
fill_solid( innerrightLeds, NUMinner_LEDS, CRGB::White);
fill_solid( innerleftLeds, NUMinner_LEDS, CRGB::White);
FastLED.show();
//Leds aus
On = 1;
Skip:
Time = millis();
Wait = Time + 10000; // + 5min. 300000
Bewegungsval = digitalRead(Bewegungsmelder);
goto Schalter;
}
Time = millis();
if (Time >= Wait) {
On = 0;
for (int whiteLed = 0; whiteLed < NUMfront_LEDS; whiteLed = whiteLed + 1) {
leftLeds[whiteLed] = CRGB::Black;
rightLeds[whiteLed] = CRGB::Black;
delay(19);
FastLED.show();
}
// Carport innen
fill_solid( innerrightLeds, NUMinner_LEDS, CRGB::Black);
fill_solid( innerleftLeds, NUMinner_LEDS, CRGB::Black);
}
}```
Although fluent in German the program structure is alittle chaotic. Since we are in C++
you should not use goto
Since to my understanding the light routines for switch and IR are the same this code should only exist once
Your routine for measuring time is not rollover safe see blinkwithoutdelay example how todo
So clean the code up by using the following structure:
unsigned long startTime = 0;
unsigned long myTimer = 10000;// 10 sec
bool lightIsOn = false;
setup(){....}
loop(){
....
// We check wether switch or IR are triggerd AND we are not already in a light sequence
if ((digitalRead(schalter) == 1 || Bewegungsval == 1) && lightIsOn == false) {
lightIsOn = true; // change state so we know that a light sequence is running
startTime = millis(); // reset the timer
}
// this part runs as long lighIsOn == true and time is not up
if(millis() - startTime <= myTimer && lighIsOn == true){
// Carport aussen
your light sequence .....
}
// Here we run the time is up sequence
if(millis() - startTime > myTimer && lighIsOn == true) { // rollover safe
light sequence for time is up
........
lightIsOn = false; // change state so we know that a light sequence is over
}
}
This technique is called finite state machine there is no "jumping around" via goto.
If you need more states you just expand the sequence - there is no else because eg in the last two combined if statements we check for lightIsON == true ==> else would mean lightIsON == false in the second which makes no sense here as we only differentiate these to states by time.
Please never use goto in object oriented programming it makes your code unreadable and untraceable. Rewrite the program and if there are "new" problems edit here or open a new question
Status bit_flags_set_flag(BIT_FLAGS hBit_flags, int flag_position) {
Bit_Flags* temp = (Bit_Flags*)hBit_flags;
int* nums;
int i;
int old_size;
if (temp->size < flag_position) {
nums = malloc(sizeof(int)*flag_position+1);
if (nums == NULL) {
return FAILURE;
}
for (i = 0; i < temp->size; i++) {
nums[i] = temp->data[i];
}
free(temp->data);
temp->data = nums;
old_size = temp->size;
temp->size = flag_position + 1;
for (i = old_size; i < temp->size; i++) {
temp->data[i] = 0;
}
}
temp->data[flag_position / 32] |= 1 << flag_position % 32;
return SUCCESS;
}
according to the debugger the error is from the free(temp->data) part. however. I only run into the error the second time I go through the function. any ideas what is happening here.
am getting a heap corruption error on visual studio.
I am writing on some assumptions like you are assuming int size is 32 bits and you are trying to set the bit at flag_position in the bitset and you are using 1 int for 1 bit for setting and unsetting bits
Few comments now
temp->data[flag_position / 32] |= 1 << flag_position % 32; now this doesn't make any sense, this line role is to set bit at flag_position, this should be temp->data[flag_position] = 1; instead because if you see your code your are using ints for each bit.
Also this line temp->size = flag_position + 1; is also incorrect , this should be temp->size = flag_position;
I am also working on the bootloader.
I had the problem in the following:
Once the cmd 'B' is received, later, 'F' is received, then I would start to call block load.
static void start_block_flash_load(uint16_t size, uint32_t *addr) {
uint16_t data_word;
uint8_t sreg = SREG;
uint16_t temp;
int i;
uint8_t my_size;
fprintf(lcdout, "B");
cli();
// Disable interrupts
(*addr) <<= 1;
if (size <= SPM_PAGESIZE) {
boot_page_erase(*addr);
boot_spm_busy_wait();
fprintf(lcdout, "%"PRIu16, size);
uint16_t i;
//store all values. PROBLEM here!!!
my_size = 208;
uint8_t buf[SPM_PAGESIZE] = { 0 };
for (i = 0; i < my_size; i++) {
//for (i=0; i<size; i++){
buf[i] = uart_getc();
// lcd_clear();
// lcd_setCursor(0, 2);
// fprintf(lcdout, "%3d", i);
// _delay_ms(500);
}
for (i = 0; i < my_size; i += 2) { //if size is odd, then use do-while
uint16_t w = buf[i];
w += buf[i + 1] << 8; //first one is low byte, second is high???
boot_page_fill((*addr)+i, w);
}
boot_page_write(*addr);
boot_spm_busy_wait();
(*addr) >>= 1;
uart_putc('\r');
} else
uart_putc('?');
boot_rww_enable ();
SREG = sreg;
}
I can see on the lcd that the size of the block is 256. However, when entering the loop to collect data, it will get stuck.
I tested with my_size and I found that only if my_size=208 the program will run further.
The strange thing is that if I put some statements inside the loop, e.g.
lcd_clear();
lcd_setCursor(0, 2);
then 'i' which I printed out on lcd will not go up to 140 something. I put different statements, the 'i' will give different value. That is very strange, since the uart_getc() will not lose data.
What I expect is that the loop will go up to 256. I cannot figure out what happened there.
Please help if you have any idea.
Thanks
I'm using a dsPic33 to try and receive a 11-byte string and place it in a array, but have not been successful at receiving it completely. The string I send is "$123456789#" which should be received by the pic. I have tried using the code below. Any help will be appreciated.
char inBytes[11];
int i;
unsigned char temp;
while (U1STAbits.URXDA != 0)
{
temp = U1RXREG;
if (temp == '$')
{
inBytes[0] = temp;
for(i = 1; i < 10; i++)
{
if (U1STAbits.URXDA != 0)
inChar = U1RXREG;
inBytes[i] = inChar;
}
}
jolati had a good point about the end value beeing too low to get 11 bytes but I must add that you have to wait for your other bytes to become available before you read them.
In your example;
char inBytes[11];
int i;
unsigned char temp;
while (!U1STAbits.URXDA ); //Wait until at least one byte is available
temp = U1RXREG;
if (temp == '$')
{
inBytes[0] = temp;
for(i = 1; i < 11; i++) //Loop over range i = 1 to 10 inclusively
{
while (!U1STAbits.URXDA ); //Wait until at least one byte is available
inBytes[i] = U1RXREG;
}
}
Ideally, you would do this in a non blocking way with interrupts so you handle your data as it comes in but, if you cant use interrupts, you can always use non blocking polling like:
void AsyncRX()
{
//Note that the static variables keeps their value between invocations of the
// function. i is set to 0 only on the first run of this function, it keeps
// its value on every other run after that.
static int i = 0;
static char inBytes[11];
//Nothing more to do until there is at least 1 byte available
if( !U1STAbits.URXDA )
return;
//Save the byte and test that our message starts with $
inBytes[i] = U1RXREG;
if( inBytes[0] != '$' )
return;
//Test the counter to see if we have a full 11 bytes
i++;
if( i < 11 )
return;
//Do something with your 11 bytes
//...
//...
//Reset the counter for the next message
i = 0;
}
For the interrupt example, you could simply grab the polled version and throw it into a ISR. The following is an example. Note that I do not know which dsp33 you are using and I have not programmed interrupts in high end cores (with vector tables) in a while so you may need to make a change or two. Also note that you need to enable interupts by setting the appropriate registers as they are not enabled by default.
void __attribute__ ((interrupt, no_auto_psv)) _U1RXInterrupt(void)
{
//Note that the static variables keeps their value between invocations of the
// function. i is set to 0 only on the first run of this function, it keeps
// its value on every other run after that.
static int i = 0;
static char inBytes[11];
//Reset the interrupt flag
IFS0bits.U1RXIF = 0;
//Use up all bytes in the buffer (the interrupt can be set to only fire
// once the buffer has multiple bytes in it).
while( U1STAbits.URXDA )
{
//Save the byte and test that our message starts with $
inBytes[i] = U1RXREG;
if( inBytes[0] != '$' )
continue;
//Test the counter to see if we have a full 11 bytes
i++;
if( i < 11 )
continue;
//Do something with your 11 bytes
//...
//...
//Reset the counter for the next message
i = 0;
}
}
for(i = 1; i < 10; i++) starts saving data at index 1 and stops at 9, only 9 bytes. Change < 10 to <= 10 or < 11.
I have written a pwm code for Atmega128. I am using fast pwm mode with non-inverting pulse on compare match and I need to change the OCR0 value at certain times. Yet it doesn't change. Anyone knows what is the problem here ??
#include <avr/interrupt.h>
#include <avr/io.h>
uint8_t tick_1sec;
void timer1_init(void) // 1 second timer
{
OCR1A = 15624;
TIMSK |= (1<<OCIE1A);
TCCR1B = (1<<WGM12); //CTC mode
TCCR1B |= (1<<CS12)|(0<<CS11)|(1<<CS10);
}
ISR(TIMER1_COMPA_vect) //1 second interrupt
{
cli();
tick_1sec = 1;
sei();
}
void timer0_init(void) // fast pwm with OC0 non-inverting mode
{
TCCR0 = (1<<FOC0)|(1<<WGM01)|(1<<WGM00);
TCCR0 |= (1<<COM01)|(0<<COM00);
TCCR0 |= (1<<CS02)|(1<<CS01)|(1<<CS00);
OCR0 = 63;
TIMSK |= (1<<OCIE0);
}
int main(void)
{
uint8_t t = 0;
DDRB = 0xFF;
timer0_init();
timer1_init();
sei();
while(1){
if (tick_1sec)
{
tick_1sec = 0;
t++;
if (t == 10){
OCR0 = 127;
}
else if (t == 20){
OCR0 = 191;
}
else if (t == 30){
OCR0 = 63;
t = 0;
}
}
}
return 0;
}
Things to check:
I recommend declaring tick_1sec as volatile to prevent the compiler of hyper-optimizing that register.
What is your clock frequency? Your ISR will deliver 1s calls only if your CPU frequency is 16MHz (==> 16.000.000 / 1024 / 15624)
You might have a LED in your hardware which you can invert from a) the ISR b) within the first if () in main to see if this is ever reached.
update: "volatile"
The link provided by #skyrift in his comment is very worth reading.
When you use Atmel Studio, compile your code once with/without the volatile keyword and compare what the compiler is doing ==> Solution explorer / Output Files / *.lss ... you will see each C statement and how the compiler converts it to machine code ... an exercise worth once in a while when working with micros ...