Redeclared as different kind of symbol in Arduino - arduino

I'm currently working on a school project. I want the servo to move according to the number of coins selected. I keep getting the error " 'void servoOne()' redeclared as different kind of symbol " I know this has been asked but I'm not sure how to fix this.
Here is my code.
#include <LiquidCrystal.h>
#include <Keypad.h>
#include <Servo.h>
Servo servoOne;
String sharp="";
int piso=0;
int lima=0;
int sampu=0;
String input="";
String remlast = "";
LiquidCrystal lcd(A0, A1, A2, A3, A4, A5);//RS,EN,D4,D5,D6,D7
const byte Rows= 4; //number of rows on the keypad i.e. 4
const byte Cols= 3; //number of columns on the keypad i,e, 3
//we will definne the key map as on the key pad:
char keymap[Rows][Cols]={
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'},
{'*', '0', '#'}
};
byte rPins[Rows]= {3,4,5,6}; //Rows 0 to 3
byte cPins[Cols]= {7,8,9}; //Columns 0 to 2
Keypad kpd= Keypad(makeKeymap(keymap), rPins, cPins, Rows, Cols);
void setup() {
// put your setup code here, to run once:
lcd.begin(20,4);
servoOne.attach(10);
}
void loop() {
char key2 = kpd.getKey();
if (key2 != NO_KEY)
{
lcd.print(key2);
if (sharp == "")
{
input+=key2;
remlast = input;
remlast.replace("*","");
remlast.replace("#","");
piso = remlast.toInt();
}
else if (sharp == "five")
{
input+=key2;
remlast = input;
remlast.replace("*","");
remlast.replace("#","");
lima = remlast.toInt();
}
else if (sharp == "ten")
{
input+=key2;
remlast = input;
remlast.replace("*","");
remlast.replace("#","");
sampu = remlast.toInt();
}
if(key2=='*' && sharp!=NULL)
{
lcd.rightToLeft();
sharp="";
piso=0;
lima=0;
sampu=0;
input="";
remlast="";
}
if (sharp=="ten" && key2=='#')
{
sharp = "out";
lcd.clear();
lcd.print(piso);
lcd.print(lima);
lcd.print(sampu);
servoOne();
}
else if (sharp=="five" && key2=='#')
{
lcd.clear();
lcd.print("10-peso=");
lcd.setCursor(0,1);
lcd.print("(*)Erase (#)Enter");
lcd.setCursor(8,0);
sharp="ten";
input = 0;
}
else if (key2=='#')
{
lcd.clear();
lcd.print("5-peso=");
lcd.setCursor(0,1);
lcd.print("(*)Erase (#)Enter");
lcd.setCursor(7,0);
sharp="five";
input = 0;
}
if (key2=='*')
{
lcd.clear();
lcd.print("1-peso=");
lcd.setCursor(0,1);
lcd.print("(*)Erase (#)Enter");
lcd.setCursor(7,0);
}
}
}
//--------------------SERVO ONE--------------------//
void servoOne()
{
servoOne.write(70);
delay(10);
while(piso>0)
{
int x = piso;
while(x>0)
{
servoOne.write(170);
delay(200);
servoOne.write(40);
delay(200);
x--;
}
}
}

It occurs as it clashes between servoOne in Servo servoOne; and void servoOne(). Please replace servoOne in void servoOne() by some other name.
(don't forget to replace the function name in function call by your new function name)

Related

Arduino hex to string decoder not working

I'm creating a HEX -> STR decoder using an LCD screen (display the HEX as well as the decoded values), a keypad (to input the HEX code), and a button (to press for it to decode the HEX values). The decoder works sometimes but sometimes it glitches out and presents unexpected values.
#include <Keypad.h>
#include<LiquidCrystal.h>
String hex; // store the hex values
String text; // store the decoded text
int calcButton = 0;
const byte ROWS = 4;
const byte COLS = 4;
char hexaKeys[ROWS][COLS] = {
{'1', '2', '3', 'F'},
{'4', '5', '6', 'E'},
{'7', '8', '9', 'D'},
{'A', '0', 'B', 'C'}
};
byte rowPins[ROWS] = {9, 8, 7, 6};
byte colPins[COLS] = {13, 12, 11, 10};
Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);
LiquidCrystal lcd(5, 4, 3, 2, A0, A1);
char nibble2c(char c) {
if ((c>='0') && (c<='9'))
return c-'0' ;
if ((c>='A') && (c<='F'))
return c+10-'A' ;
if ((c>='a') && (c<='a'))
return c+10-'a' ;
return -1 ;
}
char hex2c(char c1, char c2) {
if(nibble2c(c2) >= 0)
return nibble2c(c1)*16+nibble2c(c2) ;
return nibble2c(c1) ;
}
// resets string values and clears screen
void erase() {
hex = "";
Serial.println(hex);
text = "";
lcd.clear();
lcd.setCursor(0,0);
}
// decode the hex values
String calculate(String hex) {
if (hex.length()%2 != 0) {
lcd.setCursor(0,0);
lcd.print("No of characters");
lcd.setCursor(0,1);
lcd.print("needs to be even");
delay(2000);
erase();
}
else {
for (int i = 0; i < hex.length() - 1; i+=2){
for (int j = 1; j < hex.length(); j+=2){
text += hex2c(hex[i], hex[j]);
}
}
}
}
void setup() {
pinMode(A2, INPUT);
lcd.begin(16, 2);
lcd.setCursor(0,0);
Serial.begin(9600);
}
void loop() {
calcButton = digitalRead(A2); // decode button
char customKey = customKeypad.getKey();
// if keypad is pressed, add hex values to str
if (customKey){
lcd.print(customKey);
hex += customKey;
Serial.println(hex);
}
// if button is pressed, decode
if (calcButton == 1) {
lcd.clear();
calculate(hex);
hex = "";
lcd.print(text);
text = "";
delay(1500);
lcd.clear();
}
}
I input 49 and get I (which is correct) but when I input 4949 I expect the output to be II but it outputs IIII and when I input 6F expecting o the entire screen blurs and glitches.
The problem is here:
for (int i = 0; i < hex.length() - 1; i+=2){
for (int j = 1; j < hex.length(); j+=2){
text += hex2c(hex[i], hex[j]);
}
}
Notice that you iterate over the hex string length()*length()/4 times, combining every even hex character from the string with every odd character in the string, not just the one immediately following it. For two-digit hexadecimal strings this works because there only is one odd- and one even-indexed character; for longer strings you get wrong results.
4949 will combine 4 (#0) and 9 (#1), then 4 (#0) and 9 (#3) (wrong!), then 4 (#2) and 9 (#1) (wrong!), then 4 (#2) and 9 (#3), which gives you the result that 49494949 should give instead of 4949.
What you want is just:
for (int i = 0; i < hex.length() - 1; i+=2){
text += hex2c(hex[i], hex[i+1]);
}

Arduino Uno low memory available

i'm trying to do a communication over ethernet using ENC28J60 and Arduino Uno and run 3 task . I have a little problem with my arduino code. My code is compiling but i get the following error : "Low memory available, stability problems may occur." and the led on the board is blinking very fast. I guess that the board is trying to alocate memory but he faild. Any idea what can i do ?
#include <Arduino_FreeRTOS.h>
#include "HX711.h"
#include <PID_v1.h>
#include <string.h>
//#include <SPI.h>
#include <UIPEthernet.h>
#define configUSE_IDLE_HOOK 0
// FreeRTOS tasks
void TaskPrimaryControlLoop(void *pvParameters);
void TaskConcentrationControlLoop(void *pvParameters);
void TaskIdle(void *pvParameters);
/* Weigth Cells */
#define hx_pf_dout 3
#define hx_pf_clk 2
#define hx_c_dout 5
#define hx_c_clk 4
HX711 pf_scale(hx_pf_dout, hx_pf_clk);
HX711 c_scale(hx_c_dout, hx_c_clk);
float pf_factor = -236000;
float c_factor = -203000;
float p_weigth = 0; // (kg, 0.000) primary liquid weigth
float p_l_weigth = 0; // (kg, 0.000) primary liquid last weigth
float c_weigth = 0; // (kg, 0.000) concentrate liquid weigth
float c_l_weight = 0; // (kg, 0.000) concentrate liquid last weigth
/* h bridge config */
#define speed_p 9
#define forward_p 7
#define backward_p 8
#define speed_c 6
#define forward_c A0
#define backward_c A1
double p_pump = 0; // 0-255 pwm pump output
double c_pump = 0; // 0-255 pwm pump output
//// PID parameters
// Primary Control Loop
#define p_kp 250.0
#define p_ki 25.0
// Concentration Control Loop
#define c_kp 250.0
#define c_ki 25.0
double p_pv = 0; // (%) primary flow value
double c_pv = 0; // (%) concentration flow value
double p_sp = 0; // (l/min) primary flow setpoint
double c_sp_proc = 0; // % concentration
double c_sp = 0; // (l/min) concentration setpoint
PID pid_pcl(&p_pv, &p_pump, &p_sp, p_kp,p_ki,0.0, DIRECT);
PID pid_ccl(&c_pv, &c_pump, &c_sp, c_kp,c_ki,0.0, DIRECT);
/* Communication Ethernet */
#define MAX_STRING_LEN 32
const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 2);
IPAddress myDns(192,168,1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
// telnet defaults to port 23
EthernetServer server(23);
//EthernetClient client;
boolean alreadyConnected = false; // whether or not the client was connected previously
void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB, on LEONARDO, MICRO, YUN, and other 32u4 based boards.
}
pinMode(forward_p, OUTPUT);
pinMode(backward_p, OUTPUT);
pinMode(forward_c, OUTPUT);
pinMode(backward_c, OUTPUT);
pinMode(speed_p, OUTPUT);
pinMode(speed_c, OUTPUT);
digitalWrite(backward_p, HIGH);
digitalWrite(backward_c, HIGH);
digitalWrite(forward_p, LOW);
digitalWrite(forward_c, LOW);
pf_scale.set_scale(pf_factor);
c_scale.set_scale(c_factor);
//pf_scale.tare();
//c_scale.tare();
pid_ccl.SetMode(AUTOMATIC);
pid_pcl.SetMode(AUTOMATIC);
xTaskCreate(
TaskPrimaryControlLoop
, (const portCHAR *)"PrimaryControlLoop" // A name just for humans
, 128 // This stack size can be checked & adjusted by reading the Stack Highwater
, NULL
, 2 // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest.
, NULL );
xTaskCreate(
TaskConcentrationControlLoop
, (const portCHAR *)"ConcentrationControlLoop" // A name just for humans
, 128 // This stack size can be checked & adjusted by reading the Stack Highwater
, NULL
, 2 // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest.
, NULL );
xTaskCreate(
TaskIdle
, (const portCHAR *)"Idle" // A name just for humans
, 512 // This stack size can be checked & adjusted by reading the Stack Highwater
, NULL
, 0 // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest.
, NULL );
}
void loop() {
}
void TaskPrimaryControlLoop(void *pvParameters)
{
//(void) pvParameters;
for (;;)
{
p_weigth = pf_scale.get_units(1);
p_pv = (p_l_weigth - p_weigth)*100;
if(p_pv < 0) p_pv = 0;
pid_pcl.Compute();
analogWrite(speed_p, p_pump);
p_l_weigth = p_weigth;
vTaskDelay(200 / portTICK_PERIOD_MS); // 200 ms sample time
}
}
void TaskConcentrationControlLoop(void *pvParameters)
{
//(void) pvParameters;
for (;;)
{
c_weigth = c_scale.get_units(1);
c_pv = (c_l_weight - c_weigth)*100;
if(c_pv < 0) c_pv = 0;
c_sp = p_sp * (c_sp_proc/100);
pid_ccl.Compute();
analogWrite(speed_c, c_pump);
c_l_weight = c_weigth;
vTaskDelay(200 / portTICK_PERIOD_MS); // 200 ms sample time
}
}
void TaskIdle(void *pvParameters)
{
//(void) pvParameters;
for(;;){
EthernetClient client = server.available();
// when the client sends the first byte, say hello:
if (client) {
if (!alreadyConnected) {
client.flush();
//Serial.println("We have a new client");
//client.println("Hello, client!");
alreadyConnected = true;
}
}
recvWithStartEndMarkers();
//showNewData();
if(receivedChars[0] == 's'){
p_sp = atof(subStr(receivedChars, ",", 2));
c_sp_proc = int(subStr(receivedChars, ",", 3));
newData = false;
memset(receivedChars, 0, sizeof(receivedChars));
}
// send process values to application
if(receivedChars[0] == 'w'){
Serial.print(p_pv);
Serial.print(",");
Serial.print(p_sp);
Serial.print(",");
Serial.print(int(c_pump));
Serial.print(",");
Serial.print(c_pv);
Serial.print(",");
Serial.print(c_sp);
Serial.print(",");
Serial.print(int(p_pump));
Serial.println();
newData = false;
memset(receivedChars, 0, sizeof(receivedChars));
}
/*
// check commands
while(Serial.available() > 7){
p_sp = Serial.parseFloat();
c_sp_proc = Serial.parseInt();
}
newData = false;
memset(receivedChars, 0, sizeof(receivedChars)
*/
newData = false;
memset(receivedChars, 0, sizeof(receivedChars));
vTaskDelay(1);
}
}
void recvWithStartEndMarkers() {
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
EthernetClient client = server.available();
while (client.available() > 0 && newData == false) {
rc = client.read();
if (recvInProgress == true) {
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
recvInProgress = false;
ndx = 0;
newData = true;
}
}
else if (rc == startMarker) {
recvInProgress = true;
}
}
}
float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
// Function to return a substring defined by a delimiter at an index
char* subStr (char* str, char *delim, int index) {
char *act, *sub, *ptr;
static char copy[MAX_STRING_LEN];
int i;
// Since strtok consumes the first arg, make a copy
strcpy(copy, str);
for (i = 1, act = copy; i <= index; i++, act = NULL) {
//Serial.print(".");
sub = strtok_r(act, delim, &ptr);
if (sub == NULL) break;
}
return sub;
}
First thing to do is try to increase the stack depth of your Tasks.
You're currently using 128, 128 and 512.
You can use "StackHighWaterMark" to get the info about the amount of stack space remaining. Try to use this information to "calibrate" the depth of your task. I recommend using at least 40% of free space.
In order to save space in the Arduino memory you can put all the Serial.print in the flash memory, try to use this syntax:
Serial.print(F(","));
Basically you have to add an F in front of the string that you want to print, but you can't do that when you print a variable:
Serial.print(int(c_pump)); // you can't do that here

Rfid with Adafruit fingerprint together not working in Arduino Uno

I am trying to create an ATM module using Arduino. Im using a RFID reader to scan the card and Adafruit Fingerprint Module for fingerprint verification. The issue is both work but not together. Here is my code:
#include <Key.h>
#include <Keypad.h>
#include <Adafruit_Fingerprint.h>
#include <SD.h>
#include <SPI.h>
#include<SoftwareSerial.h>
SoftwareSerial mySerial(0, 1);
SoftwareSerial mySerials(2, 3);
int read_count = 0, tag_count = 0;
int j = 0, k = 0; // Variabvles to iterate in for loops
char data_temp, RFID_data[12], data_store[12];
boolean disp_control;
char filename[4], fileText[30], names[10];
int atm[5];
uint8_t n, num, p;
char key;
int p1, p2, p3, p4, z;
char fid;
File myFile;
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerials);
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad
Keypad keypads = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup() {
finger.begin(57600);
mySerial.begin(9600);
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.print("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println("initialization failed!");
while (1);
}
Serial.println("initialization done.");
Serial.println("Please Place Your Card");
}
void RecieveData()
{
if (mySerial.available() > 0)
{
data_temp = mySerial.read();
RFID_data[read_count] = data_temp;
read_count++;
}
}
void ReadData()
{
if (read_count == 12) {
disp_control = true;
for (j = 0; j < 12; j++) {
data_store[j] = RFID_data[j];
}
int x = 0;
for (int i = 9; i < 12; i++) {
filename[x] = data_store[i];
x++;
}
filename[3] = '.';
filename[4] = 't';
filename[5] = 'x';
filename[6] = 't';
filename[7] = '\0';
myFile = SD.open(filename, FILE_READ);
if (myFile) {
// read from the file until there's nothing else in it:
while (myFile.available()) {
for (int i = 0; i < 20; i++) {
fileText[i] = myFile.read();
}
int a, n = 0;
for (int i = 0; i < 4; i++) {
atm[a] = fileText[i];
a++;
}
for (int i = 5; fileText[i] != '\0'; i++) {
names[n] = fileText[i];
n++;
}
fid = fileText[4];
validate();
myFile.close();
}
} else {
// if the file didn't open, print an error:
Serial.println("error opening test.txt");
}
read_count = 0;
tag_count++;
}
}
void validate() {
Serial.print("Hello ");
Serial.print(names);
Serial.println();
Serial.println();
Serial.println();
pin();
}
void pin() {
Serial.println("Please Enter Your ATM PIN");
p1 = keypads.getKey();
while (p1 == NO_KEY) {
p1 = keypads.getKey(); //UPDATE VALUE
}
Serial.print(p1 - 48);
p2 = keypads.getKey();
while (p2 == NO_KEY) {
p2 = keypads.getKey(); //UPDATE VALUE
}
Serial.print(p2 - 48);
p3 = keypads.getKey(); //UPDATE VALUE
while (p3 == NO_KEY) {
p3 = keypads.getKey(); //UPDATE VALUE
}
Serial.print(p3 - 48);
p4 = keypads.getKey(); //UPDATE VALUE
while (p4 == NO_KEY) {
p4 = keypads.getKey(); //UPDATE VALUE
}
Serial.print(p4 - 48);
Serial.println();
if ((p1 == fileText[0]) && (p2 == fileText[1]) && (p3 == fileText[2]) && (p4 == fileText[3])) {
Serial.println("Please verify Fingerprint");
}
else {
Serial.println("Invalid. Buzzer!!!!");
}
}
uint8_t getFingerprintID() {
uint8_t p = finger.getImage();
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image taken");
break;
case FINGERPRINT_NOFINGER:
Serial.println("No finger detected");
return p;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FINGERPRINT_IMAGEFAIL:
Serial.println("Imaging error");
return p;
default:
Serial.println("Unknown error");
return p;
}
// OK success!
p = finger.image2Tz();
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image converted");
break;
case FINGERPRINT_IMAGEMESS:
Serial.println("Image too messy");
return p;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FINGERPRINT_FEATUREFAIL:
Serial.println("Could not find fingerprint features");
return p;
case FINGERPRINT_INVALIDIMAGE:
Serial.println("Could not find fingerprint features");
return p;
default:
Serial.println("Unknown error");
return p;
}
// OK converted!
p = finger.fingerFastSearch();
if (p == FINGERPRINT_OK) {
Serial.println("Found a print match!");
} else if (p == FINGERPRINT_PACKETRECIEVEERR) {
Serial.println("Communication error");
return p;
} else if (p == FINGERPRINT_NOTFOUND) {
Serial.println("Did not find a match");
return p;
} else {
Serial.println("Unknown error");
return p;
}
// found a match!
Serial.print("Found ID #"); Serial.print(finger.fingerID);
Serial.print(" with confidence of "); Serial.println(finger.confidence);
return finger.fingerID;
}
int getFingerprintIDez() {
uint8_t p = finger.getImage();
if (p != FINGERPRINT_OK) return -1;
p = finger.image2Tz();
if (p != FINGERPRINT_OK) return -1;
p = finger.fingerFastSearch();
if (p != FINGERPRINT_OK) return -1;
Serial.print("Found ID #"); Serial.print(finger.fingerID);
Serial.print(" with confidence of "); Serial.println(finger.confidence);
return finger.fingerID;
// found a match!
/*z = finger.fingerID;
if ((fid - 48) == z) {
Serial.println("Success");
}
else {
Serial.println("Fail");
}*/
}
void loop() {
RecieveData();
ReadData();
getFingerprintIDez();
delay(50);
}
If I initialize in this format, then fingerprint works:
mySerial.begin(9600);
finger.begin(57600);
Serial.begin(9600);
And if i do it this way, then RFID works:
finger.begin(57600);
mySerial.begin(9600);
Serial.begin(9600);
I want both of them to work i.e; I first Scan the Card, then verify pin and then it checks the validity of the fingerprint. But the issue is only one of them works at a time. If RFID works, then fingerprint doesn't even blink and if Fingerprint works, RFID doesn't read.
I'm new to this and I don't know where I am going wrong.

Arduino Calculator (Multiple Button Pressing)

We're currently making a 4x3 calculator using Arduino and LCD. We're lacking buttons so instead of one button per operation, there's only one button for all operations. So far, it only does addition. How do you do the thing wherein if I pressed the OPERATION button once, it does addition, if twice, subtraction, etc.
#include <Keypad.h>
#include <LiquidCrystal.h> //import lcd library
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //lcd pins
//LiquidCrystal lcd(5,4,3,2,1,0);
const byte ROWS = 4; // four rows
const byte COLS = 3;
//define the keymap
char keys [ROWS] [COLS] = {
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'},
{'+', '0', '='}
};
byte rowPins[ROWS] = {
9 ,8 ,7 ,6}; //connect keypad ROW1, ROW2, ROW3, ROW4 to these arduino pins
byte colPins[COLS] = {
13, 10, 1};
//create the keypad
Keypad myKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
//variables declaration
boolean valOnePresent = false;
boolean next = false;
boolean final = false;
String num1, num2;
int ans;
char op;
void setup(){
lcd.begin(16,2);
lcd.setCursor(2,0);
lcd.print("Calculator");
delay(2500);
lcd.clear(); //clears the LCD screen and positions the cursor in the upper-left corner.
}
void loop(){
char key = myKeypad.getKey();
if (key != NO_KEY && (key=='1'||key=='2'||key=='3'||key=='4'||key=='5'||key=='6'||key=='7'||key=='8'||key=='9'||key=='0')){
if (valOnePresent != true){
num1 = num1 + key;
int numLength = num1.length();
lcd.setCursor(15 - numLength, 0); //to adjust one whitespace for operator
lcd.print(num1);
}
else {
num2 = num2 + key;
int numLength = num2.length();
lcd.setCursor(15 - numLength, 1);
lcd.print(num2);
final = true;
}
}
else if (valOnePresent == false && key != NO_KEY && (key == '/' || key == '*' || key == '-' || key == '+')){
if (valOnePresent == false){
valOnePresent = true;
op = key;
lcd.setCursor(15,0);
lcd.print(op);
}
}
else if (final == true && key != NO_KEY && key == '='){
if (op == '+')
{
ans = num1.toInt() + num2.toInt();
}
else if (op == '='){
ans = num1.toInt() + num2.toInt();
}
/* else if (op == '+')
{
answ = num1.toInt() - num2.toInt();
}
*/
lcd.clear();
lcd.setCursor(15,0);
lcd.autoscroll();
lcd.print(ans);
lcd.noAutoscroll();
}
}
You could use an array in order to accomplish this. By implementing a while loop with a small delay you can keep iterating through the positions in the array every time the button is pushed until the array times out. Here's an example of some could you could use to implement it.
char ops [4] = {'+','-','/','*'};
int del = 2500;
int strt = millis();
int location = 0;
while (millis() - strt < del) {
key = myKeypad.getkey();
if (key == '+') {
if (loc == 3) {
location = 0;
}
else {
location += 1;
}
strt = millis();
}
}
op = ops(location);

Arduino mega crashes while reading somewhat large .txt from SD

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.

Resources