Hy community, I'm writing a program with arduino. I have write a function that convert string in byte but it it occupies so much memory. My question is if there is a function that I can use and it does not occupy so much memory on my arduino.
I post the code below.
byte strConv(String str)
{
byte a = 0;
char n = 2;
char g = 3;
char stringa1;
char stringa2;
char m;
stringa1 = str.charAt(n);
stringa2 = str.charAt(g);
m = costanti (stringa1);
if (m >= '0' && m <= '9' || m >= 'A' && m <= 'F') {
a += m;
} else {
a += m;
}
a = a << 4;
m = 0;
m = costanti (stringa2);
if (m >= '0' && m <= '9' || m >= 'A' && m <= 'F') {
a += m;
} else {
a += m;
}
return a;
}
and the second function:
char costanti(char n) {
char num;
switch (n) {
case '0':
num = 0;
break;
case '1':
num = 1;
break;
case '2':
num = 2;
break;
case '3':
num = 3;
break;
case '4':
num = 4;
break;
case '5':
num = 5;
break;
case '6':
num = 6;
break;
case '7':
num = 7;
break;
case '8':
num = 8;
break;
case '9':
num = 9;
break;
case 'A':
num = 10;
break;
case 'B':
num = 11;
break;
case 'C':
num = 12;
break;
case 'D':
num = 13;
break;
case 'E':
num = 14;
break;
case 'F':
num = 15;
break;
}
return num;
}
Can I reduce this two functions in a new optimized function?
As far as I understand you want something like this:
char strConv(String str)
{
if(str.length() > 2)
return -1; // return something which makes sense to you for "invalid"
return static_cast<char>(strtol(str.c_str(), NULL, 16));
}
String myString(26, HEX); // creates the string "1A" for you
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("String: \""+myString+'"');
char val = strConv(myString); //gives you the 26 again
Serial.print("int: ");
Serial.println(static_cast<int>(val));
delay(1000);
}
This prompts me the following:
String: "1a"
int: 26
String: "1a"
int: 26
...
Related
why is it like this How should I fix it?
It's my first time using PMS5003 with 7segment
I am able to display the value in the Serial Monitor but cannot get the pm2_5 value to be displayed in the 7 segment.
#include "SevSeg.h"
#include <SoftwareSerial.h>
SoftwareSerial mySerial(A0, A1);
SevSeg sevseg;
unsigned int pm1 = 0;
unsigned int pm2_5 = 0;
unsigned int pm10 = 0;
void setup() {
Serial.begin(9600);
while (!Serial) ;
mySerial.begin(9600);
byte numDigits = 4;
byte digitPins[] = {10, 11, 12, 13};
byte segmentPins[] = {2, 3, 4, 5, 6, 7, 8, 9}; //6, 7, 8, 9, 10, 11, 12, 13
bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
byte hardwareConfig = COMMON_CATHODE; // See README.md for options
bool updateWithDelays = false; // Default 'false' is Recommended
bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
bool disableDecPoint = false; // Use 'true' if your decimal point doesn't exist or isn't connected
sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments,
updateWithDelays, leadingZeros, disableDecPoint);
sevseg.setBrightness(30);
}
void loop() {
int index = 0;
char value;
char previousValue ;
static unsigned long timer = millis ();
static int deciSeconds = 0;
if (millis() - timer >= 100)
{
timer += 100;
sevseg.setNumber(pm2_5, 2);
}
sevseg.refreshDisplay();
while (mySerial.available()) {
value = mySerial.read();
if ((index == 0 && value != 0x42) || (index == 1 && value != 0x4d)) { //0x42,0x4d ค่าคงที่
Serial.println("Cannot find the data header.");
break;
}
if (index == 4 || index == 6 || index == 8 || index == 10 || index == 12 || index == 14) {
previousValue = value;
}
else if (index == 5) {
pm1 = 256 * previousValue + value;
Serial.print("{ ");
Serial.print("\"pm1\": ");
Serial.print(pm1);
Serial.print(" ug/m3");
Serial.print(", ");
}
else if (index == 7) {
pm2_5 = 256 * previousValue + value;
Serial.print("\"pm2_5\": ");
Serial.print(pm2_5);
Serial.print(" ug/m3");
Serial.print(", ");
}
else if (index == 9) {
pm10 = 256 * previousValue + value;
Serial.print("\"pm10\": ");
Serial.print(pm10);
Serial.print(" ug/m3");
} else if (index > 15) {
break;
}
index++;
}
while (mySerial.available()) mySerial.read();
Serial.println(" }");
delay(1000);
}
I want the 7segment to be able to display the value of the sensor PMS5003.
I'm trying to create a bop it game with 2 players where:
Green LED – Gyro Sensor (Z-axis)
Red LED – Temperature sensor
Blue LED – Sound sensor
Yellow LED – Light Sensor
However when I press the left button to start the game, only the yellow light above GND goes on and doesn't respond to anything, what can be wrong with my code?
long randNumber;
int temp;
int val;
int number;
int score;
boolean state;
int light;
uint8_t pixeln = 0;
int sound;
int shake;
unsigned long lastmillis = 0;
boolean game;
const byte numPins = 7;
byte pins[] = {0, 1, 2, 3, 4, 5, 6, 7};
int player1 = 0;
int player2 = 0;
#include "Adafruit_CircuitPlayground.h"
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
CircuitPlayground.begin();
CircuitPlayground.clearPixels();
//timer();
}
void loop() {
if (digitalRead(4) == HIGH && digitalRead(19) == LOW){
Serial.println("Button Pressed");
lastmillis = millis();
for (int i=0; i < 10; i ){
randNumber = random(4);
//Serial.println("Loop");
switch (randNumber){
//Serial.println("Switch");
case 0:
while (pixeln < 10){
CircuitPlayground.setPixelColor(pixeln , 255,0,0);
CircuitPlayground.strip.show();
}
pixeln = 0;
state = true;
temp = analogRead(A0);
//Serial.println(temp);
while (state == true) {
val = analogRead(A0);
number = val - temp;
if (number > 10){
score ;
state = false;
//Serial.println("Temperature");
delay(500);
}
}
break;
case 1:
while (pixeln < 10){
CircuitPlayground.setPixelColor(pixeln , 127,127,0);
CircuitPlayground.strip.show();
}
pixeln = 0;
state = true;
light = analogRead(A5);
//Serial.println(light);
while (state == true) {
val = analogRead(A5);
number = light - val;
if (number > 20){
score ;
state = false;
//Serial.println(number);
delay(500);
}
}
break;
case 2:
while (pixeln < 10){
CircuitPlayground.setPixelColor(pixeln , 0,0,255);
CircuitPlayground.strip.show();
}
pixeln = 0;
state = true;
sound = analogRead(A4);
//Serial.println(sound);
while (state == true) {
val = analogRead(A4);
number = val - sound;
if (number > 50){
score ;
state = false;
//Serial.println(number);
delay(500);
}
}
break;
case 3:
while (pixeln < 10){
CircuitPlayground.setPixelColor(pixeln , 0,255,0);
CircuitPlayground.strip.show();
}
pixeln = 0;
val = CircuitPlayground.motionZ();
//Serial.println(val);
state = true;
while (state == true) {
shake = CircuitPlayground.motionZ();
number = val - shake;
//Serial.println(number);
if (number > 15 or number < -15){
score ;
state = false;
//Serial.println("shake");
delay(500);
}
}
break;
case 4:
CircuitPlayground.clearPixels();
CircuitPlayground.setPixelColor(0, 0,255,0);
CircuitPlayground.setPixelColor(1, 0,255,0);
CircuitPlayground.strip.show();
delay(3000);
break;
case 5:
CircuitPlayground.clearPixels();
CircuitPlayground.setPixelColor(3, 255,0,0);
CircuitPlayground.setPixelColor(4, 255,0,0);
CircuitPlayground.strip.show();
delay(3000);
break;
case 6:
CircuitPlayground.clearPixels();
CircuitPlayground.setPixelColor(5, 127,0,255);
CircuitPlayground.setPixelColor(6, 127,0,255);
CircuitPlayground.strip.show();
delay(3000);
break;
case 7:
CircuitPlayground.clearPixels();
CircuitPlayground.setPixelColor(8, 255,128,0);
CircuitPlayground.setPixelColor(9, 255,128,0);
CircuitPlayground.strip.show();
delay(3000);
}
}
if (CircuitPlayground.slideSwitch()) {
player1 = (millis() - lastmillis) / 1000;
Serial.println(player1);
CircuitPlayground.clearPixels();
byte num = player1;
for (byte i=0; i < numPins; i ){
byte state = bitRead(num, i);
if (state == 1){
CircuitPlayground.setPixelColor(pins[i], 255,255,255);
CircuitPlayground.strip.show();
}
}
} else {
player2 = (millis() - lastmillis) /1000;
Serial.println(player2);
CircuitPlayground.clearPixels();
byte num = player2;
for (byte i=0; i < numPins; i ){
byte state = bitRead(num, i);
if (state == 1){
CircuitPlayground.setPixelColor(pins[i], 255,255,255);
CircuitPlayground.strip.show();
}
}}
CircuitPlayground.playTone(330, 500);
}
while (digitalRead(19) == HIGH && digitalRead(4) == LOW){
if (player1 < player2){
CircuitPlayground.clearPixels();
delay(250);
for (int i =0; i < 5; i ){
CircuitPlayground.setPixelColor(i, 255,255,255);
CircuitPlayground.strip.show();
}
delay(250);
CircuitPlayground.clearPixels();
}
else if (player1 > player2){
CircuitPlayground.clearPixels();
delay(250);
for (int i =5; i < 10; i ){
CircuitPlayground.setPixelColor(i, 255,255,255);
CircuitPlayground.strip.show();
}
delay(250);
CircuitPlayground.clearPixels();
}
else {
CircuitPlayground.clearPixels();
delay(250);
for (int i =0; i < 10; i ){
CircuitPlayground.setPixelColor(i, 255,255,255);
CircuitPlayground.strip.show();
}
delay(250);
CircuitPlayground.clearPixels();
}
}
if (digitalRead(19) == HIGH && digitalRead(4) == HIGH){
player1 = 0;
player2 = 0;
for (int a =0; a < 10; a ){
CircuitPlayground.clearPixels();
delay(100);
for (int i =0; i < 10; i ){
CircuitPlayground.setPixelColor(i, CircuitPlayground.colorWheel(25 * i));
CircuitPlayground.strip.show();
}
delay(100);
CircuitPlayground.clearPixels();
}
}
}
visual after pressing left button:
I want two Led's ( Led 1 and Led 3 ) in a 5*5 Led - Matrix to light up and when the corresponding buttons in the 5*5 push-button are pressed the Led's turns off and another two Led's ( Led 3 and Led 5 ) should light up
and when the corresponding buttons are pressed the Led's turns off and another two led's ( Led 5 and Led 11 ) should light up and the process continues for next set of Led's ( Led 11 and Led 13 ) and the next set is ( Led 13 and Led 15 ) and the next set is ( Led 15 and Led 17 ) and ( Led 17 and Led 21 ) and (Led 21 and Led 23 ) and ( Led 23 and Led 25 ).
The code I have written is :
/* If both "first_key_pressed" and "second_key_pressed", we will make the next two LEDs glow and set these two values to zero again
Initially, LEDs 1 and 3 are glowing, so it is declared that the Led 1 is currently first_in_position and Led 3 is currently second_in_position.
Once 1 and 3 are pressed, we will change this two values to first_in_position = '3' and second_in_position = '5'
The method set_next_expected_leds does this job.
*/
#include <Keypad.h>
const byte rows = 5;
const byte cols = 5;
char keys[rows][cols] = {
{'1','2','3','4','5'},
{'6','7','8','9','A'},
{'B','C','D','E','F'},
{'G','H','I','J','K'},
{'L','M','N','O','P'}
};
byte rowPins[rows] = {40, 39 , 38 , 37 , 36 };
byte colPins[cols] = { 35 , 34 ,33 , 32 , 31 };
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, rows, cols );
int Led_Rows[] = { 2 , 3 , 4 ,5 ,6 } ;
int Led_Columns[] = { 7 , 8 , 9 , 10 , 11 };
int Loop_Count = 5 ;
int first_key_pressed = 0;
int second_key_pressed = 0;
char first_in_position = '1';
char second_in_position = '3';
int Wait_Time = 1000 ;
int i = 0 ;
int j = 0 ;
int x = 0 ;
int y = 0 ;
int c = 0 ;
void setup() {
Serial.begin(9600);
for(int i=0;i<5;i++){
pinMode(Led_Rows[i], OUTPUT);
digitalWrite(Led_Rows[i],LOW);
pinMode(Led_Columns[i], OUTPUT);
digitalWrite(Led_Columns[i],HIGH);
}
Led_Glow(0,0);
Led_Glow(0,2);
}
void All_On(){
for( i = 0 ; i < Loop_Count ; i++ ){
digitalWrite(Led_Rows[i],HIGH);
while( j < Loop_Count ){
digitalWrite(Led_Columns[j],LOW);
j++ ;
}
}
j = 0 ;
}
void All_Off(){
for( i = 0 ; i < Loop_Count ; i++ ){
digitalWrite(Led_Rows[i],LOW);
digitalWrite(Led_Columns[i],HIGH);
}
}
void Led_Glow( int a , int b ){
digitalWrite(Led_Rows[a],HIGH);
digitalWrite(Led_Columns[b],LOW);
}
void Led_Dim( int a ,int b ){
digitalWrite(Led_Rows[a],LOW);
digitalWrite(Led_Columns[b],HIGH);
}
void check_for_position(int c) {
if (first_in_position == c) {
first_key_pressed = 1;
} else if (second_in_position == c) {
second_key_pressed = 1;
}
}
void set_next_expected_leds() {
if (first_in_position == '1') {
first_in_position = '3';
second_in_position = '5';
Led_Glow(0,2);
Led_Glow(0,4);
} else if (first_in_position == '3') {
first_in_position = '5';
second_in_position = 'B';
Led_Glow(0,4);
Led_Glow(2,0);
} else if (first_in_position == '5') {
first_in_position = 'B';
second_in_position = 'D';
Led_Glow(2,0);
Led_Glow(2,2);
} else if (first_in_position == 'B') {
first_in_position = 'D';
second_in_position = 'F';
Led_Glow(2,2);
Led_Glow(2,4);
} else if (first_in_position == 'D') {
first_in_position = 'F';
second_in_position = 'L';
Led_Glow(2,4);
Led_Glow(4,0);
} else if (first_in_position == 'F') {
first_in_position = 'L';
second_in_position = 'N';
Led_Glow(4,0);
Led_Glow(4,2);
} else if (first_in_position == 'L') {
first_in_position = 'N';
second_in_position = 'P';
Led_Glow(4,2);
Led_Glow(4,4);
} else if (first_in_position == 'N') {
} else if (first_in_position == 'P') {
}
first_key_pressed = 0;
second_key_pressed = 0;
}
void loop() {
char key = keypad.getKey();
switch (key) {
case '1':
check_for_position('1');
Led_Dim(0, 0);
break;
case '3':
check_for_position('3');
Led_Dim(0, 2);
break;
case '5':
check_for_position('5');
Led_Dim(0, 4);
break;
case 'B':
check_for_position('B');
Led_Dim(2, 0);
break;
case 'D':
check_for_position('D');
Led_Dim(2, 2);
break;
case 'F':
check_for_position('F');
Led_Dim(2, 4);
break;
case 'L':
check_for_position('L');
Led_Dim(4, 0);
break;
case 'N':
check_for_position('N');
Led_Dim(4, 2);
break;
case 'P':
check_for_position('P');
Led_Dim(4, 4);
}
if(first_key_pressed == 1 && second_key_pressed == 1) {
set_next_expected_leds();
}
}
Expected Result: The user can press button 1 or button 3 in the first step if he presses button 1 the led-1 should go off and after pressing button 3 the led-3 should go off and another set of LEDs (Led-3 and Led-5) should glow.
NOTE: The user has the right to press button-3 first and then button-1 then also first led-3 should go off and then led-1 should go off and then the next set of LEDs can glow.
Actual Result: If I press button 1 both led-1 and led-3 goes off and also when I press Button-3 some random led's start blinking.
I want to interface Arduino with PLC to pull some information.
My problem is at Function 3: Set alarm flag / reset flag. This function is used to compare history value and present value. I tried to process some integer number (test_number) and process like binary 16 bits data for finding 1 at some bit. I found the for loop in Findbit function, which should repeat 16 times, runs infinitely. It does not change the incremental index (variable name bit_1) which is still stuck at 1.
This is my code :
int test_number_array[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int test_number = 0;
int bit_1 = 0;
int Andbit = 0;
const char* message;
int flagAlarm[2][16] = {};
int flagReset[2][16] = {};
void setup()
{
// put your setup code here, to run once:
Serial.begin( 9600 );
}
void loop()
{
// put your main code here, to run repeatedly:
for (int j = 1; j <= 2; j++)
{
for (int i = 1; i <= 2; i++) // Example with 2 modbus address
{
unsigned int address = 40000 + i;
Serial.print ("Modbus address = ");
Serial.println(address, DEC);
pull_data(i);
Serial.print("Test number is ");
Serial.println(test_number);
Findbit(i);
Serial.println("------------------------------------------------- ");
}
}
while (1)
{
}
}
// ---------------Function 1 : Function finding alarm bit-----------------//
void Findbit(int i)
{
for (bit_1 = 0; bit_1 <= 15; bit_1++)
{
Andbit = test_number & 1;
Serial.print("Test number (BINARY) is ");
Serial.println(test_number, BIN);
Serial.print("Check at bit number ");
Serial.println(bit_1);
Serial.print("And bit is ");
Serial.println(Andbit, BIN);
Serial.print("flagAlarm(Before1) = ");
Serial.println(flagAlarm[i][bit_1]);
Serial.print("flagreset(Before1) = ");
Serial.println(flagReset[i][bit_1]);
if (Andbit == 1) //found "1" pass into loop
{
flagAlarm[i][bit_1] = 1;
}
else
{
}
Serial.print("flagAlarm(Before2) = ");
Serial.println(flagAlarm[i][bit_1]);
Serial.print("flagreset(Before2) = ");
Serial.println(flagReset[i][bit_1]);
Set_reset_flag(i,bit_1);
test_number = test_number >> 1;
Serial.print("flagAlarm(After) = ");
Serial.println(flagAlarm[i][bit_1]);
Serial.print("flagreset(After) = ");
Serial.println(flagReset[i][bit_1]);
Serial.println(" ");
}
}
// -----------------------Function 2 : Pull data------------------------- //
int pull_data(int i)
{
i = i - 1;
test_number = test_number_array[i];
return test_number;
}
// -------------Function 3 : Set alarm flag / reset flag ---------------- //
void Set_reset_flag(int i, int bit_1)
{
Serial.print("i = ");
Serial.println(i);
Serial.print("bit_1 = ");
Serial.println(bit_1);
if (flagAlarm[i][bit_1] == 1 && flagReset[i][bit_1] == 0)
{
Serial.print("Alarm at bit ");
Serial.println(bit_1);
flagAlarm[i][bit_1] = 0;
flagReset[i][bit_1] = 1;
}
else if (flagAlarm[i][bit_1] == 0 && flagReset[i][bit_1] == 1)
{
Serial.print("Reset Alarm at bit ");
Serial.println(bit_1);
flagReset[i][bit_1] = 0;
}
else if (flagAlarm[i][bit_1] == 1 && flagReset[i][bit_1] == 1)
{
Serial.print("Alarm still active at bit ");
Serial.println(bit_1);
flagAlarm[i][bit_1] = 0;
flagReset[i][bit_1] = 1;
}
else
{
}
}
Could it be that your bit_1 variable is modified from some other code not mentioned here, or get optimized at all? Also, is it necessary to make a loop counter a global variable? Can you declare it inside the Findbit function?
i am using arduino due. what i am trying to do is to receive a string at serial. like this one:
COMSTEP 789 665 432 END
if the string starts with comstep, then to tokenize the string and get an integer array {789, 665, 432}.
is there anyway to do that?
P.S: im a noob at programming, so any help is appreciated.
I have a function that I wrote long ago to parse strings up in an easy manner. It is in use on several of my Arduino projects.
Sample usage:
char pinStr[3];
char valueStr[7];
int pinNumber, value;
getstrfld (parms_in, 0, 0, (char *)",", pinStr);
getstrfld (parms_in, 1, 0, (char *)",", valueStr);
pinNumber = atoi (pinStr);
value = atoi (valueStr);
The functions:
// My old stand-by to break delimited strings up.
char * getstrfld (char *strbuf, int fldno, int ofset, char *sep, char *retstr)
{
char *offset, *strptr;
int curfld;
offset = strptr = (char *)NULL;
curfld = 0;
strbuf += ofset;
while (*strbuf) {
strptr = !offset ? strbuf : offset;
offset = strpbrk ((!offset ? strbuf : offset), sep);
if (offset) {
offset++;
} else if (curfld != fldno) {
*retstr = 0;
break;
}
if (curfld == fldno) {
strncpy (retstr, strptr,
(int)(!offset ? strlen (strptr)+ 1 :
(int)(offset - strptr)));
if (offset)
retstr[offset - strptr - 1] = 0;
break;
}
curfld++;
}
return retstr;
}
// Included because strpbrk is not in the arduino gcc/g++ libraries
// Or I just could not find it :)
char * strpbrk (const char *s1, const char *s2)
{
const char *c = s2;
if (!*s1) {
return (char *) NULL;
}
while (*s1) {
for (c = s2; *c; c++) {
if (*s1 == *c)
break;
}
if (*c)
break;
s1++;
}
if (*c == '\0')
s1 = NULL;
return (char *) s1;
}
A light-weight approach (no strict checks on valid parses of the integers and ignoring any list elements past a fixed maximum):
char buf[32] = "COMSTEP 789 665 432 END"; // assume this has just been read
int res[8], nres = 0;
bool inlist = false;
for (char *p = strtok(buf, " "); p; p = strtok(0, " "))
if (inlist)
{
if (!strcmp(p, "END"))
{
inlist = false;
break;
}
else if (nres < sizeof(res) / sizeof(*res))
res[nres++] = atoi(p);
}
else if (!strcmp(p, "COMSTEP"))
inlist = true;
if (!inlist)
for (size_t i = 0; i < nres; ++i)
printf("%d%s", res[i], i + 1 < nres ? " " : "\n"); // do whatever