Timer1 acting weird on Arduino UNO (ATMEGA328) - c++

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.

Related

Can't get past for/while loop in Arduino

New to Arduino, I have tried to make a for or a while loop to do a delay, instead of the delay() function. Have tried a LOT of values but the LED remains HIGH, it works if I use the delay() function. Note that I'm not going to use this code as delay, I just tried it and now I can't understand what goes wrong.
Board is a Nano Every, I use Arduino IDE, Fcpu = 8MHz.
const byte ledPin = 13;
byte ledState = HIGH;
pinMode(ledPin, OUTPUT);
void loop() {
unsigned long i = 0;
// read the state of the switch into a local variable:
//enaState = digitalRead(sw1);
//dirState = digitalRead(sw2);
while (i < 10000000)
{
i++;
}
//delay(1000);
ledState ^= 1;
digitalWrite(ledPin, ledState);
i = 0;
}
Adding volatile to avoid being removed by optimization works.
volatile unsigned long i = 0;
The arduino compiler by default runs with all optimizations enabled, to reduce code size and improve speed. Since at least with the Arduino IDE, source-line debugging is not possible on the Arduino itself, this normally doesn't make a visible difference for development. The above code snippet is a rare example where it does.
How to disable optimization, if one really wants to do it, is described in this question: VSCode disabling Arduino compilation optimizations for debugging (thanks #dmaxime).

Issues creating light sequence with pause button ARDUINO

So I am trying to create a program that runs various light sequences using an Arduino board. I am not very familiar with C++ so I feel that my lack of syntax knowledge is preventing me from accomplishing my goal.
My idea is to have various light sequences that are played depending on what button is pressed on an infrared remote. The amount of time that a light is on or off may or may not be the same as that of another light. Unfortunately, the sequences do not seem to be working which indicates that the issue is likely with the toggleLight function.
I also wanted there to be a button that allows the user to pause the sequence (no matter where along the sequence it is). And once the button is pressed again, then the sequence continues where it left off. I read something about an interrupter and sleep mode using C++ but I am unfamiliar with this so it is not included in my code.
The rest of my goals I have included within my code. I created an object "light" because I was trying to create the sequence without using the delay function as the interrupt does not work well with the delay function (as far as I am aware). Then I am able to call the function toggleLight on the specific light object. However, as I previously stated the sequences are not working.
I am more familiar with OOP languages so perhaps creating an object is not the best for Arduino. If anyone has any ideas for how I can accomplish my goal it would be much appreciated.
unsigned long previousMillis = 0;
unsigned long currentMillis = millis();
//sets up the Infrared receiver for the remote controller
const int RECV_PIN = 1;
IRrecv irrecv(RECV_PIN);
decode_results results;
//Sets up the LED's pin number and light status
class light{
private:
int _pinNumber;
byte _Lstatus;
public:
//function that creates the objects with the parameters
light(int pinNum, byte Lstat){
_pinNumber = pinNum;
_Lstatus = Lstat;}
void toggleLight(long interval){
//ensures that the "interval" amount of time has passed between the last LED blink
if ((currentMillis - previousMillis) >= interval) {
// if the LED is off turn it on and vice-versa:
if (_Lstatus == LOW) {
_Lstatus = HIGH;
} else if (_Lstatus == HIGH) {
_Lstatus = LOW;
}
// set the LED with the ledState of the variable:
digitalWrite(_pinNumber, _Lstatus);
// save the last time you blinked the LED
previousMillis = currentMillis;
}
}
};
//creating four light objects with the pins and initial status of off.
light J1(13, LOW);
light J2(11, LOW);
light P1(12, LOW);
light P2(10, LOW);
void setup()
{
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
}
//Sequence 1 is a mock sequence. It will probably be longer and the intervals would not all be 1000
void seq1(){
currentMillis = millis();
J1.toggleLight(1000);
P1.toggleLight(1000);
J1.toggleLight(1000);
P1.toggleLight(1000);
J2.toggleLight(1000);
P2.toggleLight(1000);
}
void seq2(){
currentMillis = millis(); //I found that placing currentMillis = millis() here allows the lights to at least turn on
J1.toggleLight(2000);
J1.toggleLight(10);
P1.toggleLight(1000);
P1.toggleLight(0);
J2.toggleLight(1500);
J2.toggleLight(1);
P2.toggleLight(2000);
P2.toggleLight(1);
}
void loop()
{
/* So once i get the sequences working, my idea is to have different sequences play
depending on what button on the remote is pressed. However, first I want to get the sequences and
interrupter
For now I have just tried running sequence #2 but it does not work.. Neither does Sequence #1. */
seq2();
//I MADE THESE LINES OF CODE COMMENTS FOR NOW. UNTIL I GET THE REST OF THE PROGRAM WORKING
/*if (irrecv.decode(&results))
{
switch (results.value) {
case : 0xf00000 // When button #1 sequence one plays
seq1();
break;
case : 0xf00000 // when button #2 is pressed, sequence two plays
seq2();
break;
*/
}
I can see that you haven't yet got around to understanding the flow of code inside the Arduino. Here's a quick tutorial to get you up and running.
Basically, your code is not being processed sequentially. So when the processor is moving through seq() and gets to the first if statement in 'J1.toggleLight(2000);' and finds that the condition is not met (i.e. the 2000 milliseconds have not yet passed,) it immediately moves on to the second line in seq(). The issue with this is that when it does meet the condition at the second line it will reset the 'previousMillis' value which all the lights depend on.
Thus you should dedicate a clock for each light by moving in 'previousMillis' into the class as a member.
class light{
private:
int _pinNumber;
byte _Lstatus;
unsigned long previousMillis = 0;
This way each light will be able to keep track of its own time without conflicting with the other lights. This will lead to your lights flickering at a frequency of 1/interval which I doubt is what you want.(it wont even do that with each light getting toggled twice in the seq() functions. Try removing the second calls and see hat happens) This brings me to the second issue.
The second issue is with the way you set up your sequences. Since you want to the lights to operate sequentially you'll need to find the accumulated time which crosses out the chance of using a class, unless you're willing to implement a scheduling mechanism that takes account the interval and arrangement of each instance. Seems a bit impractical imo.
I think you should ditch the class and use a simple function that that accepts the eight values that each sequence requires. Then you could utilize if statements to manipulate the states of the lights.
I hope the answer made some sense.
Good luck.

Arduino Nano - Why are my pins behaving the way they are?

I have a device that measures radiation, using an Elegoo Uno (knockoff Arduino brand) and an RM-60 Radiation Monitor from Aware Electronics. I have had this working for almost a year and a half as part of a high-altitude balloon payload item at my university. I am currently revisiting it, as now I want to understand and cleanup my code.
The setup goes like this:
The RM-60 has four wires. Yellow and black go to ground, red to my 5v, and the green goes to my output (More documentation can be found online).
I have a pin attached to digital 2. I had read online that pins 2 & 3 can use attachInterrputs for the Uno. But for whatever reason, setting my pinMode() to 2 won't work. I have found that when I set my pin to 8, with my actual wire connecting to digital 2, I can read it fine.
This is what I am confused about. I felt that after learning how these inputs work, I am doing it right. But it's not working. So then why, when my pin set to 8, is the device running correctly? If I am doing this wrong (or inefficiently), what tips or pointers can you give me on how to optimize/repair this?
I have my previous code, compiled and tested from almost two years ago. It works as is, but I just don't understand why. I have looked online for similar projects, as several balloon teams around the world have used RM-60s to measure radiation. Following their pin layout and program, I have been unsuccessful.
//this is taking just the necessary lines to run the geigercounter.
//using geigerPin 8, it works. But why not when I change this to 2, where my
//wire actually is?
int count;
int geigerPin = 8;
int testVar = 0;
void setup() {
Serial.begin(9600);
pinMode(geigerPin, OUTPUT);
attachInterrupt(0, test, RISING);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println(count * 6);
count = 0;
delay(10000);
}
void test() {
count++;
}
The data reads back to the Serial monitor every 10 seconds. The returned result should be the counts over ten seconds, multiplied by 6 to give us a counts-per-minute reading.
Please refer to the manual befor using any functions. The manual clearly states that your approach is not going to work.
From the Arduino Reference Manual:
attachInterrupt(digitalPinToInterrupt(pin), ISR, mode) (recommended)
attachInterrupt(interrupt, ISR, mode) (not recommended)
attachInterrupt(pin, ISR, mode) (Not recommended. Additionally, this
syntax only works on Arduino SAMD Boards, Uno WiFi Rev2, Due, and
101.)
Example Code
const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}
void loop() {
digitalWrite(ledPin, state);
}
void blink() {
state = !state;
}

C++ buzzer to play piano notes for an Arduino

unsigned long t;
boolean isHigh;
#define BUZZER_PIN 3
void setup() {
// put your setup code here, to run once:
pinMode(BUZZER_PIN, OUTPUT);
isHigh = false;
t = micros();
}
void loop() {
playNote('c');
}
void playNote(char note) {
unsigned long timeToWait;
unsigned long timeToPlayTheNote = millis();
while (timeToPlayTheNote - millis() < 1000) {
if (note == 'c') {
timeToWait = 1911;
}
if (micros() - t > timeToWait) {
if (!isHigh) {
digitalWrite(BUZZER_PIN, HIGH);
isHigh = true;
} else {
digitalWrite(BUZZER_PIN, LOW);
isHigh = false;
}
t = micros();
}
}
}
I don't know why this won't work. I used to play a frequency every 1,000 microseconds but is there any way to make this simpler as well? Also, with this method I have to do (1/f)/2 and then convert that value from seconds to microseconds and use that as the value for timeToWait.
Initialization of ˋtimeToWait` should obviously be outside of the loop.
An array could be used for timing data.
ˋt` should probably be initialized inside ˋplayNoteˋ
Alternatively, you might use an enum for delay associated to a note.
enum class notes
{
C = 1911
};
Well, all suggestion assume that you don't want to compensate for drifting offsets.
Buzzers have a fixed frequency. They don't work like speakers at all. You will get better results with a real speaker. Don't forget to put a capacitor in series with it so the speaker sees an AC signal, you can fry a speaker quite easily if you feed it a DC signal..
For best results, you should use 2 x 47uF to 100uF electrolytic capacitors back to back, with the negative poles joined together, one positive to the 'duino and the other positive pole connected to the speaker. With higher capacitance, you'll get more bass.
Why don't you use a PWM at 50% (128) and change the PWM frequency to generate the sound? You could use the Timer1 or Timer3 library for that. Letting the hardware do the work would be more presise and would free your application for other tasks, such as reading a keyboard.
https://playground.arduino.cc/Code/Timer1
Setting the PWM at 0% with an analogWrite() would cut the sound.

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.