Trouble setting up PWM using bitwise operations PIC12F615 MPLAB X - bit-manipulation

For whatever reason, I have never been able to use bitshifts in MPLAB. Here is some code I'm working on to setup PWM on the PIC12F615:
// configuration of PWM
void configPWM(void) {
// Disable the PWM pin (CCP1) output drivers by setting the associated TRIS bit.
TRISIO |= 1 << 2; //
// Set the PWM period by loading the PR2 register.
PR2 = 0x65; // from datasheet???
// Configure the CCP module for the PWM mode by loading the CCP1CON register with the appropriate values. 0b00001100
CCP1CON = 0x0C; //
// Set the PWM duty cycle by loading the CCPR1L register and DC1B bits of the CCP1CON register.
CCPR1L = 0x88; // about half duty cycle
// Configure and start Timer2:
// Clear the TMR2IF interrupt flag bit of the PIR1 register.
PIR1 &= ~(1 << 1); // clearing bit 1
// Set the Timer2 prescale value by loading the T2CKPS bits of the T2CON register.
T2CON |= 1 << 1; // setting "1x"
// Enable Timer2 by setting the TMR2ON bit of the T2CON register.
T2CON |= 1 << 2; // setting bit 1
// Enable PWM output after a new PWM cycle has started:
// Wait until Timer2 overflows (TMR2IF bit of the PIR1 register is set).
while(!(PIR1 & (1 << 1))) {
__delay_ms(1);
}
// Enable the CCP1 pin output driver by clearing the associated TRIS bit.
TRISIO &= ~(1 << 2); // clearing GP2, CCP1 pin
}
As you can see I'm using bitshifts heavily to set and clear bits. However, I get this error 9 times on the block of code above when I do an MISRA check:
main.c:72:17: [misra-c2012-10.1] Operands shall not be of an
inappropriate essential type
Is there a better way to do this? On TM4C123G I did not have this issue using Keil uVision4 IDE. I'm currently using MPLAB X IDE v5.45.

So i make an answer :
MISRA don't allow shift operations on signed types, because the result depends on how your compiler chooses to represent types and how it performs shifts.
So for e.g. you had to switch to:
TRISIO |= 1u << 2;

Related

VirtualBox crashing when assembly "sti" is executed when testing Operating System

I'm currently attempting to build my own Operating System and have run into an issue when trying to test out my kernel code using VirtualBox.
The real issue arises when I call the assembly instruction sti as I'm currently attempting to implement an interrupt descriptor table and communicate with the PICs.
Here is the code that calls it. It's a function called kernel_main that is called from another assembly file. That file simply sets up the stack before executing any code from the OS, but there hasn't been any issues there, and everything works fine until I add the instruction asm("sti"); to the following code:
/* main function of our kernal
* accepts the pointer to multiboot and the magic code (no particular reason to take the magic number)
*
* use extern C to prevent gcc from changing the name
*/
extern "C" void kernel_main(void *multiboot_structure, uint32_t magic_number)
{
// can't use the standard printf as we're outside an OS currently
// we don't have access to glibc so we write our own printf
printf_boot_message("kernel.....\n");
// create the global descriptor table
GlobalDescriptorTable gdt;
// create the interrupt descriptor table
InterruptHandler interrupt_handler(&gdt);
// enable interrupts (test)
asm("sti"); // <- causes crash
// random debug printf
printf_boot_message("sti called\n");
// kernal never really stops, inf loop
while (1)
;
}
Below is the virtual box debug output, I've googled around for VINF_EM_TRIPLE_FAULT but mostly found RAM related issues that I don't think apply to me. The printf calls in the above code execute as expected followed by the VM immediately crashing stating the following:
Link to output as it's too large to post here: https://pastebin.com/jfPfhJUQ
Here is my interrupt handling code:
* Implementations of the interrupt handling routines in sys_interrupts.h
*/
#include "sys_interrupts.h"
#include "misc.h"
//handle() is used to take the interrupt number,
//i_number, and the address to the current CPU stack frame.
uint32_t InterruptHandler::handle(uint8_t i_number, uint32_t crnt_stkptr)
{
// debug
printf(" INTERRUPT");
// after the interrupt code has been executed,
// return the stack pointer so that the CPU can resume
// where it left off.
// this works for now as we do not have multiple
// concurrent processes running, so there is no issue
// of handling the threat number.
return crnt_stkptr;
}
// define the global descriptor table
InterruptHandler::_gate_descriptor InterruptHandler::interrupt_desc_table[N_ENTRIES];
// define the constructor. Takes a pointer to the global
// descriptor table
InterruptHandler::InterruptHandler(GlobalDescriptorTable* global_desc_table)
{
// grab the offset of the usable memory within our global segment
uint16_t seg = global_desc_table->CodeSegmentSelector();
// set all the entries in the IDT to block request initially
for (uint16_t i = 0; i < N_ENTRIES; i++)
{
// create an a gate for a system level interrupt, calling the block function (does nothing) using seg as its memory.
create_entry(i, seg, &block_request, PRIV_LVL_KERNEL, GATE_INTERRUPT);
}
// create a couple interrupts for 0x00 and 0x01, really 0x20 and 0x21 in memory
//create_entry(BASE_I_NUM + 0x00, seg, &isr0x00, PRIV_LVL_KERNEL, GATE_INTERRUPT);
//create_entry(BASE_I_NUM + 0x01, seg, &isr0x01, PRIV_LVL_KERNEL, GATE_INTERRUPT);
// init the PICs
pic_controller.send_master_cmd(PIC_INIT);
pic_controller.send_slave_cmd(PIC_INIT);
// tell master pic to add 0x20 to any interrupt number it sends to CPU, while slave pic sends 0x28 + i_number
pic_controller.send_master_data(PIC_OFFSET_MASTER);
pic_controller.send_slave_data(PIC_OFFSET_SLAVE);
// set the interrupt vectoring to cascade and tell master that there is a slave PIC at IRQ2
pic_controller.send_master_data(ICW1_INTERVAL4);
pic_controller.send_slave_data(ICW1_SINGLE);
// set the PICs to work in 8086 mode
pic_controller.send_master_data(ICW1_8086);
pic_controller.send_slave_data(ICW1_8086);
// send 0s
pic_controller.send_master_data(DEFAULT_MASK);
pic_controller.send_slave_data(DEFAULT_MASK);
// tell the cpu to use the table
interrupt_desc_table_pointerdata idt_ptr;
//set the size
idt_ptr.table_size = N_ENTRIES * sizeof(_gate_descriptor) - 1;
// set the base address
idt_ptr.base_addr = (uint32_t)interrupt_desc_table;
// use lidt instruction to load the table
// the cpu will map interrupts to the table
asm volatile("lidt %0" : : "m" (idt_ptr));
// issue debug print
printf_boot_message(" 2: Created Interrupt Desc Table...\n");
}
// define the destructor of the class
InterruptHandler::~InterruptHandler()
{
}
// function to make entries in the IDT
// takes the interrupt number as an index, the segment offset it used to specify which memory segment to use
// a pointer to the function to call, the flags and access level.
void InterruptHandler::create_entry(uint8_t i_number, uint16_t segment_desc_offset, void (*isr)(), uint8_t priv_lvl, uint8_t desc_type)
{
// set the i_number'th entry to the given params
// take the lower bits of the pointer
interrupt_desc_table[i_number].handler_lower_bits = ((uint32_t)isr) & 0xFFFF;
// take the upper bits
interrupt_desc_table[i_number].handler_upper_bits = (((uint32_t)isr) >> 16) & 0xFFFF;
// calculate the privilage byte, setting the correct bits
interrupt_desc_table[i_number].priv_lvl = 0x80 | ((priv_lvl & 3) << 5) | desc_type;
interrupt_desc_table[i_number].segment_desc_offset = segment_desc_offset;
// reserved byte is always 0
interrupt_desc_table[i_number].reserved_byte = 0;
}
// need a function to block or ignore any requests
// that we dont want to service. Requests could be caused
// by devices we haven't yet configured when testing the os.
void InterruptHandler::block_request()
{
// do nothing
}
// function to tell the CPU to send interrupts
// to this table
void InterruptHandler::set_active()
{
// call sti assembly to start interrup poling at the CPU level
asm volatile("sti"); // <- calling this crashes the kernel
// issue debug print
printf_boot_message(" 4: Activated sys interrupts...\n");
}
And here is the code for my GDT, I followed the os dev wiki guide for this:
#include "global_desc_table.h"
/**
* A code segment is identified by flag 0x9A, cannot write to a code segment
* while a data segment is identified by flag 0x92
*
* Based on the C code present on OSDEV Wiki
*/
GlobalDescriptorTable::GlobalDescriptorTable() : nullSegmentSelector(0, 0, 0),
unusedSegmentSelector(0, 0, 0),
codeSegmentSelector(0, 64*1024*1024, 0x9A),
dataSegmentSelector(0, 64*1024*1024, 0x92)
{
//8 bytes defined, but processor expects 6 bytes only
uint32_t i[2];
//first 4 bytes is address of table
i[0] = (uint32_t)this;
//second 4 bytes, the high bytes, are size of global desc table
i[1] = sizeof(GlobalDescriptorTable) << 16;
// tell processor to use this table using its ldgt function
asm volatile("lgdt (%0)" : : "p" (((uint8_t *) i) + 2));
// issue debug print
printf_boot_message(" 1: Created Global Desc Table...\n");
}
// function to get the offset of the datasegment selector
uint16_t GlobalDescriptorTable::DataSegmentSelector()
{
// calculate the offset by subtracting the table's address from the datasegment's address
return (uint8_t *) &dataSegmentSelector - (uint8_t*)this;
}
// function to get the offset of the code segment
uint16_t GlobalDescriptorTable::CodeSegmentSelector()
{
// calculate the offset by subtracting the table's address from the code segment's address
return (uint8_t *) &codeSegmentSelector - (uint8_t*)this;
}
// default destructor
GlobalDescriptorTable::~GlobalDescriptorTable()
{
}
/**
* The constructor to create a new entry segment, set the flags, determine the formatting for the limit, and set the base
*/
GlobalDescriptorTable::SegmentDescriptor::SegmentDescriptor(uint32_t base, uint32_t limit, uint8_t flags)
{
uint8_t* target = (uint8_t*)this;
//if 16 bit limit
if (limit <= 65536)
{
// tell processor that this is a 16bit entry
target[6] = 0x40;
} else {
// if the last 12 bits of limit are not 1s
if ((limit & 0xFFF) != 0xFFF)
{
limit = (limit >> 12) - 1;
} else {
limit >>= 12;
}
// indicate that there was a shift of 12 done
target[6] = 0xC0;
}
// set the lower and upper 2 lowest bytes of limit
target[0] = limit & 0xFF;
target[1] = (limit >> 8) & 0xFF;
//the rest of limit must go in lower 4 bit of byte 6, and byte 5
target[6] |= (limit >> 16) & 0xF;
//encode the pointer
target[2] = base & 0xFF;
target[3] = (base >> 8) & 0xFF;
target[4] = (base >> 16) & 0xFF;
target[7] = (base >> 24) & 0xFF;
// set the flags
target[5] = flags;
}
/**
* Define the methods to get the base pointer from an segment and
* the limit for a segment, taken from os wiki
*/
uint32_t GlobalDescriptorTable::SegmentDescriptor::Base()
{
// simply do the reverse of wht was done to place the pointer in
uint8_t* target = (uint8_t*) this;
uint32_t result = target[7];
result = (result << 8) + target[4];
result = (result << 8) + target[3];
result = (result << 8) + target[2];
return result;
}
uint32_t GlobalDescriptorTable::SegmentDescriptor::Limit()
{
uint8_t* target = (uint8_t *)this;
uint32_t result = target[6] & 0xF;
result = (result << 8) + target[1];
result = (result << 8) + target[0];
//check if there was a shift of 12
if (target[6] & 0xC0 == 0xC0)
{
result = (result << 12) & 0xFFF;
}
return result;
}
i[0] = (uint32_t)this;
//second 4 bytes, the high bytes, are size of global desc table
i[1] = sizeof(GlobalDescriptorTable) << 16;
I've had the same problem, just swap the 0 and 1 in between:
i[1] = (uint32_t)this;
//second 4 bytes, the high bytes, are size of global desc table
i[0] = sizeof(GlobalDescriptorTable) << 16;
That's the problem if you are following the same tutorial and I think you do if you came here.
Sometimes due to wrong idtr value also(invalid pointer causing crash)
check the idtr reg value in vbox log
if u load idt in protected mode address of idt shows some wierd changes(shifted left 16bits or some value in lower 16 bit)
try changing pointer according to that(thats how i did) or use lidt in before entering protected mode(this is also tested)
There was a bug in my GDT that forced the kernel to read an invalid pointer from the segment. This caused a seg fault.

Frequency measurement with 8051 microcontroller

I simply want to continuously calculate the frequency of a sine signal with a comparator input (on the falling edges). The effective target frequency is about ~122 Hz and my implementation works most the time, but sometimes it calculates a wrong frequency with always about ~61Hz (which cannot be possible, I verified this with an oscilloscope).
It seems my implementation has a weakness, perhaps in form of a race condition or misuse of the timer, since it uses concurrent interrupt service routines and manually starts and stops the timer.
I also think the bug correlates with the measured frequency of about ~122Hz, because one timer overflow is pretty much the same:
One Timer Overflow = 1 / (1/8 MHz * 2^16 [Bits]) = 122.0703125 Hz
I am using a 8051 microcontroller (Silicon Labs C8051F121) with the following code:
// defines
#define PERIOD_TIMER_FREQ 8000000.0 // Timer 3 runs at 8MHz
#define TMR3_PAGE 0x01 /* TIMER 3 */
#define CP1F_VECTOR 12 /* comparator 1 falling edge */
#define TF3_VECTOR 14 /* timer3 reload timer */
sfr TMR3CN = 0xC8; /* TIMER 3 CONTROL */
sfr TMR3L = 0xCC; /* TIMER 3 LOW BYTE */
sfr TMR3H = 0xCD; /* TIMER 3 HIGH BYTE */
// global variables
volatile unsigned int xdata timer3_overflow_tmp; // temporary counter for the current period
volatile unsigned int xdata timer3_lastValue; // snapshot of the last timer value
volatile unsigned int xdata timer3_overflow; // current overflow counter, used in the main routine
volatile unsigned int xdata tempVar; // temporary variable
volatile unsigned long int xdata period; // the caluclated period
volatile float xdata period_in_SI; // calculated period in seconds
volatile float xdata frequency; // calculated frequency in Hertz
// Comparator 1 ISR has priority "high": EIP1 = 0x40
void comp1_falling_isr (void) interrupt CP1F_VECTOR
{
SFRPAGE = TMR3_PAGE;
TMR3CN &= 0xfb; // stop timer 3
timer3_lastValue = (unsigned int) TMR3H;
timer3_lastValue <<= 8;
timer3_lastValue |= (unsigned int) TMR3L;
// check if timer 3 overflow is pending
if (TMR3CN & 0x80)
{
timer3_overflow_tmp++; // increment overflow counter
TMR3CN &= 0x7f; // Clear over flow flag. This will also clear a pending interrupt request.
}
timer3_overflow = timer3_overflow_tmp;
// Reset all the timer 3 values to zero
TMR3H = 0;
TMR3L = 0;
timer3_overflow_tmp = 0;
TMR3CN |= 0x04; // restart timer 3
}
// Timer 3 ISR has priority "low", which means it can be interrupted by the
// comparator ISR: EIP2 = 0x00
// Timer 3 runs at 8MHz in 16 bit auto-reload mode
void timer3_isr(void) interrupt TF3_VECTOR using 2
{
SFRPAGE = TMR3_PAGE;
timer3_overflow_tmp++;
TMR3CN &= 0x7f; // Clear over flow flag. This will also clear a pending interrupt request.
}
void main(void)
{
for(;;)
{
...
calcFrequencyLabel: // this goto label is a kind of synchronization mechanism
// and is used to prevent race conditions caused by the ISRs
// which invalidates the current copied timer values
tempVar = timer3_lastValue;
period = (unsigned long int)timer3_overflow;
period <<= 16;
period |= (unsigned long int)timer3_lastValue;
// If both values are not equal, a race condition has been occured.
// Therefore the the current time values are invalid and needs to be dropped.
if (tempVar != timer3_lastValue)
goto calcFrequencyLabel;
// Caluclate period in seconds
period_in_SI = (float) period / PERIOD_TIMER_FREQ;
// Caluclate period in Hertz
frequency = 1 / period_in_SI; // Should be always stable about ~122Hz
...
}
}
Can someone please help me to find the bug in my implementation?
I can't pin-point the particular bug, but you have some problems in this code.
The main problem is that the 8051 was not a PC, but rather it was the most horrible 8-bit MCU to ever become mainstream. This means that you should desperately avoid things like 32 bit integers and floating point. If you disassemble this code you'll see what I mean.
There is absolutely no reason why you need to use floating point here. And 32 bit variables could probably be avoided too. You should use uint8_t whenever possible and avoid unsigned int too. Your C code shouldn't need to know the time in seconds or the frequency in Hz, but just care about the number of timer cycles.
You have multiple race condition bugs. Your goto hack in main is a dirty solution - instead you should prevent the race condition from happening in the first place. And you have another race condition between the ISRs with timer3_overflow_tmp.
Every variable shared between an ISR and main, or between two different ISR with different priorities, must be protected against race conditions. This means that you must either ensure atomic access or use some manner of guard mechanism. In this case, you could probably just use a "poor man's mutex" bool flag. The other alternative is to change to an 8 bit variable and write the code accessing it in inline assembler. Generally, you cannot have atomic access on an unsigned int on a 8-bit core.
With a slow edge as you would have for low frequency sine and insufficient hysteresis in the input (the default being none), it would only take a little noise for a rising edge to look like a falling edge and result in half the frequency.
The code fragment does not include the setting of CPT1CN where the hysteresis is set. For your signal you probably need to max it out, and ensure that the peak-to-peak noise on your signal is less that 30mV.

Using 4 16bit timers for 400hz PWM

I'm dealing with arduino mega based quadcopter and trying to make PWM frequency for 4 motors - 400hz each. I've found an interesting solution where 4 ATmega2560 16bit timers are used to control 4 ESCs with PWM so it could reach 400hz frequency. 700 to 2000µs are normal pulse widths ESC are dealing with.
1sec/REFRESH_INTERVAL = 1/0.0025 = 400hz.
this is servo.h lib:
#define MIN_PULSE_WIDTH 700 // the shortest pulse sent to a servo
#define MAX_PULSE_WIDTH 2000 // the longest pulse sent to a servo
#define DEFAULT_PULSE_WIDTH 1000 // default pulse width when servo is attached
#define REFRESH_INTERVAL 2500 // minimum time to refresh servos in microseconds
#define SERVOS_PER_TIMER 1 // the maximum number of servos controlled by one timer
#define MAX_SERVOS (_Nbr_16timers * SERVOS_PER_TIMER)
The problem is to make it work each PWM should be controlled with 1 16bit timer. Otherwize, say, 2 escs on 1 timer would give 200hz. So all of 16bit timers are busy controlling 4 ESC but I still need to read input PPM from receiver. To do so I need at least one more 16bit timer which I don't have anymore. It's still one 8bit timer free bit it can only read 0..255 numbers while normal number escs operate with are 1000..2000 and stuff.
So what would happen if I'll use same 16bit timer for both pwm and ppm reading? Would it work? Would it decrease speed drastically? I have arduino working in pair with Raspberry Pi which controls data filtering, debugging, and stuff, is it better to move ppm reading to Raspberry?
To answer one of your questions:
So what would happen if I'll use same 16bit timer for both pwm and ppm
reading? Would it work?
Yes. When your pin change interrupt fires you may just read the current TCNT value to find out how long it has been since the last one. This will not in any way interfere with the timer's hardware PWM operation.
Would it decrease speed drastically?
No. PWM is done by dedicated hardware, software operations running at the same time will not affect its speed and neither will any ISRs you may have activated for the corresponding timer. Hence, you can let the timer generate the PWM as desired and still use it to a) read the current counter value from it and b) have an output compare and/or overflow ISR hooked to it to create a software-extended timer.
Edit in response to your comment:
Note that the actual value in the TCNT register is the current timer (tick) count at any moment, irrespective of whether PWM is active or not. Also, the Timer OVerflow interrupt (TOV) can be used in any mode. These two properties allow to make a software-extended timer for arbitrary other time measurement tasks via the following steps:
Install and activate a timer overflow interrupt for the timer/counter you want to use. In the ISR you basically just increment a (volatile!) global variable (timer1OvfCount for example), which effectively counts timer overflows and thus extends the actual timer range. The current absolute tick count can then be calculated as timer1OvfCount * topTimerValue + TCNTx.
When an event occurs, e.g a rising edge on one pin, in the handling routine (e.g. pin-change ISR) you read the current timer/couter (TCNT) value and timer1OvfCount and store these values in another global variable (e.g. startTimestamp), effectively starting your time measurement.
When the second event occurs, e.g. a falling edge on one pin, in the handling routine (e.g. pin-change ISR) you read the current timer/couter (TCNT) value and timer1OvfCount. Now you have the timestamp of the start of the signal in startTimestamp and the timestamp of the end of the signal in another variable. The difference between these two timestamps is exactly the duration of the pulse you're after.
Two points to consider though:
When using phase-correct PWM modes the timer will alternate between counting up and down successively. This makes finding the actual number of ticks passed since the last TOV interrupt a little more complicated.
There may be a race condition between one piece of code first reading TCNT and then reading timer1OvfCount, and the TOV ISR. This can be countered by disabling interrupts, then reading TCNT, then reading timer1OvfCount, and then checking the TOV interrupt flag; if the flag is set, there's a pending, un-handled overflow interrupt -> enable interrupts and repeat.
However, I'm pretty sure there are a couple of library functions around to maintain software-extended timer/counters that do all the timer-handling for you.
what is unit of 700 and 2000?I guess usec.You have not exaplained much in your question but i identified that you need pulses of 25msec duration in which 700 usec on time may be 0 degree and 2000 may be for 180 degree now pulse input of each servo may be attached with any GPIO of AVR.and this GPIOs provide PWM signal to Servo.so i guess you can even control this all motors with only one timer.With this kind of code:
suppose you have a timer that genrate inturrupt at every 50 usec.
now if you want 700 usec for motor1,800 usec for motor 2,900 usec for motor 3 & 1000 usec for motor 4 then just do this:
#define CYCLE_PERIOD 500 // for 25 msec = 50 usec * 500
unsigned short motor1=14; // 700usec = 50x14
unsigned short motor2=16; // 800usec
unsigned short motor3=18; // 900usec
unsigned short motor4=20; // 1000usec
unsigned char motor1_high_flag=1;
unsigned char motor2_high_flag=1;
unsigned char motor3_high_flag=1;
unsigned char motor4_high_flag=1;
PA.0 = 1; // IO for motor1
PA.1 = 1; // IO for motor2
PA.2 = 1; // IO for motor3
PA.3 = 1; // IO for motor4
void timer_inturrupt_at_50usec()
{
motor1--;motor2--;motor3--;motor4--;
if(!motor1)
{
if(motor1_high_flag)
{
motor1_high_flag = 0;
PA.0 = 0;
motor1 = CYCLE_PERIOD - motor1;
}
if(!motor1_high_flag)
{
motor1_high_flag = 1;
PA.0 = 1;
motor1 = 14; // this one is dummy;if you want to change duty time update this in main
}
}
if(!motor2)
{
if(motor2_high_flag)
{
motor2_high_flag = 0;
PA.1 = 0;
motor2 = CYCLE_PERIOD - motor2;
}
if(!motor2_high_flag)
{
motor2_high_flag = 1;
PA.1 = 1;
motor2 = 16;
}
}
if(!motor3)
{
if(motor3_high_flag)
{
motor3_high_flag = 0;
PA.2 = 0;
motor3 = CYCLE_PERIOD - motor3;
}
if(!motor3_high_flag)
{
motor3_high_flag = 1;
PA.2 = 1;
motor3 = 18;
}
}
if(!motor4)
{
if(motor4_high_flag)
{
motor4_high_flag = 0;
PA.3 = 0;
motor4 = CYCLE_PERIOD - motor4;
}
if(!motor4_high_flag)
{
motor4_high_flag = 1;
PA.3 = 1;
motor4 = 19;
}
}
}
& tell me what is ESC?

Timer1 acting weird on Arduino UNO (ATMEGA328)

I am trying to implement a simple timer1 example that I saw on YouTube: http://youtu.be/Tj6xGtwOlB4?t=22m7s . The example was in c++ for stand alone ATMEGA328 chip and I am trying to get it to work on the Arduino UNO. Here is my working code:
void setup() {
//initialize port for LED
DDRB = 0b11111111; //initialize port B as output (really only care about 5th bit)
PORTB = 0b00000000; //set ouput values to zero
TCCR1A = 0; //clear control register A (not sure that I need this)
TCCR1B |= 1<<CS10; //no prescaler, turns on CS10 bit of TCCR1B
}
void loop() {
if (TCNT1 >= 255){
TCNT1 = 0; //resets timer to zero
PORTB ^=1<<PINB5; //1<<PINB5 is same as 0b00100000, so this toggles bit five of port b which is pin 13 (red led) on Arduino
}
}
Everything is working, but TCNT1 will only count up to 255. If I set the value in the if-statement to anything higher, the code in the if statement is never executed. Timer1 should be a 16-bit timer, so it does not make sense why the count stops at 255. Is arduino doing something behind the scenes to mess this up? It seems to work just fine in the example on youtube (without arduino).
First of all.... Why do you set the registers? Arduino's only benefit is that it wraps up some functions, so why not use it? Instead of
DDRB = 0b11111111;
PORTB = 0b00000000;
...
PORTB ^=1<<PINB5;
use simply
int myoutpin = XXXX; // Put here the number of the ARDUINO pin you want to use as output
...
pinMode(myoutpin, OUTPUT);
...
digitalWrite(myoutpin, !digitalRead(myoutpin));
I think that probably there are some similar functions for the timer too..
As for your question, I tried this code:
// the setup routine runs once when you press reset:
void setup() {
TCCR1A = 0; //clear control register A (not sure that I need this)
TCCR1B |= 1<<CS10; //no prescaler, turns on CS10 bit of TCCR1B
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
if (TCNT1 >= 12000){
TCNT1 = 0; //resets timer to zero
Serial.println("Timer hit");
}
}
in a simulator and it works well; I should try it with a real Arduino, but I haven't any at the moment... As soon as i get one I'll try to use it
I've encountered the same problem, in the Atmel documentation, I found that other pins influence the counter mode. That is, the pins: WGM13,WGM12,WGM11,WGM10 are 0,1,0,0 respectively, the counter will be in CTC mode, meaning that it will count up to the value of OCR1A instead of (2^16-1) which might be the case in your code.
WGM11,WGM10 are bits 1,0 in TCCR1A and WGM13,WGM12 are bits 4,3 in TCCR1B so setting them to zero should do the job.
I had some thing like this with one of my code. I could not able to find the exact reason for the issue. At last I remove both setup and loop function an replace those with c code.
Then it work fine. If you need those function then start code by clear both TCCR1A and TCCR1B register. I hope this is happened due to Arduino IDE not sure. But it works.

16-bit timer in AVR CTC mode

I'm trying to achieve that with an Arduino Uno board (ATmega328, 16 MHz). So I searched through the Internet and came up with something like this:
unsigned long Time=0;
int main (void)
{
Serial.begin(9600);
cli();
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
OCR1A = 15999; // Compare value
TCCR1B |= (1 << WGM12)| (1 << CS10); // Prescaler
TIMSK1 |= (1 << OCIE1A); // Enable timer compare interrupt
sei();
while(1) {
Serial.println(TCNT1);
}
return 0;
}
ISR(TIMER1_COMPA_vect)
{
Time++;
Serial.println(Time);
}
I'm trying to achieve a frequency of 1 kHz, so I'll be able to create intervals which are a couple of milliseconds long.
That's why I chose the comparison value to be 15999 (so 16000-1) and the prescaler to be equal to 1, so I get (at least what I believe to be the right calculation):
Frequency = 16.000.000 MHz/16000 = 1000 Hz = 1 kHz
The problem now is that, even though the Serial.println(TCNT1) shows me numbers counted up to 16000, back to zero, up to 16000, back to zero,..., Serial.println(Time) just counts up to 8, and it just stops counting although TCNT1 is still counting.
I thought about some kind of overflow somewhere, but I could not think about where; the only thing I came up with is that the comparison value might be too big which is -as I think - obviously not the case since 2^16 -1=65.535>15999.
If I, for instance, make the prescaler, let's say 64, and leave the comparison value, Time counts as expected. So I'm wondering: Why does ISR() stops getting called at a value of 8, but works when bringing up the prescaler?
I'm not sure, but depending on the version of Arduino you use, the println call would be blocking. If you call it faster than it can complete in your ISR, the stack will overflow.
If you want higher resolution timing, maybe try differencing the getMicroseconds result in your Loop(). You should cycle in Loop() far faster than once per millisecond.
If you want to do something once per millisecond, capture a start microseconds, and then subtract it from the current microseconds in a conditional in your Loop() function. When you see more than 1000 do the task...
It seems like the resolution of the timer was too much for my Arduino Uno (16 MHz). Chosing a lower resolution (i.e higher compare value) fixed the issue for me.