First led of WS2812B starts to light when the code enters the for loop - for-loop

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

Related

How to code a servomotor with two buttons in arduino?

I wanted to make a servomotor oscilate between 0-90 degrees when i push a button, but when i push another one, it stops oscillating and then remains in its latest position.
i started with this:
#include <Servo.h>
Servo myservo;
int pos = 0;
const int button1 = 5;
const int button2 = 6;
int lastpos = pos;
void setup() {
myservo.attach(3);
pinMode(button1, INPUT);
pinMode(button2, INPUT);
}
void loop() {
if(digitalRead(button1) == HIGH)
{for(pos = 0; pos <= 90; pos += 1)
{myservo.write(pos);
for(pos = 90; pos >= 0; pos -= 1)
{myservo.write(pos);
delay(36);
} } if(digitalRead(button2) == HIGH){ myservo.write(lastpos);}}}
To start, take a look at how to format code inside a question. It makes it a lot easier to read and help you out. See below for how I formatted for the site, but also readability.
Servo myservo;
int pos = 0;
const int button1 = 5;
const int button2 = 6;
int lastpos = pos;
void setup() {
myservo.attach(3);
pinMode(button1, INPUT);
pinMode(button2, INPUT);
}
void loop() {
if(digitalRead(button1) == HIGH) {
for(pos = 0; pos <= 90; pos += 1) {
myservo.write(pos);
for(pos = 90; pos >= 0; pos -= 1) {
myservo.write(pos);
delay(36);
}
}
if(digitalRead(button2) == HIGH) {
myservo.write(lastpos);
}
}
}
There are several issues with your code based on your description of what you are trying to achieve. First, let's start with the button presses. You are ready the button state, but your code will only detect the button if it is pressed at the exact moment you are doing the digital read. Here's a good resource for reading up on how to properly implement buttons on Arduino: https://www.logiqbit.com/perfect-arduino-button-presses
The second objective is to have the servo sweep back and forth, but stop when you press a button. Your for loops won't let that happen. As currently written, you will always do a sweep to one end and back and then check the next button.
You should update the position of the servo once each time through the loop so you can check on the status of the buttons. In pseudo-code, what I suggest you do is:
void loop() {
//Check button statuses
if(button1), start sweep
if(button2), stop sweep
//Update sweep position
if(ascending && pos < 90) {
//You should be increasing in angle and you haven't reached 90 yet
ascending = TRUE;
pos += 1
myservo.write(pos);
delay(36); //Or whatever delay you need for the servo
} else if(pos > 0) {
//You already reached 90 and are coming back down to 0
ascending = FALSE;
pos -= 1;
delay(36);
}

ESP32 Task watchdog got triggered using ESP IDF

We need to read ADC module over I2C continuously 20 times to get stable values of ADC.
We have created a task for it, but code stop working in couple of min showing below error.
E (1925655) task_wdt: Task watchdog got triggered. The following tasks did not r
eset the watchdog in time:
E (1925655) task_wdt: - IDLE (CPU 0)
E (1925655) task_wdt: Tasks currently running:
E (1925655) task_wdt: CPU 0: esp_timer
We are not getting any exact solution for our error. Below is the task espfor reference.
void Hal_Read_Average_Voltage_For_TLA202x (void *pvParameters)
{
float read_value = 0, bigger_value = 0, voltage = 0;
while(1)
{
Hal_TLA2024_Re_Initialize ();
{
for (int count1 = 0; count1 < 20; count1++)
{
voltage = readVoltage (); //Performs I2C register read
if (voltage > bigger_value)
{
bigger_value = voltage;
}
vTaskDelay (1);
}
read_value += bigger_value;
bigger_value = 0;
}
ESP_LOGE(TAG, "ADC Highest Value = %f\n", (read_value));
read_value = 0;
bigger_value = 0;
voltage = 0;
vTaskDelay (300 / portTICK_PERIOD_MS);
}
}
float readVoltage (void)
{
int16_t raw_voltage;
uint16_t u16TempRead = 0;
uint8_t u8TempRead[2] = { 0, 0 };
uint8_t u8TempAddress = TLA202x_DATA_REG;
Hal_I2C_Read_Register (TLA202x_I2CADDR_DEFAULT, u8TempAddress, u8TempRead, 2, 1);
u16TempRead = u8TempRead[1] | (u8TempRead[0] << 8);
raw_voltage = u16TempRead;
// this will read the sign bit correctly, but shifting will move the bit out
// of the msbit
if (raw_voltage & 0x8000)
{
raw_voltage >>= 4;
raw_voltage |= 0x8000;
}
else
{
raw_voltage >>= 4;
}
switch (current_range)
{
case TLA202x_RANGE_6_144_V:
voltage = raw_voltage *= 3;
break;
case TLA202x_RANGE_4_096_V:
voltage = raw_voltage *= 2;
break;
case TLA202x_RANGE_2_048_V:
voltage = raw_voltage *= 1;
break;
case TLA202x_RANGE_1_024_V:
voltage = raw_voltage *= 0.5;
break;
case TLA202x_RANGE_0_512_V:
voltage = raw_voltage *= 0.25;
break;
case TLA202x_RANGE_0_256_V:
voltage = raw_voltage *= 0.125;
break;
}
voltage /= 1000.0; // mV =>V
return voltage;
}
void Hal_I2C_Read_Register (uint32_t slave_address, int register_address, uint8_t read_data_buffer[],
uint8_t read_buffer_length, uint8_t write_buffer_length)
{
i2c_cmd_handle_t cmd;
DATA_READ: cmd = i2c_cmd_link_create ();
i2c_master_start (cmd);
if (register_address != -1)
{
i2c_master_write_byte (cmd, slave_address << 1 | I2C_MASTER_WRITE,
ACK_CHECK_EN);
i2c_master_write_byte (cmd, register_address, ACK_CHECK_EN);
i2c_master_start (cmd);
}
i2c_master_write_byte (cmd, slave_address << 1 | I2C_MASTER_READ,
ACK_CHECK_EN);
if (read_buffer_length > 1)
{
i2c_master_read (cmd, read_data_buffer, read_buffer_length - 1, ACK_VAL);
}
i2c_master_read_byte (cmd, read_data_buffer + read_buffer_length - 1,
NACK_VAL);
i2c_master_stop (cmd);
esp_err_t ret = i2c_master_cmd_begin (I2C_NUM_0, cmd, 1000/ portTICK_RATE_MS);
i2c_cmd_link_delete (cmd);
if (ret == ESP_OK)
{
}
else if (ret == ESP_ERR_TIMEOUT)
{
// ESP_LOGW(TAG, "Bus is busy");
}
else
{
ESP_LOGW(TAG, "Read failed %d", ret);
goto DATA_READ;
}
}
We are having 2 more thread running on same priority.
If we remove the for loop in the above thread then there is no WDT error.
Updated ESP-IDF version to 4.4 and it solved this issue.

Unable to execute interrupt function

Using Mplab ide 5.10 and xc8 compiler for the pic18f4550 I am unable to get the code to get into the interrupt function the goal is to get J to count up in the background until something trigger it to output a value in the lcd. Currently only the lcd display the first message and using ICD 3 the value of J does not change and does not look like the program runs the interrupt function at all
#define _XTAL_FREQ 48000000
#include <xc.h>
#include <stdio.h>
#include <stdlib.h>
#include "lcd.h"
unsigned char j, output = 0, i, outchar;
char buffer[2] = " ";
char Message[ ] = "Hands Position ";
void interrupt timer0_isr();
void lcd_write_cmd(unsigned char cmd);
void lcd_write_data(unsigned char data);
void lcd_strobe(void); // Generate the E pulse
void lcd_init(void);
void interrupt timer0_ISR() // Timer0 Interrupt Service Routine (ISR)
{
if (INTCONbits.TMR0IF) // TMR0IF:- Timer0 Overflow Interrupt Flag Bit
{
TMR0H = 0x48; // Timer0 start value = 0x48E5 for 1 second
TMR0L = 0xE5;
PORTCbits.RC1 = !PORTCbits.RC1; /* external timing check - toggle every 1ms */
if (j <= 4) { //limit up to 7
j++; // Increase count by 1
PORTB = j; // Output to Demultiplexer
} else {
j = 0; // Reset count aftwr it hit 7
PORTB = j; // Output to Demultiplexer
}
INTCONbits.TMR0IF = 0; // Reset TMR0IF at interrupt end
}
}
void main(void) // Main Function
{
ADCON1 = 0x0F;
CMCON = 0x07;
RCONbits.IPEN = 1; // Bit7 Interrupt Priority Enable Bit
INTCONbits.GIEH = 1; // Bit7 Global Interrupt Enable bit
INTCONbits.GIEL = 0; /* turn on low & high interrupts */
T0CONbits.TMR0ON = 1; // Turn on timer
T0CON = 0b00000111; // bit7:0 Stop Timer0
// bit6:0 Timer0 as 16 bit timer
// bit5:0 Clock source is internal
// bit4:0 Increment on lo to hi transition on TOCKI pin
// bit3:0 Prescaler output is assigned to Timer0
// bit2-bit0:111 1:256 prescaler
INTCON2 = 0b10000100; // bit7 :PORTB Pull-Up Enable bit
// 1 All PORTB pull-ups are disabled
// bit2 :TMR0 Overflow Int Priority Bit
// 1 High Priority
TMR0H = 0x48; // Initialising TMR0H
TMR0L = 0xE5; // Initialising TMR0L for 1 second interrupt
INTCONbits.TMR0IE = 1; // bit5 TMR0 Overflow Int Enable bit
INTCONbits.TMR0IF = 0; // bit2 TMR0 Overflow Int Flag bit
// 0 TMR0 register did not overflow
TRISC = 0; /* all outputs */
TRISAbits.TRISA5 = 1; // RA5 is the check for signal from input Multiplexer.
TRISAbits.TRISA0 = 0; // RA0, RA1 & RA2 output to arduino
TRISAbits.TRISA1 = 0;
TRISAbits.TRISA2 = 0;
TRISD = 0x00; // PortD connects to Demultiplexer
TRISB = 0;
lcd_init(); // LCD init
lcd_write_cmd(0x80); // Cursor set at line 1 positon 1
for (i = 0; i < 16; i++) {
outchar = Message[i]; // Store Message in outchar
lcd_write_data(outchar); // Display Message
}
__delay_ms(100);
PORTD = 0x00; // Clear PortD
PORTB = 0;
j = 0; // Start count from 0
while (1) // Main Process
{
if (PORTAbits.RA5 == 1) { // If RA3 detect a signal
switch (j) { // Switch case to determine hand position & output to RA0, RA1 & RA2 to transmit to arduino
case(0):
output = 10;
PORTAbits.RA0 = 0;
PORTAbits.RA1 = 0;
PORTAbits.RA2 = 0;
break;
case(1):
output = 20;
PORTAbits.RA0 = 1;
PORTAbits.RA1 = 0;
PORTAbits.RA2 = 0;
break;
case(2):
output = 30;
PORTAbits.RA0 = 0;
PORTAbits.RA1 = 1;
PORTAbits.RA2 = 0;
break;
case(3):
output = 40;
PORTAbits.RA0 = 1;
PORTAbits.RA1 = 1;
PORTAbits.RA2 = 0;
break;
case(4):
output = 50;
PORTAbits.RA0 = 0;
PORTAbits.RA1 = 0;
PORTAbits.RA2 = 1;
break;
}
lcd_write_cmd(0xC0); // Cursor set at line 2 positon 1
sprintf(buffer, "%d", output); // Convert numbers to character
for (i = 0; i < 2; i++)
lcd_write_data(buffer[i]); // Display Hand Position
}
}
}

IR Receiver RC5 with Pic12F1572

I am building an IR Receiver with PIC12F1572 with receiver module TSOP2438
My objective of this project is to receive a data by remote control and send it to PC via UART..
I have done the code and I am testing it I can send the normal value through the UART but Somewhereis wrong so that I can not receive the hex values regarding the commands of remote control
Can anyone see my code and tell where I am goping wrong?
Here is my code
void main(void)
{
OSCILLATOR_Initialize(); // 0x78 for Fosc = 16Mhz
PIN_MANAGER_Initialize(); //All port pins Digital and input
EUSART_Initialize();
INTCONbits.IOCIF = 0; // Interrupt on-change Flag
INTCONbits.PEIE = 1; //SEt Peripheral Interrupt
INTCONbits.GIE = 1; //Set Global Interrupt
//while(!OSCSTATbits.HFIOFS); //Check here or wait here to OSC stable/ 0.5% accuracy
TRISAbits.TRISA2 = 1; //Configure R1 as input
// uint16_t Input_buffer [20];
EUSART_Write(0x40); // 0x40 = # some flag
while(1)
{
count = 0;
//while((IR_PIN)); //IR_PIN receives an IR signal its output pin goes from logic 1 to logic 0
//which causes the microcontroller to start reading the IR signal using the function. decode()
EUSART_Write(0x41);
//while(IR_PIN);
if(Decode()) //check if RC5 decoding- new data is arrived
{
EUSART_Write(0x42);
toggle_bit = bit_test(IR_Code, 11);
address = (IR_Code >> 6) & 0x1F;
command = IR_Code & 0x3F;
EUSART_Write(toggle_bit);
EUSART_Write(address);
EUSART_Write(command);
EUSART_Write(0x43);
}
}
}
/*----------*/
uint8_t Measure_space()
{
TMR0_Initialize();
while(IR_PIN && (count < 2000))
count = TMR0_ReadTimer(); //Read timer value and store it in count value
if((count > 1999) || (count < 700))
return 0; //0 = If width is out of range
if(count > 1200)
return 1; //1 = If width is long
else
return 2; //2 = If the width is short
}
uint8_t Decode()
{
uint8_t i = 0, check;
mid1:
check = Measure_Pulse();
if(check == 0)
return FALSE;
bit_set(IR_Code, 13 - i);
i++;
if(i > 13)
return TRUE;
if(check == 1)
goto mid0;
else
goto start1;
mid0:
check = Measure_space();
if((check == 0) && (i != 13))
return FALSE;
bit_clear(IR_Code, 13 - i);
i++;
if(i > 13) return TRUE;
if(check == 1)
goto mid1;
else
goto start0;
start1:
check = Measure_space();
if(check != 2)
return FALSE;
goto mid1;
start0:
check = Measure_Pulse();
if(check != 2)
return FALSE;
goto mid0;
}
I think this is because you are sending Hex value without converting to string. If you want to print this Hex value in PC terminal, First you have to convert it to ASCII string.

SDCC integer comparison unexpected behavior

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.

Resources