I am currently working on a code involving the MPLAB XC8 Compiler, PIC18F452 with a Multiplexed Seven Segment Display. I want to use two pushbuttons connected to pins RB2 and RB3 of PORTB of the PIC18F452 to increment and decrement a variable "count" and display this number from 0 to 99 on this display. Schematic and code is show below.
This code relatively functions as it is, and I do not believe the schematic is to blame for the issues I am seeing, nor is the byte array not correct as I am able to see each number when using the array with a 1 segment display.
The issue arrises when trying to use this multiplexing scheme shown in the below figure. I can successfully display two numbers on the seven segment displays, but there are strange anomalies present when executing this code. For one, I seem to not be able to display the number 1, 4 and occasionally 7 on either display, but when this digit does not show the display is blank, and when the button is again pushed the next number is shown as expected.
for example:
The display shows the numbers as follows for number sequences:
9... 10... 11... 12 13... 14... ect...
or
34.... 35... 36... 37....
Not sure where the issues lies, and debugging is not going well... any help would be appreciated.
Schematic for Multiplexed 7 Segment Display
#define _XTAL_FREQ 10000000
#include <xc.h>
#include <stdlib.h>
#define Digit1 PORTBbits.RB1 //variable to sink current to PNP base
#define Digit2 PORTBbits.RB2 //variable to sink current to PNP base
#define Switch1 PORTBbits.RB4 //switch decrement variable
#define Switch2 PORTBbits.RB3 //switch increment variable
#define Pressed1 1 //pressed is high
#define Pressed2 1 //pressed is high
void initialize();
void segment1 (void);
void segment2 (void);
void buttonPress(void);
void delay_ms(unsigned int);
void sendPattern1(unsigned char pattern);
void sendPattern2(unsigned char pattern3);
unsigned char rotateLeft(unsigned char pattern, int no);
unsigned char MSD, LSD, count=0;
Main code
void main(void){
initialize();
Digit1 = 0;
Digit2 = 0;
while(1){
buttonPress();
MSD = count/10 ;
segment1();
Digit2 = 1;
delay_ms(10); // Delay for 10 ms
Digit2 = 0;
LSD = count%10;
segment2();
Digit1 = 1;
delay_ms(10); // Delay for 10 ms
Digit1 = 0;
}
return;
}
Functions to index Most Significant Digit and Least Significant Digit from array to be sent to the ports to sink current low for common annode display.
void segment1(void){
unsigned char segArrayC[]={0b11000000,0b11111001,0b00100100,
0b00110000,0b00011001,0b00010010,
0b00000010,0b11111000,0b00000000,0b00011000};
unsigned char pattern;
pattern = segArrayC[MSD];
sendPattern1(pattern);
return;
}
void segment2(void){
unsigned char segArrayD[]= {0b11000000,0b11111001,0b00100100,
0b00110000,0b00011001,0b00010010,0b00000010,
0b11111000,0b00000000,0b00011000};
unsigned char pattern3;
pattern3 = segArrayD[LSD];
sendPattern2(pattern3);
return;
}
Button Press Code
void buttonPress(void){
if (Switch1 == Pressed1) {
++count;
delay_ms(100);
}
if (Switch2 == Pressed2) {
--count;
delay_ms(100);
}
if(count>=99||count<0)
{
count=0;
delay_ms(100);
}
return;
}
Function to rotate bytes in array two places to left to be displayed on PORTs
/** Rotate pattern to the left 'no' number of bits
*/
unsigned char rotateLeft(unsigned char pattern, int no) {
return (((pattern << no) & 0xFF) | (pattern >> (8-no)));
}
Functions to output indexed array char to PORTC and PORTB pins
void sendPattern1(unsigned char pattern) {
// Send pattern to appropriate port pins
unsigned char pattern2;
PORTC = pattern;
pattern2=rotateLeft(pattern, 2);
PORTB = pattern2;
return;
}
void sendPattern2(unsigned char pattern3) {
unsigned char pattern4;
PORTC = pattern3;
pattern4=rotateLeft(pattern3, 2);
PORTB = pattern4;
return;
}
Delay Function
void delay_ms(unsigned int n){
while (--n) _delay(2500);
}
Initialize pins to be used (0 output, 1 input)
void initialize() {
TRISC = 0;
TRISBbits.TRISB0 = 0;
TRISBbits.TRISB1 = 0;
TRISBbits.TRISB2 = 0;
TRISBbits.TRISB4 = 1;
TRISBbits.TRISB3 = 1;
PORTC = 0x00;
PORTB = 0x00;
}
In sendPattern() you write a rotated bit pattern to PORTB.
This interferes with the setting the common anode control. So you see both digits only, if both right hand segments are turned on. According your schematic you should write a 0 to turn on the common anode. Try this:
void main()
{
static const unsigned char segArray[]=
{ 0b11000000, 0b11111001, 0b00100100, 0b00110000, 0b00011001,
0b00010010, 0b00000010, 0b11111000, 0b00000000, 0b00011000
};
TRISC = 0; //PortC all OUTPUT
PORTC = 0xFF; //PortC all HIGH = IDLE = LED_OFF
TRISBbits.TRISB0 = 0; //Output unused
TRISBbits.TRISB1 = 0; //Output Digit1
TRISBbits.TRISB2 = 0; //Output Digit2
TRISBbits.TRISB4 = 1; //Input: Switch PLUS
TRISBbits.TRISB3 = 1; //Input: Switch MINUS
PORTB = 0x00;
unsigned char count=0;
for(;;)
{
//Handle buttons
if (Switch1 && count<99)
{
++count;
delay_ms(100);
}
if (Switch2 && count > 0)
{
--count;
delay_ms(100);
}
//Write high digit
PORTC = segArray[count/10];
Digit2 = 0;
delay_ms(10); // Delay for 10 ms
Digit2 = 1;
//Write low digit
PORTC = segArray[count%10];
Digit1 = 0;
delay_ms(10); // Delay for 10 ms
Digit1 = 1;
}
}
Related
I am new to programming in IDE. I am using built-in timer of arduino.I am using TDR method to capture reflection from fault location in cable and for that I am using timer.Timer should start as soon as output is send and stop at reflection. I have a reference code for it but I dont able to understand it, so if anyone know about it , it would be great.
void setup()
{
pinMode(stepPin, OUTPUT);
pinMode(refPin, OUTPUT);
pinMode(shutdownPin, OUTPUT);
TCCR1A = 0;
TCCR1B = (1 << ICNC1); // input capture noise canceller enabled, capture on falling edge
TIMSK1 = 0; // timer 1 interrupts disabled
ACSR = 0; // input capture from ICP1 pin
TCCR2B = (1 << CS20); // change timer 2 PWM frequency to 31.25kHz because we're using pin 11 as a DAC
Serial.begin(19200);
}
struct Step
{
unsigned int time;
unsigned int amplitude;
};
// Take a single measurement, using either a positive or negative edge from the comparator.
// The comparator reference voltage must have been set up and allowed to stablise before calling this.
unsigned int takeMeasurement(bool posEdge)
{
byte reg1b = (posEdge) ? 0 : (1 << ICES1); // input capture noise canceller csdisabled, set up input capture polarity, stop timer
reg1b |= (1 << CS10);
TCCR1B = reg1b;
TCNT1H = 0;
TCNT1L = 0; // clear timer
unsigned int capture = 0;
unsigned long start = micros(); // get the time
cli();
TCNT1H = 0;
TCNT1L = 0; // clear timer
TIFR1 = (1 << ICF1); // clear timer 1 input capture bit
PORTD |= (1 << 4); // set output high
sei();
do
{
if ((TIFR1 & (1 << ICF1)) && capture == 0)
{
byte temp = ICR1L;
capture = (ICR1H << 8) | temp;
}
} while (micros() - start < 100);
PORTD &= ~(1 << 4); // set output low
return capture;
}
size_t findSteps(bool positive, struct Step *results, size_t maxResults)
{
byte amplitude = (positive) ? 5 : 250;
analogWrite(refPin, amplitude);
delay(100); // wait 100ms for the output to stabilise
unsigned int lastReading = 0;
size_t numResults = 0;
unsigned int stepSize = 0; // 0 means not in a step
#ifdef DEBUG
Serial.print((positive) ? "pos " : "neg ");
#endif
for (int i = 0; i < 50; ++i)
{
analogWrite(refPin, amplitude);
delay(10);
unsigned int currentReading = takeMeasurement(positive);
unsigned int currentDiff = currentReading - lastReading; // diff since start of possible step
if (stepSize == 0)
{
// Not currently in a step
if (i != 0 && currentReading != 0 && currentDiff == 0)
{
// Found the start of a possible step
++stepSize;
}
lastReading = currentReading;
}
else
{
if (currentDiff > 2 || i + 1 == 50)
{
// Step has endeed, so record it if it is big enough
if (stepSize >= 2)
{
results->time = lastReading;
results->amplitude = amplitude - 5;
++results;
++numResults;
if (numResults == maxResults) break;
}
stepSize = 0;
lastReading = currentReading;
}
else if (currentDiff == 0)
{
++stepSize;
}
}
#ifdef DEBUG
if (i != 0) Serial.write(',');
Serial.print(currentReading);
#endif
if (positive)
{
amplitude += 5;
}
else
{
amplitude -= 5;
}
}
#ifdef DEBUG
Serial.println();
#endif
return numResults;
}
I am making a game where you need to repeat the sequence of LEDs that light up. This sequence is set by two LEDs. To repeat the sequence, I use the joystick.
I had an idea to make two bool arrays where True will indicate the left LED, and False will indicate the right LED. The first array must contain a random sequence(True/False) that needs to be repeated. When I push to one or the other side of the joystick, I want to write to the second array, respectively, True / False and all this time compare them.
This is what I have at the moment. (AT90USB647)
#define F_CPU 2000000UL
#include <avr/io.h>
#include <stdbool.h>
int main(void) {
MCUCR |= 0x80;
MCUCR |= 0x80;
DDRA = 0xFF;
PORTF = 0x20;
bool seq2[100];
while(1)
{
uint8_t x = PINF;
if(!(x & 0x20)) {
PORTA = 0x80;
}
else if(!(x & 0x08)) {
PORTA = 0x01;
}
else {
PORTA = 0x00;
}
}
}
The main question is how do I write True or False to an array when I push the joystick?
A basic approach could be:
#define F_CPU 2000000UL
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
volatile unsigned int counter;
static unsigned char pattern_position;
static unsigned char array_position;
static unsigned char pattern[] = {
0b01010101,
0b11010101,
0b10010101
};
ISR(TIMER0_COMPA_vect)
{
counter++;
}
int main(void)
{
MCUCR |= 0x80;
DDRA = 0xFF;
PORTF = 0x20;
// Timer initialization
// Mode: CTC
// Prescaler: 1024
TCCR0A = (1<<WGM01);
TCCR0B = (1<<CS02) | (1<<CS00);
// Calculate a correct time
//
// we want 1 ms -> f_TIMER0 = 1/T = 1/(1 * 10^-3)s = 1 kHz
//
// f_CPU f_CPU 20 MHz
// f_TIMER0 = ------------- -> OCR0A = ---------------- = ------------- = ~ 20 (It is not exactly 1ms but it is ok)
// k_H * OCR0A k_H * f_TIMER0 256 * 1 kHz
//
OCR0A = 20;
TIMSK0 = (1<<OCF0A); // Enable Timer0 Overflow Compare Match interrupt
// Show the sequence that the user should input
for (unsigned char i=0; i < sizeof(pattern)/sizeof(&pattern[0]); i++)
{
for (unsigned char j=0; j < 8; j +=2)
{
// There is possible a signal missing to show the user that the next pattern occurs!
PORTA = ((pattern[i]>>(j+1))<<PINA7) | ((pattern[i]>>j)<<PINA0);
// That the user can see the patterns a delay is necessary!
_delay_ms(1000);
}
}
// Signalize that the game starts
for (unsigned char i=0; i <8; i++)
{
PORTA ^= 0x81;
_delay_ms(1000);
}
TCNT0 = 0x00;
sei();
while(1)
{
// There is possible a signal missing to trigger next pattern input to the user!!!
if(!(PINF & (1<<PINF5)))
{
PORTA |= 0x80;
}
if(!(PINF & (1<<PINF3)))
{
PORTA |= 0x01;
}
// Time is 4 seconds to match the correct pattern
if(counter >= 4000)
{
if(!((pattern[pattern_position] & (1<<array_position)) == (0x01 & PORTA)))
{
// Wrong input end of game
}
array_position++;
if(!((pattern[pattern_position] & (1<<array_position)) == (0x01 & (PORTA>>8))))
{
// Wrong input end of game
}
array_position++;
if(array_position >= 8)
{
array_position = 0;
pattern_position++;
}
if(pattern_position >= (sizeof(pattern)/sizeof(&pattern[0])))
{
// End of game reached winning!
}
counter = 0x00;
PORTA = 0x00;
TCNT0 = 0x00;
}
}
}
I´m not sure if you are exactly trying this to do and i also can not test the code on your target platform but maybe this is a rudimental approach to solve your problem...
I am programming an embedded processor (Atmega644a) using C (Atmel studio) and I am trying to use this nested case/switch to cycle through my states but when I get to the 3rd state inside my "on" case, it doesn't go back to my startTrigger case, even though I set the current_state to startTrigger inside my rotate function, which I call in my startRotate state/case. Also, I am certain that all states are being entered and the functions work for the first cycle through the states. I've posted my code below, this is my first time posting on a forum so I'm not sure if you want the whole thing or not.
This is my full code
/*
* test_external_interrupts.c
*
* Created: 12/28/2017 10:49:37 AM
* Author : Celeste MacNeil
*/
//libraries
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include <stdio.h>
#include "UART_library.h"
// system constants
#define pi 3.14159265359
#define MAX 65535
#define ARRAYmax 11
const float fclk = 14.7456e6;
const float prescale = 1024;
const float cm_meter = 100;
const float speed_of_sound = 343;
const float fclk_echo = 14.7456e6;
const float ten_us = 10e-6;
const float prescale_echo = 8;
const float prescale_speaker = 256;
const float spkr_midpoint = 1.25;
// for input captures
volatile unsigned short current_edge;
volatile float rising_edge_timestamp, falling_edge_timestamp;
volatile float pulse_width;
// for distances
volatile float duration, distance, net_distance;
//counter
int p;
//states
enum fsm {startTrigger, startMeasure,startRotate};
enum fsm current_state;
enum status {on, off};
enum status button_status;
//distance/frequency values arrays and counter
float dist[] = {0,0.363636364,0.727272727,1.090909091,1.454545455,1.818181818,2.181818182,2.5454545,2.909090909,3.272727273,3.636363636,4};
float freq[] = {261.6, 282.7181818, 303.8363636,324.9545455,346.0727273,367.1909091,388.3090909,409.4272727,430.5454545,451.6636364,472.7818182,493.9};
// angle and pulse duration counts/arrays
float angle[] ={-90 ,-75,-60,-45,-30,-15, 0, 15, 30, 45, 60, 75, 90};
float pulseIn[]={0.00054,0.00065,0.0008,0.00094,0.0011,0.00125,0.0014,0.0016,0.0018,0.002,0.0022,0.0023,0.0024};
/******************************************************************************
function to trigger 10us pulse
************************************
******************************************/
void trigger(){
PORTA |=(1<<PA7);
/* initialize counter settings */
TCCR1A = 0; // not required since WGM11:0, both are pre-set to zero
TCCR1B |= (1<<WGM12)|(1<<CS11); // Mode = CTC, Prescaler = 8
TIMSK1 |= (1<<OCIE1A)|(1<<ICIE1); // set timer to reset when output compare is reached
TCNT1 = 0; // initialize counter
OCR1A = (int)fclk_echo*ten_us/prescale_echo; // initialize compare value
//printf("Trigger\n");
}
/******************************************************************************
When the timer count is reached, do something
******************************************************************************/
ISR (TIMER1_COMPA_vect)
{
PORTA &= ~(1<<PA7); //end 10us pulse on trigger pin
TCCR1B |= (1<<ICES1); //set input capture on rising edge
TIMSK1 |= (1<<ICIE1); //set input capture interrupt flag
TCCR1B |= (1 << WGM12)|(1 << CS11); // Mode = CTC, Prescaler = 8
TCNT1 = 0;
OCR1A = 0;
}
/******************************************************************************
When echo pulse is triggered, capture pulse duration
************************************
******************************************/
ISR (TIMER1_CAPT_vect)
{
if(current_edge == 1){
rising_edge_timestamp = ICR1; //save time stamp
TCCR1B &= ~(1<<ICES1); //set input capture on falling edge.
current_edge = 0;
}else if(current_edge == 0){
falling_edge_timestamp = ICR1;
TCCR1B |= (1<<ICES1); //set input capture to rising edge
current_edge = 1;
}
if(rising_edge_timestamp<falling_edge_timestamp){
pulse_width = falling_edge_timestamp - rising_edge_timestamp;
}else{
pulse_width = MAX - rising_edge_timestamp + falling_edge_timestamp;
}
//printf("rising edge: %f\n falling edge :%f\n pulse width: %f\n", rising_edge_timestamp, falling_edge_timestamp,pulse_width);
_delay_ms(100);
current_state = startMeasure;
}
/******************************************************************************
function to sound speaker tones
************************************
******************************************/
void speaker_tones(){
int q, r=0;
for(q=0;dist[q]<ARRAYmax;q++){
while(net_distance>dist[r]*cm_meter){
r++;
}
OCR0A = (int)((fclk_echo/(4*prescale_speaker*freq[r])));
//printf("%f",freq[r]);
_delay_ms(3000);
OCR0A = 0;
}
}
/******************************************************************************
function to measure echo pulse
************************************
******************************************/
void measure(){
duration = (pulse_width*prescale_echo)/fclk_echo;
distance = (duration*speed_of_sound*cm_meter)/2;
net_distance = sqrt((distance*distance -spkr_midpoint*spkr_midpoint));
if(distance>spkr_midpoint&&net_distance<395){
printf("The object distance is %.2f cm away.\n", net_distance);
printf("The object angle is %.2f degrees.\n\n", angle[p]);
speaker_tones();
printf("p in measure is %d\n\n",p);
}
_delay_ms(100);
p++;
current_state = startRotate;
}
/******************************************************************************
function to rotate servo
*************************************************
*****************************/
void rotate(){
if(p<=ARRAYmax){
printf("p in rotate is %d\n\n",p);
OCR2A = (int)(pulseIn[p]*fclk/prescale); // sets output compare to approx clockcycles per sample
}else{
p=0;
OCR2A = (int)(pulseIn[p]*fclk/prescale); // sets output compare to approx clockcycles per sample
}
_delay_ms(100);
current_state = startTrigger;
}
/******************************************************************************
read the button status on an external interrupt.
*************************************************
*****************************/
ISR (INT2_vect){
button_status^=button_status|1;
//printf("%d\n",button_status);
}
/******************************************************************************
function to power down or restart cycle
************************************
******************************************/
void zero_off(){
p=0;
OCR2A = (int)(pulseIn[p]*fclk/prescale); // sets output compare to approx clockcycles per sample
}
/******************************************************************************
main function:
***************************************
***************************************/
int main(void){
/* initialize output ports */
DDRB |= (1 << PB3); // Set PB3 (speaker) to write all others unchanged
DDRA |= (1<< PA7); // set A7 to write, all others are unchanged
DDRD |= (1<< PD7); // set PD7 to write, all others are unchanged
PORTB = 0;
PORTA = 0;
/*initialize counter settings*/
TIMSK1 = (1 << OCIE0A); // Enable compare interrupt
TCCR0A |= (1 << COM0A0 | 1 << WGM00); //pwm phase correct, toggle OC0A
TCCR0B |= (1 << CS02)|(1 << WGM02); //prescale set to 256
TCCR2A |= (1<<COM2A1)|(1<<WGM21)|(1<<WGM20);//clear OC2A on compare match fast PWM TOP = 0xFF
TCCR2B |= (1<<CS22)|(1<<CS21)|(1<<CS20); //set period of PWM to 17.7ms
TCNT0 = 0; //set bottom of counter to 0
/* enable external interrupt button setup */
EICRA |= (1<<ISC21)|(1<<ISC20); // set ISC2[1:0] to 0b01, so that the external
// interrupt on PB2 is sensitive to rising edge.
EIMSK |= (1<<INT2); // enable interrupts on PB2
/*initialize states*/
button_status = off;
current_state = startTrigger;
sei (); //global interrupt enabled
current_edge = 1; //set rising edge as first ICR timestamp
init_uart(); //call uart lib
while (1) // run indefinitely
{
switch(button_status){
case on:
switch(current_state){
case startTrigger:
trigger();
break;
case startMeasure:
measure();
break;
case startRotate:
rotate();
break;
}
break;
case off:
zero_off();
break;
}
}
}
I have reduced the code to a minimal size
Notice that the 'problem' switch is only stepped when a certain interrupt occurs, as handled by: ISR (TIMER1_CAPT_vect)
The probability is that interrupt is never being triggered.
And now, the shortened code:
//#include <avr/io.h>
//#include <avr/interrupt.h>
//#include <util/delay.h>
#include <stdio.h>
//#include "UART_library.h"
// note, following statement missing from posted code
#include <math.h> // M_PI, sqrt()
//prototypes
void trigger( void );
void measure( void );
void rotate( void );
//states
enum fsm {startTrigger, startMeasure,startRotate};
enum fsm current_state;
int triggered_interrupt;
int main( void )
{
/*initialize states*/
current_state = startTrigger;
while (1) // run indefinitely
{
if( triggeredInterrupt )
{
triggeredInterrupt = 0;
puts( "interrupt triggered" );
}
switch( current_state )
{
case startTrigger:
puts( "mode: startTrigger" );
trigger();
break;
case startMeasure:
puts( "mode: startMeasure" );
measure();
break;
case startRotate:
puts( "mode: startRotate" );
rotate();
break;
} // end switch currentState
} // end while forever
}
void trigger()
{
puts( "Trigger" );
}
void ISR (TIMER1_CAPT_vect)
{
current_state = startMeasure;
}
void measure()
{
puts( "measure" );
current_state = startRotate;
}
void rotate()
{
puts( "rotate" );
current_state = startTrigger;
}
I'm trying to run the following code in c on a beaglebone black (microcontroller running Debian).
The code compiles but terminates right when the pwm_init() function is called.
No printf will execute after this line, even the first in the pwm_init() function.
I tried removing pwm_init(), and then wait_for_pwm() will run normally.
This is a code to setup an interrupt timer on the beaglebone in order to communicate with a DAC through SPI.
The code was running and could communicate before this adding.
/*
*Filename: mems.c
*SPI test program to communicate with AD5666 DAC on Micro Mirror Driver board */
#include <stdint.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include "iolib.h"
#include <unistd.h>
#define DELAY_NS 62500 // Timer period in ns
// PRU Interrupt control registers
#define PRU_INTC 0x00020000 // Start of PRU INTC registers TRM 4.3.1.2
#define PRU_INTC_GER ((volatile uint32_t *)(PRU_INTC + 0x10)) // Global Interrupt Enable, TRM 4.5.3.3
#define PRU_INTC_SICR ((volatile uint32_t *)(PRU_INTC + 0x24)) // Interrupt, TRM 4.5.3.6
#define PRU_INTC_GPIR ((volatile uint32_t *)(PRU_INTC + 0x80)) // Interrupt, TRM 4.5.3.11
// PRU ECAP control registers (i.e. PWM used as a timer)
#define ECAP 0x00030000 // ECAP0 offset, TRM 4.3.1.2
// Using APWM mode (TRM 15.3.2.1) to get timer (TRM 15.3.3.5.1)
#define ECAP_TSCTR ((volatile uint32_t *)(ECAP + 0x00)) // 32-bit counter register, TRM 15.3.4.1.1
#define ECAP_APRD ((volatile uint32_t *)(ECAP + 0x10)) // Period shadow, TRM 15.3.4.1.5, aka CAP3
#define ECAP_ECCTL2 ((volatile uint32_t *)(ECAP + 0x2a)) // Control 2, TRM 15.3.4.1.8
#define ECAP_ECEINT ((volatile uint16_t *)(ECAP + 0x2c)) // Enable interrupt, TRM 15.3.4.1.9
#define ECAP_ECCLR ((volatile uint16_t *)(ECAP + 0x30)) // Clear flags, TRM 15.3.4.1.11
// R30 is the GPIO register
// R31 is the interrupt register
#define NUMBER_OF_COEFS 87
int xn[NUMBER_OF_COEFS] = { 0 };
int ynn[NUMBER_OF_COEFS] = { 0 };
int xy[2];
static double coefs[NUMBER_OF_COEFS] = { -0.003874396983162784,-0.0037425007502381417,0.0007168162935488041,-0.0015837981969284466,0.001324731958160302,0.000940030114550933,0.002909179571989647,0.002970492669088027,0.0037475240063036684,0.003135242276391628,0.002431551570668268,0.0007465565198417194,-0.0010918847362976609,-0.0032610680167253635,-0.0050886443383995035,-0.0064219306251743396,-0.0067757336585719885,-0.00603689840577871,-0.004073405037328031,-0.001084864753089533,0.002607744624181485,0.006446336960328277,0.009805149887731802,0.012005211009068262,0.01248315933178856,0.010855477027307714,0.007038206816858291,0.0013011753812607633,-0.005726736257811221,-0.013085733616184817,-0.019608024169477135,-0.024024160014903175,-0.025137566107801428,-0.022018671074884637,-0.01412798218138592,-0.0014477915111131118,0.015482420337480308,0.03556527369143834,0.057256428960766804,0.07871540989639365,0.09799912606296178,0.1132905004893123,0.12311069228747347,0.1265004803246064,0.12311069228747347,0.1132905004893123,0.09799912606296178,0.07871540989639365,0.057256428960766804,0.03556527369143834,0.015482420337480308,-0.0014477915111131118,-0.01412798218138592,-0.022018671074884637,-0.025137566107801428,-0.024024160014903175,-0.019608024169477135,-0.013085733616184817,-0.005726736257811221,0.0013011753812607633,0.007038206816858291,0.010855477027307714,0.01248315933178856,0.012005211009068262,0.009805149887731802,0.006446336960328277,0.002607744624181485,-0.001084864753089533,-0.004073405037328031,-0.00603689840577871,-0.0067757336585719885,-0.0064219306251743396,-0.0050886443383995035,-0.0032610680167253635,-0.0010918847362976609,0.0007465565198417194,0.002431551570668268,0.003135242276391628,0.0037475240063036684,0.002970492669088027,0.002909179571989647,0.000940030114550933,0.001324731958160302,-0.0015837981969284466,0.0007168162935488041,-0.0037425007502381417,-0.003874396983162784};
#define REF_ON 0x01000008 //command to turn on internal VREF
#define X_OFFSET 3
#define Y_OFFSET 0
#define X_DRIVE 1
#define Y_DRIVE 2
#define SIZEMAT 2
float tabx[SIZEMAT] = { -100, 100 };
float taby[SIZEMAT] = { -100, 100 };
// Forward definitions
int convert_spi(int dac_val,int channel); //formats bytes for write function
inline void pwm_init();
inline void wait_for_pwm_timer();
int* fir_filterXY(int x, int y);
int main(int argc, char **argv){
int i, fd, debug=0, loop=0, user_loop=0;
int x_off=-1, y_off=-1;
int x_val=-1, y_val=-1;
int freq = -1;
unsigned int buf = REF_ON;
unsigned int dac_value = 1; // 0 to 65535 value to set dac output
unsigned int spi_bytes = 0; // spi communication bytes to send
char direction = 0; // Direction of triangle wave ramp
fd = open("/dev/spidev1.0", O_RDWR);
if(fd < 0) printf("spi failed to open\n");
iolib_init();
//Set LDAC control pin to output
iolib_setdir(9,15,1);
//Tying LDAC low will update dac channel as soon as it has new data
pin_low(9,15); //sel0
write(fd,&buf,4); //set internal vref on
// User loop
int valx = 0;
int valy = 0;
int* ass;
int assx = 0;
int assy = 0;
int i = 0;
int freqcnt = 0;
int freqi = 0;
if (freq>1000)
{
freq = 1000;
}
if (freq<1)
{
freq = 1;
}
freqcnt = (int)((1000000000/DELAY_NS)/freq - 1);
spi_bytes = convert_spi(32000, X_OFFSET);//format bytes for write function
write(fd, &spi_bytes, 4);
spi_bytes = convert_spi(32000, Y_OFFSET);//format bytes for write function
write(fd, &spi_bytes, 4);
printf("In user loop with movement frequency of:%i\n", freq);
pwm_init();
valx = 32000;
valy = 32000;
assx = 32000;
assy = 32000;
printf("starting\n");
while (1){
wait_for_pwm_timer();
spi_bytes = convert_spi(assx, X_DRIVE);//format bytes for write function
write(fd, &spi_bytes, 4);
spi_bytes = convert_spi(assy, Y_DRIVE);//format bytes for write function
write(fd, &spi_bytes, 4);
freqi++;
if(freqi >= freqcnt){
valx = (int)((tabx[i]+100) * 320);
valy = (int)((taby[i]+100) * 320);
freqi = 0;
i++;
if (i >= SIZEMAT)
i = 0;
}
ass = fir_filterXY(valx, valy);
assx = *(ass);
assy = *(ass+1);
}
return 0;
}
/* Function: convert_spi
*
* Takes a dac value (0-65535) and a dac channel (or all channels) and generates the appropriate 32bits to send to AD5666 via SPI
*
* INPUTS
* dac_val: sets the voltage output with voltage output= 2.5*(dac_val/65535)
* channel: selects which dac channel to update with dac_val. 0=DACA ,1=DACB, 2=DACC, 3=DACD, 16=all
*
* RETURNS
* spi_data: integer value to send via spi using to update channel with new dac value
*/
int convert_spi(int dac_val,int channel){
int spi_data=0;
unsigned int nibble1;
unsigned int nibble2;
unsigned int nibble3;
unsigned int nibble4;
nibble1= dac_val & 0xF000;
nibble2= dac_val & 0x0F00;
nibble3= dac_val & 0x00F0;
nibble4= dac_val & 0x000F;
spi_data |=(nibble1>>4);
spi_data |=(nibble2<<12);
spi_data |=(nibble3<<12);
spi_data |=(nibble4<<28);
spi_data |=(channel<<12);
return spi_data;
}
// Initializes the PWM timer, used to control output transitions.
// Every DELAY_NS nanoseconds, interrupt 15 will fire
inline void pwm_init(){
printf("Intereupt setup");
*PRU_INTC_GER = 1; // Enable global interrupts
printf("1");
*ECAP_APRD = DELAY_NS / 5 - 1; // Set the period in cycles of 5 ns
printf("2");
*ECAP_ECCTL2 = (1<<9) /* APWM */ | (1<<4) /* counting */;
printf("3");
*ECAP_TSCTR = 0; // Clear counter
printf("4");
*ECAP_ECEINT = 0x80; // Enable compare equal interrupt
printf("5");
*ECAP_ECCLR = 0xff; // Clear interrupt flags
printf("done\n");
}
// Wait for the PWM timer to fire.
// see TRM 15.2.4.26x
inline void wait_for_pwm_timer() {
register unsigned int __R31;
while (!(__R31 & (1 << 30))) {} // Wait for timer compare interrupt
*PRU_INTC_SICR = 15; // Clear interrupt
*ECAP_ECCLR = 0xff; // Clear interrupt flags
}
int* fir_filterXY(int x, int y){
int i = 0;
double temp = 0;
for (i = 0; i < NUMBER_OF_COEFS - 1; i++)
{
xn[i] = xn[i + 1]; //xn est au bout
}
xn[NUMBER_OF_COEFS-1] = x;
//multiplier par les coef
for (i = 0; i < NUMBER_OF_COEFS; i++)
{
temp += xn[NUMBER_OF_COEFS - i] * coefs[i];
}
xy[0] = (int)(temp+0.5);
for (i = 0; i < NUMBER_OF_COEFS - 1; i++)
{
ynn[i] = ynn[i + 1];
}
ynn[NUMBER_OF_COEFS-1] = y;
temp = 0;
for (i = 0; i < NUMBER_OF_COEFS; i++)
{
temp += ynn[NUMBER_OF_COEFS - i] * coefs[i];
}
xy[1] = (int)(temp + 0.5);
return xy;
}
A couple of recommendations:
printf() can occasionally lag in its output. To be very sure that nothing is being printed, call fflush(stdout) after the print line. This will flush the stdout buffer-- if nothing is printed after the flush, then the println() really is not being executed.
How is your program terminating? If execution does not continue past the pwm_init() function, that almost certainly means that something bad is happening with the memory locations you are writing to. Double check that your register values are correct and that your program isn't being killed due to invalid memory access.
I am interfacing LM35 with Atmega8. To display digits I use 7 segment LED anode display that I connect to AVR both ends (it handles it without transistors so why not). Strange thing happens:
res value after assigning it from adc is 237 (23.7 degrees). I want to print on my display the first digit (2).
If I leave last line in the while commented out, the display first shows digit 2 correctly but after the first delay it shows 1 instead of 2. Otherwise I get correctly digit 2. Why is this happening?
#ifndef F_CPU
#define F_CPU 1000000UL
#endif // F_CPU
#include <avr/io.h>
#include <util/delay.h>
#define DELAY_IN_MS 500 /* 0.5 sec */
int numbers[] = {
0b01000000,
0b01110011,
0b00100100,
0b00100001,
0b00010011,
0b00001001,
0b00001000,
0b01100011,
0b00000000,
0b00000001,
0b11111111 // off
};
uint8_t digits[3];
void initADC()
{
ADMUX=(1<<REFS1)|(1<<REFS0);
ADCSRA=(1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
}
uint16_t ReadADC(uint8_t ch)
{
//Select ADC Channel ch must be 0-7
ch=ch&0b00000111;
ADMUX|=ch;
//Start Single conversion
ADCSRA|=(1<<ADSC);
//Wait for conversion to complete
while(!(ADCSRA & (1<<ADIF)));
//Clear ADIF by writing one to it
ADCSRA|=(1<<ADIF);
return(ADC);
}
int main()
{
DDRD = 0xFF;
PORTD = 0xFF;
DDRB = 0b00000001;
PORTB = 1;
initADC();
uint16_t adc_value;
uint16_t res;
while(1)
{
adc_value = 0;
for (int i = 0; i < 250; i++)
{
adc_value += ReadADC(0);
}
adc_value=(adc_value/25)/4;
res = adc_value;
for(int j = 2; j >= 0; j--) {
digits[j] = res%10;
res /= 10;
}
uint8_t dig = digits[0];
PORTD = numbers[dig];
_delay_ms(DELAY_IN_MS);
// if following is uncommented there blinks digit two correctly
// if commented there is unblinking digit 1
PORTD = numbers[10]; // display off
}
return 0;
}
The problem was induction.
My circuit had many wires in non-soldering-field. When the display was on, there was a lot of induction going on changing resulting voltage on ADC input/LM35 output.
There is more than one solution.
1) Software: I moved ADC conversion into the interruption function. It turns of the displays, converts value from lm35 and displays digit on proper display. It happens so fast that the eye cant perceive it.
I prefer this one for now, because it makes my circuit simpler.
2) Hardware: adding L/C or R/C filter to adc pin should resolve the issue.
Full code for 1)
#ifndef F_CPU
#define F_CPU 1000000UL
#endif // F_CPU
#include <avr/io.h>
#include <util/delay.h>
#include <avr/interrupt.h>
#define DELAY_IN_MS 5000 /* ms */
#define NUM_OF_MEASUREMENTS 100
#define NUM_DISPLAYS 3
int numbers[] = {
0b10000001,
0b10011111,
0b10100100,
0b10010100,
0b10011010,
0b11010000,
0b11000000,
0b10011101,
0b10000000,
0b10010000,
0b11111111 // off
};
int display = 0;
uint8_t digits[NUM_DISPLAYS];
volatile uint16_t adc_values[NUM_OF_MEASUREMENTS];
int adc_read_cycle_index = 0;
uint32_t res;
void initADC()
{
ADMUX=(1<<REFS1)|(1<<REFS0);
ADCSRA=(1<<ADEN)|(1<<ADPS2);
}
uint16_t ReadADC(uint8_t ch)
{
//Select ADC Channel ch must be 0-7
ch=ch&0b00000111;
ADMUX|=ch;
//Start Single conversion
ADCSRA|=(1<<ADSC);
//Wait for conversion to complete
while (ADCSRA & (1<<ADSC));
return(ADC);
}
void readDegrees()
{
adc_values[adc_read_cycle_index] = (ReadADC(0)*10)/4;
if(adc_read_cycle_index + 1 == NUM_OF_MEASUREMENTS) {
adc_read_cycle_index = 0;
} else {
adc_read_cycle_index++;
}
}
void fetchTemperatureDigits() {
res = 0;
for(int i = 0; i < NUM_OF_MEASUREMENTS; i++) {
res += adc_values[i];
}
res /= NUM_OF_MEASUREMENTS;
for(int j = 2; j >= 0; j--) {
digits[j] = res%10;
res = res / 10;
}
}
void initTimer0()
{
// Prescaler = FCPU/64
TCCR0|=(1<<CS01);//|(1<<CS00);
//Enable Overflow Interrupt Enable
TIMSK|=(1<<TOIE0);
//Initialize Counter
TCNT0=0;
}
ISR(TIMER0_OVF_vect)
{
// turn off displays
PORTD = numbers[10];
// read ADC and convert to degrees
readDegrees();
// turn on proper anode
PORTB &= 0b11111000;
PORTB |= (1<<display);
// show digit
PORTD = numbers[digits[display]];
// show decimal point for second display (21.5 - second display shows "1.")
if(display == 1) {
PORTD &= 0b01111111;
}
// next display for next interruption
display++;
if(display == NUM_DISPLAYS) {
display = 0;
}
}
int main()
{
initADC();
for(int i = 0; i < NUM_OF_MEASUREMENTS; i++) {
readDegrees();
}
DDRD = 0xFF;
PORTD = 0;
DDRB |= 0b00000111;
PORTB |= 1;
initTimer0();
sei();
while(1) {
fetchTemperatureDigits();
_delay_ms(DELAY_IN_MS);
}
return 0;
}