I'd like to get out of the loop in my Arduino project. Currently I am programming a digital watch, everything works just fine but I wanted to add options menu by clicking a button, but after clicking it nothing pops up even if I have something inside the code. Take a look at it. I don't know how to write it better. If you have some ideas, please you could rewrite some parts of the code and explain why you did so. Thanks forwardly.
Please do not mind s = s + 1, I wanted it like that.
#include "LiquidCrystal.h"
#include <EEPROM.h>
LiquidCrystal lcd(12,11,5,4,3,2);
int h = 0;
int m = 0;
int s = 0;
int right = 8;
int left = 9;
int buttonStateLeft = 0;
String when;
uint8_t EEPROMaddress_sec = 1;
uint8_t EEPROMaddress_min = 2;
uint8_t EEPROMaddress_hour = 3;
bool clockShown = true;
bool menuShown = false;
void setup()
{
lcd.begin(16,2);
pinMode(right, INPUT);
pinMode(left, INPUT);
}
void loop()
{
if(menuShown)
{
lcd.setCursor(0,0);
lcd.print("jozo je kkt");
delay(200);
}
if(clockShown) {
lcd.setCursor(0,0);
buttonStateLeft = digitalRead(left);
if(buttonStateLeft == HIGH)
{
clockShown = false;
menuShown = true;
lcd.clear();
}
s = EEPROM.read(EEPROMaddress_sec);
m = EEPROM.read(EEPROMaddress_min);
h = EEPROM.read(EEPROMaddress_hour);
s = s + 1;
if(h > 12)
when = "PM";
if(h < 12)
when = "AM";
if(h == 12)
when = "PM";
lcd.print("Cas: ");
if(h<10)lcd.print("0");
lcd.print(h);
lcd.print(":");
if(m<10)lcd.print("0");
lcd.print(m);
lcd.print(":");
if(s<10)lcd.print("0");
lcd.print(s);
lcd.print(" ");
lcd.print(when);
if(s == 60)
{
s = 0;
m = m+1;
}
if(m == 60)
{
s = 0;
m = 0;
h = h+1;
}
if(h == 24)
{
m = 0;
s = 0;
h = 0;
}
EEPROM.write(EEPROMaddress_sec, s);
EEPROM.write(EEPROMaddress_min, m);
EEPROM.write(EEPROMaddress_hour, h);
delay(1000);
}
}
In order to do that you will have to use Interrupts, note that you must connect your button to an interrupt pin (not every pin is an interrupt pin) you can google "what are the interrupt pins of 'your_card_name' ", the code would have to change, you can follow these :
In the setup function replace :
pinMode(left, INPUT);
by :
attachInterrupt(digitalPinToInterrupt(left), switchMode, RISING);
add this function before setup(){...}
int lastPressTime=millis();
void switchMode(){ // function called when the button is pressed
if((millis()-lastPressTime)>60){ // for debouncing
clockShown = false;
menuShown = true;
lcd.clear();
lastPressTime=millis();
}
}
and remove this part from your code : (the one in the loop() function)
buttonStateLeft = digitalRead(left);
if(buttonStateLeft == HIGH)
{
clockShown = false;
menuShown = true;
lcd.clear();
}
Related
This may seem like a foolish problem and maybe its description is not the best I could have devised.
I am making a velocity sensor that uses two IR beams to calculate velocity based on the time it takes to break both beams.
I have two testing methods.
My hand (5-10 m/s)
A high speed cannon (30-60 m/s).
I have ruled out that it's a problem with the signal from the IR beams with an oscilloscope, when the code fails/works the data is identical on the scope.
My problem is that my code works when I use my hand, but still irregularly fails, while it fails more often at high speed. All the conditions are the same in both scenarios. What could be the issue?
#include <SPI.h>
#include <SD.h>
#include <LiquidCrystal.h>
const int rs = 9, en = 8, d4 = 7, d5 = 6, d6 = 5, d7 = 4;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
File root;
int fileNo = 0;
String currentFileName;
const int CS = 10;
const byte interruptPinStart = 2;
const byte interruptPinFinish = 3;
volatile unsigned long int startTimeMillis = 0;
volatile unsigned long int stopTimeMillis = 0;
volatile unsigned long int startTimeMicros = 0;
volatile unsigned long int stopTimeMicros = 0;
volatile unsigned long int microsDifference = 0;
volatile unsigned long int millisDifference = 0;
int launchNo = 0;
float currentVelocity = 0;
volatile boolean started = false;
String inputString = "";
boolean stringComplete = false;
const int txLed1 = 14;
const int statusLed1 = 15;
const int statusLed2 = 16;
volatile boolean triggerDone = false;
float velocity = 0;
String temp;
unsigned long int lockout = 0;
boolean lockedOut = false;
boolean fileFail = false;
int testNo = 0;
void setup() {
inputString.reserve(200);
pinMode(statusLed1, OUTPUT);
pinMode(statusLed2, OUTPUT);
pinMode(txLed1, OUTPUT);
Serial.begin(9600);
while (!Serial) {
;
}
lcd.begin(16, 2);
pinMode(interruptPinStart, INPUT);
attachInterrupt(digitalPinToInterrupt(interruptPinStart), startTrigger, RISING);
pinMode(interruptPinFinish, INPUT);
attachInterrupt(digitalPinToInterrupt(interruptPinFinish), stopTrigger, RISING);
Serial.print("Initializing SD card...");
if (!SD.begin(CS)) {
Serial.println("initialization failed!");
return;
}
Serial.println("initialization done.");
root = SD.open("/");
newDirectory(root);
Serial.println("done!");
lcd.clear();
lcd.print(currentFileName);
tone(txLed1, 38000);
}
void loop() {
int millsDiff = millis() - stopTimeMillis;
if (triggerDone) {
lockedOut = true;
Serial.print("Micros Diffrence: ");
Serial.println(microsDifference);
Serial.print("Millis Difference: ");
Serial.println(millisDifference);
float millDiff = (float) millisDifference;
float microDiff = (float) microsDifference;
if (microDiff > 0) {
velocity = (float) 0.09 / (microDiff/1000000);
testNo++;
temp = String(launchNo) + "%" + String(microsDifference) + "%" + String(velocity);
if (velocity > 10.0) {
root = SD.open(currentFileName, FILE_WRITE);
if (root) {
root.println(temp);
root.close();
Serial.println(temp);
launchNo++;
} else {
Serial.println("error opening file, " + currentFileName);
fileFail = true;
}
}
if (fileFail) {
lcd.clear();
lcd.print("File Error");
lcd.setCursor(0, 1);
lcd.print("Vel " + String(launchNo) + ": " + String(velocity) + " m/s");
fileFail = false;
} else {
lcd.clear();
lcd.print("Test Number: " + String(testNo));
lcd.setCursor(0, 1);
lcd.print("Vel " + String(launchNo) + ": " + String(velocity) + " m/s");
}
}
triggerDone = false;
Serial.println("Test Number: " + String(testNo));
}
if (digitalRead(interruptPinStart) == LOW) {
digitalWrite(statusLed1, HIGH);
} else {
digitalWrite(statusLed1, LOW);
}
if (digitalRead(interruptPinFinish) == LOW) {
digitalWrite(statusLed2, HIGH);
} else {
digitalWrite(statusLed2, LOW);
}
}
void startTrigger() {
startTimeMicros = micros();
startTimeMillis = millis();
volatile int diff1 = startTimeMicros - startTimeMillis;
volatile int diff2 = startTimeMillis - stopTimeMillis;
if (diff2 > 200) {
if (started == false || diff1 > 1000) {
started = true;
triggerDone = false;
}
}
}
void stopTrigger() {
stopTimeMicros = micros();
stopTimeMillis = millis();
microsDifference = stopTimeMicros - startTimeMicros;
millisDifference = stopTimeMillis - startTimeMillis;
if ((millisDifference > 0 && millisDifference < 800) && started) {
microsDifference = stopTimeMicros - startTimeMicros;
millisDifference = stopTimeMillis - startTimeMillis;
started = false;
triggerDone = true;
}
}
I'm currently doing a project on an Arduino Uno. The project is based on receiving an IR Signal from an IR Remote and then based on the signal received, perform other operations.
The problem is that the signal gets reset every time. I want to store the value received from the IR Remote and then resets it if detects another pulse.
Here is my code :
int brojac = 0;
int pinData = 10;
unsigned long lengthHeader;
unsigned long bit;
int byteValue;
int vrime = 1000 ;
int storeValue = 0;
void setup()
{
Serial.begin(9600);
pinMode(pinData, INPUT);
}
void loop() {
lengthHeader = pulseIn(pinData, LOW);
if (lengthHeader > 1500)
{
for (int i = 1; i <= 32; i++) {
bit = pulseIn(pinData, HIGH);
if (i > 16 && i <= 24)
if (bit > 1000)
byteValue = byteValue + (1 << (i - 17));
}
}
Serial.print("byteValue = ");
Serial.println(byteValue);
if(byteValue == 66){
digitalWrite(11,HIGH);
}
else{
digitalWrite(11,LOW);
}
delay(vrime);
byteValue = 0;
delay(250);
}
I got the answer by storing the value in a variable until a new variable is detected.
int pinData = 10;
int led = 11;
unsigned long lengthHeader;
unsigned long bit;
int byteValue;
int storeValue = 0;
int previousValue = 0;
void setup()
{
Serial.begin(9600);
pinMode(pinData, INPUT);
pinMode(led, LOW);
}
void loop() {
lengthHeader = pulseIn(pinData, LOW);
if (lengthHeader > 1500)
{
for (int i = 1; i <= 32; i++) {
bit = pulseIn(pinData, HIGH);
if (i > 16 && i <= 24)
if (bit > 1000)
byteValue = byteValue + (1 << (i - 17));
}
}
Serial.print("byteValue = ");
Serial.println(byteValue);
**storeValue = byteValue;
if (storeValue != 0){
previousValue = storeValue;
}
Serial.print("Previous value = ");
Serial.println(previousValue);**
byteValue = 0;
delay(500);
}
I am a beginner with arduino and I'm trying to make a sinus wave generator. Since I've recently found I can't put everything into main void loop, I'm trying to use interrupts. I have problem with changing variable inside of the interrupt (Delay), I don't know where's the mistake.
Here is my code:
int sine256[] = { //256 sin values from 0 to 2pi
};
int i = 0;
int sensorPin = 7;
int outputPin = 6;
volatile float Delay = 10000;
void setup()
{
Serial.begin(9600);
pinMode(outputPin, OUTPUT);
pinMode(sensorPin, INPUT);
attachInterrupt(digitalPinToInterrupt(sensorPin), freq, RISING);
}
void loop()
{
analogWrite(6,sine256[i]);
i = i + 1;
if(i == 256){
i = 0;
}
Serial.println(Delay);
delayMicroseconds(Delay);
}
void freq() {
Delay = Delay/2;
}
EDIT
Try this:
int sine256[] = { //256 sin values from 0 to 2pi
};
int i = 0;
int sensorPin = 7;
int outputPin = 6;
volatile float Delay = 10000;
void setup()
{
Serial.begin(9600);
pinMode(outputPin, OUTPUT);
pinMode(sensorPin, INPUT);
//attachInterrupt(digitalPinToInterrupt(sensorPin), freq, RISING);
}
void loop()
{
analogWrite(6,sine256[i]);
i = i + 1;
if(i == 256){
i = 0;
}
Serial.println(Delay);
freq();
delay(Delay);
}
void freq() {
Delay = Delay / 2;
}
https://www.arduino.cc/en/Reference/AttachInterrupt
Try taking a look at that.
What model are you using?
The only thing that causes me troubles now is the button; when i press it, it often respond as if i had pressed the button multiple times (2,3 or 4x).
This is my final code for now. Since the execution time for a void loop is 12 microseconds, i've calculated delay required to run a generator on 20,40 & 60Hz.
int sine256[] = { //256 sin values from 0 to 2pi (from 0 to 255)
int i = 0;
int sensorPin = 2;
volatile int outputPin = 7;
volatile float Delay = 1000;
int time1;
int time2;
void setup()
{
Serial.begin(9600);
pinMode(outputPin, OUTPUT);
pinMode(sensorPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(sensorPin), freq, FALLING);
}
void loop()
{
//time1 = micros();
analogWrite(outputPin,sine256[i]);
i = i + 1;
if(i == 256){
i = 0;
}
//time2 = micros();
//Serial.println(time2 - time1);
delay(Delay);
}
void freq() {
outputPin = 6;
if(Delay == 0.02){
analogWrite(6,LOW);
outputPin = 7;
Delay = 1000;
}
if(Delay == 0.04){
Delay = 0.02;
}
if(Delay == 0.09){
Delay = 0.04;
}
if((Delay == 1000)&&(outputPin == 6)){
Delay = 0.09;
}
Serial.println(Delay);
}
I have an Arduino mega with an SD Shield and a GSM shield. I'm trying to send one sms to 200 numbers from a text file on the SD card, but the Arduino reboots every time I try to send to over 100 numbers. It doesn't crash when I try to send to 70 numbers. I only read one number at a time so I don't understand the problem. I'm pretty new to Arduino programming.
Please help me this is for a tournament. Here's the code:
#include <avr/pgmspace.h>
#include <SPI.h>
#include <SD.h>
#include <GSM.h>
#define PINNUMBER ""
GSM gsmAccess;
GSM_SMS sms;
// GSM
boolean notConnected;
//char input;
//byte input2;
//char txtContent[200];
byte i = 1;
byte f = 0;
boolean sendit;
//char senderNumber[11];
const String stopp PROGMEM = "Stopp";
//SD
char numbers[11];
//char nmbr;
int l = 0;
//Optimizing
const char q PROGMEM = '\xe5'; // å
const char w PROGMEM = '\xe4'; // ä
const char e PROGMEM = '\xf6'; // ö
const char r PROGMEM = '\xc5'; // Å
const char t PROGMEM = '\xc4'; // Ä
const char y PROGMEM = '\xd6'; // Ö
void setup() {
// txtContent[0] = '\0';
i = 0;
pinMode(53, OUTPUT);
Serial.begin(115200);
// Serial.begin(4800);
Serial.println(F("Connecting to GSM..."));
notConnected = true;
while (notConnected) {
if (gsmAccess.begin(PINNUMBER) == GSM_READY) {
notConnected = false;
}
else {
Serial.println(F("Not Connected"));
delay(1000);
}
}
Serial.println(F("GSM Ready"));
if (!SD.begin(4)) {
Serial.println(F("Error with SD card"));
return;
}
Serial.println(F("SD Ready"));
delay(1000);
Serial.println(F("Write your sms and end it with * and press Send"));
Serial.flush();
}
void loop() {
char txtContent[300];
if (Serial.available() > 0 && !sendit) {
byte input2;
input2 = (int)Serial.read();
txtContent[i] = (char)input2;
if (txtContent[i] == '{') {
txtContent[i] = q;
}
else if (txtContent[i] == '}') {
txtContent[i] = w;
}
else if (txtContent[i] == '|') {
txtContent[i] = e;
}
else if (txtContent[i] == '[') {
txtContent[i] = r;
}
else if (txtContent[i] == ']') {
txtContent[i] = t;
}
else if (txtContent[i] == ';') {
txtContent[i] = y;
}
i++;
if (input2 == '*') {
// Remove the * from text.
for (int j = 0; j < sizeof(txtContent); j++) {
if (txtContent[j] == '*') {
txtContent[j] = '\0';
//Serial.println(txtContent);
}
}
sendit = true;
Serial.flush();
}
else {
sendit = false;
Serial.flush();
}
}
else if (sendit && txtContent[0] != '\0') {
int txtCount = 0;
// else if(sendit){
Serial.println(F("Sending please wait..."));
// Serial.flush();
File myFile;
myFile = SD.open("numbers.txt");
char input;
if (myFile) {
// if (myFile.available()) {
while(myFile.available()){
input = (char)myFile.read();
if (input == ',') {
sms.beginSMS(numbers);
sms.print(txtContent);
// sms.beginSMS("0704941025");
// sms.print("yo");
delay(30);
sms.endSMS();
delay(30);
Serial.println(numbers);
Serial.flush();
// Serial.flush();
for (int j = 0; j < sizeof(numbers); j++) {
if (numbers[i] != '\0') {
numbers[j] = '\0';
}
}
f = 0;
}
else {
numbers[f] = input;
f++;
}
}
myFile.close();
Serial.println(F("All texts have been sent."));
Serial.flush();
} else {
Serial.println(F("error opening numbers.txt"));
}
for (int j = 0; j < sizeof(txtContent); j++) { // Clear text
txtContent[j] = '\0';
}
i = 0;
sendit = false;
}
else {
// delay(1000);
if (sms.available()) {
char senderNumber[11];
sms.remoteNumber(senderNumber, 11);
if (sms.peek() == 'S') {
Serial.print(F("Detta nummer har skickat Stopp: "));
Serial.println(senderNumber);
}
sms.flush();
Serial.flush();
// sendit = false;
}
}
}
Arduino is a strange ground for me but if that is anything like C, then i risk saying sizeof(numbers) will likely return 44, because you're asking for the size of an array in bytes, this probably means your for loop will iterate up to numbers[43] when numbers[] length is 11. Consider this instead:
for (int j = 0; j < sizeof(numbers)/sizeof(numbers[0]); j++) {
Same goes for all the other times you check for the size of an array in this code.
Also, do double check your textfile to ensure its really written in your expected format: 11 numbers then a comma, with no exception. You should maybe try to figure out if f went past 11 digits before hitting a comma and "Fail gracefully" with an error message.
I've built an arduino sketch that attempts to do a couple of different lengths of windowing and some simple calculations (mean/variance) on the analog values from a couple of sensors. Previously I had the same code for 1 sensor working as intended but the code below has been expanded with a bunch of little for loops so that everything should run for both sensors now.
I simply can't get anything at all to print to serial - even the two serial prints i put in setup and start of loop just to debug - yet the code compiles and uploads without any errors or warnings.
I apologise for including the whole sketch, I couldn't think how to break it apart to show.
long int currentTime = 0;
long int stopTime[2] = {0,0};
long int shortWindowTime = 0;
int shortVal[2][40];
int reflexWindowStart = 0;
int reflexWindowTime = 0;
int reflexVal[2][500];
int mean[2] = {0,0};
unsigned int variance[2] = {0,0};
int lowVal[2] = {0,0};
int peakVal[2] = {0,0};
int lowIndex[2] = {0,0};
int peakIndex[2] = {0,0};
int stopIndex[2] = {0,0};
boolean stopped[2] = {false,false};
void setup(){
Serial.begin(9600);
Serial.println("wtf?");
for(int i=0;i<2;i++){
for(int j=0;j<40;j++){
shortVal[i][j] = 0;
}
for(int j=0;j<500;j++){
reflexVal[i][j] = 1023;
}
}
}
void loop() {
Serial.println("wtf?");
currentTime = micros();
if(currentTime - shortWindowTime > 500){
shortWindowTime = currentTime;
writeShortWindow();
meanVariance();
if(reflexWindowStart == 0){
reflexWindow();
}
reflexWindowStart++;
if(reflexWindowStart > 9){
reflexWindowStart = 0;
}
}
}
void writeShortWindow(){
for(int i=0;i<2;i++){
for(int j=39; j>0; j--){
shortVal[i][j] = shortVal[i][j-1];
}
int ground = analogRead(A5);
shortVal[0][0] = analogRead(A1);
analogRead(A5);
shortVal[i][0] = analogRead(A2);
}
}
void meanVariance(){
for(int i=0;i<2;i++){
for(int j=0; j<39; j++){
mean[i] = mean[i] + shortVal[i][j];
}
mean[i] = mean[i] / 40;
for(int j=0; j<39; j++){
variance[i] = variance[i] + sq(mean[i] - shortVal[i][j]) ;
}
variance[i] = variance[i] / 40;
}
}
void reflexWindow(){
for(int i=0;i<2;i++){
if(stopped[i] == true){
if((millis() - stopTime[i] > 20) && (peakVal[i] - shortVal[i][0] > 20) && (variance[i] <= 1)){
stopped[i] = false;
stopIndex[i] = 0;
Serial.println("................................NOTstopped");
}
}
}
for(int i=0;i<2;i++){
if(stopped[i] == false){
lowVal[i] = 1023;
peakVal[i] = 0;
for(int j=stopIndex[i]; j>0; j--){
reflexVal[i][j] = reflexVal[i][j-1];
if(reflexVal[i][j] < lowVal[i]){
lowVal[i] = reflexVal[i][j];
lowIndex[i] = j;
}
}
reflexVal[i][0] = shortVal[i][0];
for(int j=lowIndex[i]; j>=0; j--){
if(reflexVal[i][j] > peakVal[i]){
peakVal[i] = reflexVal[i][j];
}
}
}
}
for(int i=0;i<2;i++){
if(stopped[i] == false){
if(peakVal[i] - lowVal[i] >= 50){
Serial.print(i);
Serial.println("...................................stopped");
stopTime[i] = millis();
stopped[i] = true;
}
}
}
for(int i=0;i<2;i++){
if(stopIndex[i] < 499){
stopIndex[i]++;
}
}
Serial.print(shortVal[0][0]);
Serial.print(" ... ");
Serial.print(lowVal[0]);
Serial.print(" ... ");
Serial.print(peakVal[0]);
Serial.print(" ........ ");
Serial.print(shortVal[1][0]);
Serial.print(" ... ");
Serial.print(lowVal[1]);
Serial.print(" ... ");
Serial.println(peakVal[1]);
}
If you have a Leonardo board you will most likely not see the Serial.print in the setup function.
Try changing your setup to this (notice the extra while loop waiting for the Serial)
void setup(){
Serial.begin(9600);
while (!Serial);
Serial.println("wtf?");
for(int i=0;i<2;i++){
for(int j=0;j<40;j++){
shortVal[i][j] = 0;
}
for(int j=0;j<500;j++){
reflexVal[i][j] = 1023;
}
}
}
The reason behind this you can read in the Arduino docs for Leonardo http://arduino.cc/en/Guide/ArduinoLeonardo#toc3 but in short is that Leonardo doesnt resets the serial port when opening the serial stream.
Have you checked your BAUD rate in serial monitor, because if it is different, it will not show anything.
be sure the one in serial monitor and in Serial.begin(<BAUD rate here>) is the same