texts: How can I pass an object as a parameter to a function?

texts:
I am making a tiny game, and want to store high-scores. I made a Highscore-class in the top of the sketch file, like this:

class Highscore {
public:
  String name;
  int score;

  String toString() {
    return this->name + " - " + (String)score;
  }

  Highscore(String name, int score) {
    this->name = name;
    this->score = score;
  }
};

setup() { // etc

Now. Near the bottom of the sketch, I have a function I want to take a Highscore-object as a parameter, but the compiler will not let me. Example:

void writeHighscore(Highscore hs) {
  File f = SD.open("high.txt", FILE_WRITE);
  // Do stuff

The complation error is as follows:

  sketch.ino:19:21: error: variable or field ‘writeHighscore’ declared void
  sketch.ino:19:21: error: ‘Highscore’ was not declared in this scope
  sketch.ino: In function ‘void setup()’:
  sketch.ino:64:20: error: ‘writeHighscore’ was not declared in this scope

After changing parameter type to String, int or whatever, all the errors go away. I am able to create Highscore-objects INSIDE the writeHighscore() function, but how can I pass objects to it?

Edit 1 - Object creation

Highscore hs = Highscore("John", 975);
Serial.println(hs.toString()); // Prints "John - 975" as expected
writeHighscore(hs); // Error


texts:
I am just getting started with my Uno via the Vilros Ultimate Starter Kit. I've done all of the sample circuits and played around with a few other things.

Today I connected the Ethernet shield with the intention of building a temperature logger. I am finding that the output I get from the included TMP36 temperature sensor is much different with the Ethernet shield installed.

The kit's sample circuit #7 for the temperature sensor connects the sensor directly to 5V and GND and the sensor output to A0. The loop code (compressed a bit for pasting here) looks like this:

float voltage, degreesC, degreesF;
voltage = analogRead(temperaturePin) * 0.004882814;
degreesC = (voltage - 0.5) * 100.0;
degreesF = degreesC * (9.0/5.0) + 32.0;
// Write to serial; omitting for brevity
delay(1000);

Without the Ethernet shield installed, a typical output I get from this looks like:

voltage: 0.81  deg C: 30.57  deg F: 87.02

That might be a little high but it feels close enough for what I'm going for at the moment (I don't have a reliable thermometer with me, but it's a warm day here). It's close enough, and is stable across readings.

With the shield installed, the exact same circuit and sketch outputs this:

voltage: 0.96  deg C: 46.19  deg F: 115.14

It's still very stable across readings but obviously way off. What could cause this and how can I fix it? I am not expecting the sensor to be perfectly accurate but the major discrepancy I'm seeing makes this unworkable.


texts: Do the libraries of the Arduino Uno work with the Arduino Mega?

texts: I did a project with the Arduino Due and the libraries for the VS1053 MP3 Shield were not compatable with the Due. Are the libraries that work with the Uno compatable with the Arduino Mega?


texts: Which of the ESP8266 alternatives allows for full packet capture/injection in promiscuous mode?

texts:
I am part of a product group that is developing a low cost wireless intrusion detection system, for home usage.

We have already produced and delivered to market ESP8266 based product however for the new thing, we need the chipset to be able to enter promiscuous mode and receive/inject 802.11 packets on the fly without any limits.

ESP8266 is limited to 112bytes max, which is not enough to even parse the Beacon frame properly.

What are the alternatives for ESP8266 currently - that allow:

to capture the 802.11 frames
have no packet length limits
allow packet injection

Ps. doesn't have to be ARDUINO - but needs to be C/C++ programmable.

Thanks in advance.


texts: Reading analog signal from digital pin #6

texts:
Is it possible to use digital pin 6 (PD6_PCINT22/AIN0) to read an analog voltage with analogRead()?

According to the ATMega datasheet, this should be possible.

If yes how is it done ? (pin configuration)


texts:
I'm developing on android with bluetooth LTE, I can send hex codes, but I send one code at time, so I need to send many informations in this way, how can I recognize a string and save the datas inside an array to parse it later?

Here is my sketch:

 char c=' ';
 String inString,one,check;
 char inData[11];
 char inChar;
 int counter=0;
 bool started = false;
 bool ended = false;
 byte index;

boolean NL = true;
const int LED1 = 6;
const int LED2 = 7;
const int LED3 = 2;
const int LED4 = 3;
const int LED5 = 4;
const int LED6 = 5;

void setup() {
   Serial.begin(9600);
    Serial.print("Sketch:   ");   Serial.println(__FILE__);
    Serial.print("Uploaded: ");   Serial.println(__DATE__);
    Serial.println(" ");

    BTserial.begin(9600);
    Serial.println("BTserial started at 9600");

    pinMode(LED1, OUTPUT);
    pinMode(LED2, OUTPUT);
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);
    pinMode(LED5, OUTPUT);
    pinMode(LED6, OUTPUT);

}

void loop() {

  if (BTserial.available()>0)
    {
      Serial.print("bts: ");
      Serial.println(BTserial.available());
      c = BTserial.read();
      check =  String(c, HEX);

      if(check=="ffbc"){
        Serial.println("check");
        index=0;
        while (BTserial.available()>0){

            inChar = BTserial.read();
            check=String(inChar,HEX);
            if(check != "0xfff3")
            {
                inData[index] = inChar;
                index++;
            }
        }
        for (int i=0;i<=11;i++){
          one =  String(inData[i], HEX);
          Serial.print(i);Serial.print(": ");Serial.println(one);
        };

      }

             if(check=="ffca"){
             // Serial.write(c);
              digitalWrite(LED1, !digitalRead(LED1));
             }
             if(check=="ffcb"){
              //Serial.write(c);
              digitalWrite(LED2, !digitalRead(LED2));
              }
              if(check=="ffcc"){
              //Serial.write(c);
              digitalWrite(LED3, !digitalRead(LED3));
             }
             if(check=="ffcd"){
              //Serial.write(c);
              digitalWrite(LED4, !digitalRead(LED4));
              }
              if(check=="ffce"){
             // Serial.write(c);
              digitalWrite(LED5, !digitalRead(LED5));
             }
             if(check=="ffcf"){
             // Serial.write(c);
              digitalWrite(LED6, !digitalRead(LED6));
              }
    }
}

Without the loop I can read all the single datas, but for my job it's not enough, to recognize the data applications I send a "sample string" to recognize the type of informations I want to send.


texts:
I have 7 float variables.

float temperature, differential, calibration,hta,lta,hha,lha;

I want to store them all on the EEPROM memory, how do I calculate the addresses given that there type is float.

Thanks!


texts:
Inside my main loop there is this string:

String string1;

I have a function that will take string1 as parameter, and use it to send this string as SMS.

sendSMS(string1);

This is the sendSMS() function (without parameters):

void sendSMS()
{ sms.beginSMS(remoteNumber);
  sms.print(finalstr);
  sms.endSMS();
  lcd.setCursor(0, 0);
  lcd.print("Message sent!");
  delay(10000);
}

My questions are:

How do I put the string input parameter in sendSMS?
Do I also need to use a function prototype for sendSMS()? (so that it appears three times, 1 in the prototype, 1 in the declaration and one in the call). Or I don't need to use function prototype before the main loop()?


texts: How to add a pedestrian button code to a traffic light with ultrasonic sensor?

texts:
So I have a project to create a 2 set of traffic lights which would detect a car coming and stopping on the ultrasonic sensor and my code would allow the traffic lights to loop and let the car through. But now I also have to add a pedestrian code in for the pedestrians to press the button, the traffic lights to loop back to red and give 30 seconds of crossing time.

I did the ultrasonic sensor traffic lights code already and some of it seems confusing but somehow works quite well. I'm not familiar with the buttons and looping the traffic lights correctly back to red so I need help to add a pedestrian crossing code to this code:

// Variables for Station 1 Traffic Light Components
const int Red1LED = 9;
const int Yellow1LED = 2;
const int Green1LED = 3;
const int GreenArrow = 4;
#define trigPin 12
#define echoPin 13
// Setup Variables for Station 2 Traffic Light Components
const int Red2LED = 5;
const int Yellow2LED = 6;
const int Green2LED = 7;
const int GreenArrow2 = 8;

void setup() {

  pinMode(Red1LED, OUTPUT);
  pinMode(Yellow1LED, OUTPUT);
  pinMode(Green1LED, OUTPUT);
  pinMode(GreenArrow, OUTPUT);
  pinMode(Red2LED, OUTPUT);
  pinMode(Yellow2LED, OUTPUT);
  pinMode(Green2LED, OUTPUT);
  pinMode(GreenArrow2, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);
 Serial.begin(9600);
  // Set Initial state of all red LED to HIGH
  digitalWrite (Red1LED, HIGH);
  digitalWrite (Red2LED, HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
 long duration, distance;
  digitalWrite(trigPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(1000); - Removed this line
  //delayMicroseconds(10); // Added this line
  //digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  Serial.println(distance);
  if (distance < 20) {  // This is where the LED On/Off happens
     delay(1000);  //  1 Seconds of Red
  digitalWrite(Green1LED, LOW);  //  Sets Red1 OFF Green ON
  digitalWrite(Yellow1LED, HIGH);
  delay(1000);  // 1 Seconds of Green
  digitalWrite(Yellow1LED, LOW);  //  Sets Green1 OFF Yellow ON
  digitalWrite(Red1LED, HIGH);
  delay(1000);  // 1 Seconds of Yellow
   // Station 2 Timing
  delay(1000);  //  1 Second of Red
  digitalWrite(Red2LED, LOW);
  digitalWrite(GreenArrow2, HIGH);  //  Sets Red2 OFF Green ON
  delay(1000);  // 1 Second of Green
  digitalWrite(GreenArrow2, LOW);
  digitalWrite(Green2LED, HIGH);  //  Sets Green ARROW OFF Yellow ON
  delay(1000);  // 1 Second of Yellow
  digitalWrite(Green2LED, LOW);
  digitalWrite(Yellow2LED, HIGH); // Sets Green 2 OFF YELLOW OFF
  delay(1000);
  digitalWrite(Yellow2LED, LOW);
  digitalWrite(Red2LED, HIGH);

   digitalWrite(Red1LED, LOW);
  digitalWrite(GreenArrow, HIGH);
  delay(1000);
  digitalWrite(GreenArrow, LOW);  //  Sets Yellow1 OFF Red ON
  digitalWrite( Green1LED, HIGH);
}
  else {
   digitalWrite(Red1LED, LOW); // When the Red condition is met, the Green LED should turn off
  digitalWrite(Red2LED, HIGH);
  digitalWrite(GreenArrow, LOW);
  digitalWrite(Green1LED, HIGH);
  digitalWrite(Yellow1LED, LOW);
  digitalWrite(Yellow2LED, LOW);
  digitalWrite(Green2LED, LOW);
  digitalWrite(GreenArrow2, LOW);

  }
}

I NEED HELP ASAP PLEASE. Due tomorrow by 12 am. It is extension so I am not that worried if I don't get help by the deadline but if I still do after the deadline I can still learn so don't hesitate to post.


texts:
Let's say that I've tried sending an SMS directly from serial monitor or any kind of terminal. For whatever reason (syntax error, etc), my attempt fails. Now, I try sending it again, but this time by code (as seen on this site):
#include <SoftwareSerial.h>

//SIM800 TX is connected to Arduino D8
#define SIM800_TX_PIN 8

//SIM800 RX is connected to Arduino D7
#define SIM800_RX_PIN 7

//Create software serial object to communicate with SIM800
SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);

void setup() {
  //Begin serial comunication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);
  while(!Serial);

  //Being serial communication witj Arduino and SIM800
  serialSIM800.begin(9600);
  delay(1000);

  Serial.println("Setup Complete!");
  Serial.println("Sending SMS...");

  //Set SMS format to ASCII
  serialSIM800.write("AT+CMGF=1\r\n");
  delay(1000);

  //Send new SMS command and message number
  serialSIM800.write("AT+CMGS=\"07194XXXXX\"\r\n");
  delay(1000);

  //Send SMS content
  serialSIM800.write("TEST");
  delay(1000);

  //Send Ctrl+Z / ESC to denote SMS message is complete
  serialSIM800.write((char)26);
  delay(1000);

  Serial.println("SMS Sent!");
}

void loop() {
}

The code sends not only the SMS within the code ("TEST"), but also the unwanted junk / remains of the previously unsuccessful sending attempt.
Is there a way to clear the module's buffer before sending a new message?
I guess I could restart the module before sending messages, but I was wondering whether there's a cleaner solution.
P.S. I apologize for the slightly misleading and irrelevant tags, but I can not use the nonexistent sim800L, which would be better suited for my question.


texts: Can I upload with avrdude 2 hexes with 2 usbasp connected to computer, one hex with one usbasp ? If yes, how?

texts: If I have connected 2 usbasps in the same time to ubuntu, can I upload 2 hexes one after the other(using avrdude) on each usbasp without disconnecting a usbasp ? If yes, how do I select each port for each hex ?


texts: I can't use buffer without printing in my Nodemcu esp8266

texts:
#include <ESP8266WiFi.h>

#include <ESP8266HTTPClient.h>
#include <WiFiClientSecureBearSSL.h>

#define WIFI_SSID "ssid"
#define WIFI_PASSWORD "password"

void setup() {
  Serial.begin(9600);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(300);
  }
  Serial.println();
  Serial.print("Connected with IP: ");
  Serial.println(WiFi.localIP());
  Serial.println();
  ////////////////////////////////////////////

  std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
  client->setInsecure();
  HTTPClient http;

  http.begin(*client, "https://jsonplaceholder.typicode.com/photos");
  http.addHeader("Accept", "*/*");

  int httpCode = http.GET();
  Serial.print("HTTP CODE: "); Serial.println(httpCode);

  //reading response with buffer
  static char buff[128] = { 0 };
  while (http.connected() ) {
    size_t size = client->available();
    if (size) {
      int c = client->readBytes(buff, ((size > sizeof(buff) ) ? sizeof(buff) : size));
      //if i uncomment this next line, everything is fine.
      //Serial.write(buff, c); Serial.println();

      //but if i dont use serial.write program never gets here
      if (char * pch = strstr (buff, "quis fuga")) {
        char str[20] = { 0 }; int g =   0 ;
        while (pch[g] != '\"') {
          str[g] = pch[ g];
          g++;
        }
        Serial.print("FOUND IT: "); Serial.println(str);
      }

    }
    else if (!size) {
      Serial.println( "reading done");
      break;
    }
    delay(1);
  }

}

void loop() {

  delay(222222);

}

EDIT
here i created a compilable runnable code. basically i am trying to find a word in a http response. my real examples response isnt json and it is as long as this examples response. one other problem is i cant read all of the repsponse. it unexpectedly finishes reading sometimes after a few lines sometimes after a few hundred. in this particular request my nodemcu cant read after id 258. or id 8. object in the json response: https://jsonplaceholder.typicode.com/photos

if i dont use serial.write print buffer content, it finishes reading immideatly and thats exactly where i have the problem.


texts:
So there is this pretty generic part of my project that involves triggering an ISR that will flip a boolean value. I have set up the software side like so:

void setup() {
  attachInterrupt(digitalPinToInterrupt(2), displayConvergence, FALLING);
}

void loop() {
  if(flashConvergence) {
    //Do stuff that takes several seconds
    delay(3000);
    flashConvergence = false;
  }
}

void displayConvergence() {
  if (!flashConvergence) {
    flashConvergence = true;
  }
}

The schematic is as follows:

simulate this circuit – Schematic created using CircuitLab

But the behavior of my circuit surprised me as the pin interrupt would get triggered randomly at a frequency at (guessing here) 3 times a second.

Weird, I thought. I fiddled around and found that when the boost converter's 180V is not connected to any load, the interrupt service triggers as expected, as in it starts working correctly. So I thought perhaps the issue was some noise introduced by the boost converter.

I modified the circuit by adding a capacitor across the switch:

simulate this circuit

I tried 1 uF at first, but that didn't help and neither did 10 uF. However, when I tried 100 uF (I thought decoupling capacitors are usually 0.1uF to 1 uF, is the value I am using too big?), things seem to be working as expected with the exception that when I hold the switch in the closed position for a long time, then let it go back in the open position, the interrupt service can be triggered randomly for a short period right after I let go of the switch.

Is my initial assumption that the ISR is triggering randomly due to EMI from the boost converter correct? Perhaps there are other causes I am not looking at? Is there a way to make this work 100% (as in solve the issue right after the switch is put in the open position)?

Thanks for the help!


texts: Reading a 10 pin 7 segment (2 digits) sing Arduino 1. Please Help!

texts:
thanks for taking the time to read this, I really appreciate it.
I am very new to Arduino and the Micro controller world so please forgive my ignorance.

So I have an old 7 segment display that displays outside temperature, what i want to do is read the temp into the Arduino and light up an LED if the temperature gets high, and a different color if the temp gets low.

I know i can use a thermometer and plug it into the Arduino and go from there, but that would be cheating. So my question is, can i read each pin of the 7 segment display and translate that into a number into the Arduino?

Task: Read a dual  10 pin 7 segment by jumping wires into the Arduino.
Setup: I am using the code and setup found here: "http://blog.rastating.com/using-a-7-segment-led-display-w-arduino-uno/" to display a number (21) for testing purposes. I want to jump the pins into another Arduino and read "21"

please see pictures.

Any help would be very very appreciated!!

Thanks again for reading.

This last picture shows "21" using the code and set up on the above link.
I want to jump another Arduino into the breadboard and read "21" or any other temperature (depends on outside thermometer) into the serial monitor. Now the challenging part is the code, Im not really good at coding but i understand if this had 1 pin for each LED i would just read each one and translate it into the serial monitor. However this only has 10 pins therefore represents a challenge.

Any input is greatly appreciated, I dont even know how to start.


texts: Routing Arduino Mega output to either one of two serial ports

texts:
I have an Arduino Mega controller that normally communicates via Bluetooth (HC08 Bluetooth module) to an Android device. In case there is a problem on the Android side I wish to have a fallback ability to communicate via the USB serial port. The choice of serial port is determined by a hardware switch that the Arduino can read. Currently I have:
HardwareSerial & Terminal = Serial;
HardwareSerial & BTPort = Serial1;

Is there a way to route an output to either BTPort or to terminal, dependent on the state of the switch? Ideally I would like to do something like this:
HardwareSerial & OutputPort
if(switch_is_on)
  OutputPort = Terminal;
else
  OutputPort = BTPort;

Obviously the above code does not work. I have no idea of how to proceed.


texts: Bluetooth Communication Not Working with DC Power But Works With USB Power?

texts:
I am running a HM-10 Bluetooth Low Energy (BLE) module to transmit serial data (using SoftwareSerial) from an analog sensor onboard my Arduino Uno to a serial terminal app on my Android phone. When I power the Arduino with a USB power bank, the data transmits flawlessly.

When I tried to power the Arduino with a 9V battery through the DC power jack instead of USB power, the BLE module connects to my phone, but no data is transmitted when a serial connection is established.

Any ideas why this would be?


texts: How compile an Arduino program for a desktop PC

texts:
I have an arduino program that only does serial communications with a little bit of math, and I am writing another one to communicate with it on a second arduino.  For testing purposes I was hoping I could run the serial only program on my desktop.  I know it is possible to run on a raspberry pi but I have never done that.  Can I do something similar on windows?  If not, can anybody recommend the easiest way to do this with a regular C++ program that would require very little editing? Here is a copy of my code if it's helpful.  It basically increments a variable up and down between 0 and 100.

int pos = 60;
bool flag=0;
int dly=50;
int vel=0;

const int buttonPin =  12;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);

Serial.begin(115200);
}

void loop() {
    dly=50;
    buttonState = digitalRead(buttonPin);
    if (buttonState==0)dly=12;
    Serial.print(vel); //speed
    Serial.print(",");
    Serial.println(pos); //position
    delay(dly);
    if (pos==30)flag=1;
    if (flag==1) pos+=1;
    if (pos==100)flag=0;
    if (flag==0) pos-=1;
    vel=1000/dly;
    if (flag==0) vel*=-1;

}


texts: Controlling 2 DC Motors with L293D and 6 V battery pack?

texts:
Sorry if my question looks newbie, but I'm just starting to delve into robotics and electronics, and my first project was building a small arduino collision-avoidance robot with a ultrasonic range finder, one servo and two dc motors. Right now I'm using a 6V battery pack to power both DC motors, another 6V just for the servo, and a 9V battery for the arduino.
But I'm in doubt if the power supply for the DC motors is enough. I'm using an L293D IC to control both motors, but the robot can barely move under load (and the total weight of the robot is not that much. I already reduced all the weight I could). So, how much power, typically, I should supply for the L293D to control those motors?


texts: How many UNO pins have internal pull up resistors?

texts:
As the title implies.
thank you in advance.


texts: Is it possible to use I2C and SPI ons the same Clock line?

texts: I'm trying to connect an I2C OLED display and an n RF24L01 WiFi module to an ATTiny85. But I only need 1 extra pin. Is it possible to use the same clock wire/pin for the I2C and SPI device? Maybe with some extra code? Thanks a lot!


texts: RFID system for proximity detection with data logging

texts:
I am wondering if anybody has ideas for developing an Arduino-based system that would use RFID to log occurrences when two people are in close proximity to each other (e.g., <= 1 meter).  Ideally, I would like to construct something that would operate in a manner very similar to the OpenBeacon system -- and, preferably, the events/data would be transmitted via wi-fi in real time.

My ideas are as follows, so any feedback or alternative solutions would be greatly appreciated.  (Please keep in mind that I am not an engineer!)

I am thinking of using a wi-fi enable microprocessor (e.g., Arduino Yun) that would serve as the reader or detection system.  For beta-testing, this device could be set in an enclosed case and attached to a belt.  I presume it would require a fairly robust battery supply.  The other person would be wearing an RFID tag that has a range of <= 1 meter and would log the event.  Ideally, a reading would take place roughly every 30 seconds, and the captured event would be transmitted over wi-fi.

Here are a few other things to keep in mind:

The people using the hardware should not have to do anything other than simply wear the constructed devices.
The reader itself should be as small as possible.
My ultimate goal is the data logging of the proximal events.

I am certainly open to other technologies, as my ultimate goal is simply the proximity detection with data logging (preferably via wi-fi).

Thanks in advance!
Brian


texts: I'm getting NaN for readings on my DHT22 sensor when using 3v3 pin, but not 5v pin

texts:
I have a DHT22 temperature sensor and DS1302 RTC module connected to the 3v3 pins on an Arduino Nano. Both the sensor and the RTC module are rated to work on either 3.3V or 5V, but the recommendation is 3.3V.  For some reason though, when I connect the sensor and RTC to 3.3V power on the Nano, the sensor just returns NaN even though the RTC module works.  When I change the sensor to use 5V and leave the RTC on 3.3V, I get a proper temp and humidity value on the DHT22.  What is wrong?

Turns out the solder joint for the 3v3 pin on the nano was not properly done. I figured this out after I swapped out the nano for another nano and it worked. Resoldering the 3v3 pin fixed the problem.


texts: compile error when using two typename in template class

texts:
I am using Arduino 1.8.5 ide. I am just creating a class with two typename which name is "Map". This class takes all int and String variations. Like;

class Map<int, int>;
class Map<int, String>;
class Map<String, int>;
class Map<String, String>;

Map<int, String> *list = new Map<int, String>();

If I create instance of this class like above in Main.ino file then everything is ok. But if I create it another file with .h extension which is "Test.h" then compilation fails. These are files;

    Main.ino

#include "Map.h"
#include "Test.h"

Test *test = new Test();
Map<int, String> *list = new Map<int, String>();

void setup() {

}

void loop() {

}

Map.cpp

#include "Arduino.h"
#include "Map.h"

template<typename E, typename T> Map<E, T>::Map()
{

}

template class Map<int, int>;
template class Map<int, String>;
template class Map<String, int>;
template class Map<String, String>;

Map.h

#ifndef Map_h
#define Map_h

#include "Arduino.h"

template<typename E, typename T> class Map {

public:
    Map();
    ~Map();
};

#endif

Test.h

#ifndef _Test_h
#define _Test_h

#include "Arduino.h"
#include "Map.h"

class Test
{
public :
    Test();
    ~Test();
    Map<int, String> *list = new Map<int, String>();
};

#endif

Error is;

In file included from C:\Users\zafer\Desktop\Main\Main.ino:3:0:
Test.h:14: error: expected ';' at end of member declaration
  Map<int, String> *list = new Map<int, String>();

                                        ^

Test.h:14: error: expected unqualified-id before '>' token
  Map<int, String> *list = new Map<int, String>();

                                              ^

Test.h:14: error: wrong number of template arguments (1, should be 2)
  Map<int, String> *list = new Map<int, String>();

                                   ^

In file included from C:\Users\zafer\Desktop\Main\Main.ino:2:0:
Map.h:6: error: provided for 'template<class E, class T> class Map'
 template<typename E, typename T> class Map {

                                        ^
exit status 1
expected ';' at end of member declaration

Sorry, If it's been already resolved and I couldn't find it.

Thank you.


texts:
I am using the SoftAP feature of the ESP to create a central node, and connecting five or six clients in the final application. However, I don't know if i can connect that many clients.

One of the core files on GitHub, esp_wifi_types.h shows two conflicting lines:

#line 215, as a member of the 'wifi_ap_config_t' struct
uint8_t max_connection; /**< Max number of stations allowed to connect in, default 4, max 4 */

#line 254
#define ESP_WIFI_MAX_CONN_NUM (10) /**< max number of stations which can connect to ESP32 soft-AP */

So is it four or ten? Or something else? Any advice by somebody who's tried this would be appreciated.

esp_wifi_types.h on GitHub


texts:
In my setup, I've got a number of ESP8266 devices around my home controlling various devices like my boiler and some lights.

They're all controlled by a central smart hub on a Raspberry Pi with a static's IP address.

This works great, but I'm increasingly concerned of the security implications of this. Communication between the Pi and the various ESP8266s is currently done over HTTP, with all the commands simply in the URL the Pi requests from the web servers.

As such, anyone on my network could theoretically control these smart devices using a simple curl request.

Whilst I have a strong Wi-Fi password, and am using WPA2 encryption, I would feel much more comfortable if communication with the ESP8266s was controlled in some way. E.g. in the same sort of way you can only connect to an SSH server using public key encryption if you have the right private key.

Is something like this possible to implement on an ESP8266? I've done some searching and only found articles about HTTPS which doesn't seem like it would solve my problem.

Thanks in advance,
Rocco


texts:
I have two I2C LCD screens:

one with 2 lines
one with 4 lines.

Both have 4 pins each: GND, VCC, SDA, SDL. I connect SDA and SDL to A4 and A5 respectively, and I display text on each one of them with:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,4);

But how can I use both of them at the same time?

I connected the second one's SDA and SDL to A2 and A3, but apparently I have to provide the right address for them (like 0x27), right?

However, while both are connected, using I2C_Scanner only shows one device:

Scanning...
I2C device found at address 0x27  !
done

What am I missing?


texts: Powering arduino sensors - what resistor should I use?

texts:
Recently I have asked a question, why my sensors do not work on external power supply (link). I have found out, that I was limiting the current too much with the resistors. I have tried using two sensors:

DHT22, rated at 1.5mA max (picture of my module)
BH1750, rated at 190uA max (picture of my module)

My logic is, if they are rated at that current, I should put a resistor in the Vin, to restrict the current to given value. But it turned out that I was wrong, because they started working only after I removed my resistors.

My questions is - should I put a resistor in there? If yes, then how do I know what resistance should I have, if the data sheet values are misleading?


texts: Arduino Mega web server always returning JSON data even if JSON is not passed in URL

texts:
I am trying to return JSON data if JSON is found in the HTTP header, and if not I am trying to display a normal page. But instead it always displays the JSON text, even if I do not pass the JSON in the URL! Full code is here.

if (client) {
  // an http request ends with a blank line
  boolean currentLineIsBlank = true;
  boolean sentHeader = false;
  while (client.connected()) {
    if (client.available()) {
      // client data available to read
      char c = client.read(); // read 1 byte (character) from client
      // buffer first part of HTTP request in HTTP_req array (string)
      // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
      if (req_index < (REQ_BUF_SZ - 1)) {
        HTTP_req[req_index] = c; // save HTTP request character
        req_index++;
      }
      // last line of client request is blank and ends with \n
      // respond to client only after last line received
      if (c == '\n' && currentLineIsBlank) {
        if (!sentHeader) {
          // send a standard http response header
          client.println(F("HTTP/1.1 200 OK"));
        }
        // Ajax request - send JSON output
        if (util::StrContains(HTTP_req, "json")) {
          // Spit out JSON data
          client.println("Content-Type: application/json;charset=utf-8");
          client.println("Server: ArduinoMega");
          client.println("Connnection: close");
          client.println();
          client.print("{\"arduino\":[{\"location\":\"outdoor\",\"celsius\":\"");
          client.print(tempInC);
          client.print("\"}]}");
          client.println();
          break;
        } else {
          client.println(F("Content-Type: text/html"));
          client.println(F("Connection: close")); // the connection will be closed after completion of the response
          client.println(F("Refresh: 1000")); // refresh the page automatically every 60 sec
          client.println();
          sentHeader = true;
          client.println(F("<!DOCTYPE HTML>"));
          client.println(F("<title>"));
          client.println(F("Welcome to Arduino WebServer</title>"));
          util::printProgStr(client, htmlStyleMultiline );
          client.println(F(""));
          client.println(c);
          client.print(F("
 LIVE:
"));

Please help.


texts: Can I switch from Serial to SoftwareSerial at runtime with the same baud?

texts:
I'm trying to use a GPS and the Adafruit thermal printer module with an Arduino Nano in the same project (both use baud 9600) and was wondering if I could do something like in the code below? Basically, in the example I made, I'm getting the time from the GPS and when it's on the minute, it will call the printTime() method.

What I'm wondering is if it's okay to do what I did in my disableGPS, enablePrinter methods by ending the serial connection for GPS and starting it for my printer? I feel like this should work, but I don't fully understand serial connections.

If this doesn't work, is there an alternative I could do? I never need to read from GPS and write to the printer at the same time in code.

#include <Adafruit_Thermal.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#define PrinterTXPin 6 // Arduino transmit  YELLOW WIRE  labeled RX on printer
#define PrinterRXPin 5 // Arduino receive   GREEN WIRE   labeled TX on printer

static const uint32_t baud = 9600;
//Printer
SoftwareSerial PrinterSerial(PrinterRXPin, PrinterTXPin);
Adafruit_Thermal printer(&PrinterSerial);
//we only want to print on the minute
boolean havePrinted = false;

//GPS
TinyGPSPlus gps;
TinyGPSDate lastDate;

void setup() {
  enableGPS();
}

void loop()
{
  if(gps.time.isValid() && checkDate(gps.time)){
    printTime(gps.time);
  }
}

boolean checkDate(TinyGPSTime theTime)
{
 if(theTime.second() == 0 && !havePrinted)
 {
    havePrinted = true;
    return true;
 }
 if(theTime.second() == 1){
    havePrinted = false;
 }
}

void printTime(TinyGPSTime theTime)
{
  //Disable since we can only have 1 serial connection per baud
  disableGPS();
  enablePrinter();

  printer.doubleHeightOn();
  printer.println(theTime.hour() + ":" + theTime.minute());
  printer.feed(1);

  disablePrinter();
  enableGPS();
}

void enablePrinter()
{

  PrinterSerial.begin();
  printer.begin();
  printer.wake();
}

void disablePrinter()
{
  printer.sleep();
  PrinterSerial.end();
}

void disableGPS()
{
  Serial.end();
}

void enableGPS()
{
  Serial.begin(baud);
}


texts: Arduino Mega + XBee Shield + RAMPS 1.4 Is it possible?

texts:
Is it possible to sandwich an XBee shield between Arduino Mega and Ramps 1.4 without damaging any of the boards or lose of Ramps functionality ?

I am not trying to make a 3D printer it is rather a completely different project and I am afraid of burning my XBee or losing some functionality of ramps.

Since XBee shield has the form factor of Arduino UNO I had to 3D print the rest of the shield and use some connectors to completely cover the Mega.


texts: What Kind of relay module to use if i want to turn on or off high voltage appliances like AC?

texts: What kind of relay module to use if i want to turn on or off my AC (which is a 1.5 ton bluestar) using arduino. Like we use a 5v relay for small appliances like fan and lights, what to use if i want to control my AC or Geyser???


texts: Error: Function not declared in the scope

texts:
I want to make a timer library. The cpp file I have written is:

#include "avr/interrupt.h"
#include "Arduino.h"

#include "AllTimer.h"

AllTimer::AllTimer()
{}

void AllTimer::dofun(void)
{
    TIFR1 |= _BV(OCF1A);
    TCCR1B = 0X00;
    digitalWrite(13,!digitalRead(13));
}

void AllTimer::setTimer(void)
{
    TCNT1 = 0x0BDC;
    TCCR1A = 0x00;
    TCCR1B = 0x00;
    TCCR1B |= (1<<CS12) && (1<<CS10);
    TIMSK1 |= (1<<TOIE1);
    sei();
}

ISR (TIMER1_OVF_vect)
{
    dofun();
}

And the header file:

#ifndef AllTimer_h
#define AllTimer_h

class AllTimer{
public:
    AllTimer();
    void setTimer(void);

private:
    void dofun(void);
};

#endif

While compiling the file i am getting the following error:

sketch_jan05a.cpp: In function ‘void __vector_13()’:
sketch_jan05a.cpp:34:9: error: ‘dofun’ was not declared in this scope


texts: ESP8266 - AP+STA mode not working properly

texts:
I'm trying to have an ESP8266 ESP-12 to serve as Access Point and Station at the same time, delivering the same webpage in both cases.
This is what I have:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <EEPROM.h>
#include <DNSServer.h>
#include <ESP.h>

const byte DNS_PORT = 53;
DNSServer dnsServer;

MDNSResponder mdns;
ESP8266WebServer server(80);

String ssid = "";
String password = "";
String webPage = "";

void setup(void){

  IPAddress Ip(192, 168, 1, 1);
  IPAddress NMask(255, 255, 255, 0);
  WiFi.softAPConfig(Ip, Ip, NMask);
  WiFi.softAP(conf_ssid.c_str());
  WiFi.mode(WIFI_AP_STA);
  Serial.begin(115200);
  delay(1000);
  Serial.println("");
  Serial.println("Soft AP Started");
  Serial.println("");

  /* Setup the DNS server redirecting all the domains to the Ip */
  dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
  dnsServer.start(DNS_PORT, "www.example.com", Ip);

  //connectToWifi();
  getCredentials(); //Reads Home WiFi credentials from the EEPROM
  if (ssid != "" and password != ""){
    WiFi.begin(ssid.c_str(), password.c_str());
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    WiFi.mode(WIFI_AP_STA);
  }
  server.begin();

  // When no password is present
  if ((ssid == "" and password == "") or (ssid == "Error")){
    // ****** MAIN PAGE ******
    server.on("/", [](){ /* HANDLES CREDENTIAL INPUT */   });
    server.begin();
  }
  else // If we have ssid and password -- check if we have connection
  {
    webPage += "
Main Webpage
";
    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
    server.begin();
    //if (mdns.begin("esp8266", WiFi.localIP())) {
     // Serial.println("MDNS responder started");
    //}

    server.on("/", [](){
      server.send(200, "text/html", webPage);
    });
    Serial.println("HTTP server started");
  }
}

void loop(void){
  dnsServer.processNextRequest();
  server.handleClient();
}

Basically, it reads the credentials from the EEPROM, if there is no credential, a WiFi configuration page is displayed, otherwise it also connects to the WiFi serving the Main Webpage to both AP and Station.

The issue is that, even though I can see the AP and a ping from my PC to the WiFi Station's Ip works, I can only access the webpage if I'm connected via AP, not via Station.
Any thoughts?

Many thanks.


texts: How to control a DSP-G1 programmatically/electronically?

texts:
I want to generate music/sounds for a video game I am making with my son (using an Arduino Mega and a 240x320 LCD graphical display). I have a basic understanding of the MIDI protocol. I've been a computer programmer for over 30 years. I read the MIDI implementation in the DSP-G1 manual, but I don't understand how to go from this to sending the right signals from the dev board to the chip pins.

Everything I find is about connecting a physical MIDI device. Can anyone possibly provide or point me to information on how to control the DSP-G1 programmatically/electronically? I think I need some hardware or software to serialize MIDI protocol bytes into a sequence of voltage changes, but all my searching leads me to info about a physical device.


texts: Decode rf remote signals with ESP32 or node MCU?

texts:
I'm trying to decide my rf remote signals using ESP32 or node MCU. I have tried with Arduino and was successful but for some reason it is not working on either ESP32 or node MCU even using the same GPIO2 pin can anyone please tell me why both the boards are not able to decode the signal. I'm using the rc-switch library to decode and a 433Mhz transmitter reciever combo from amazon

RCSwitch mySwitch = RCSwitch();

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
}

void loop() {
  if (mySwitch.available()) {
    output(mySwitch.getReceivedValue(), mySwitch.getReceivedBitlength(), mySwitch.getReceivedDelay(), mySwitch.getReceivedRawdata(),mySwitch.getReceivedProtocol());
    mySwitch.resetAvailable();
  }
}```


texts: Why must I reload ArduinoCreateAgent-1.1-windows-installer-chrome every time I restart my computer?

texts:
What am I missing that this is happening?
Used to use a laptop (with Create Agent installed on hard drive) which never had this problem.
Now using a Windows 10 desktop and the On-line Create Agent.
Unless I reload the Arduino Create Agent, I always get the 'No Plug-In Connection' error message, please see screen capture.  Device manager recognizes the Arduino Uno and assigns COM3 to the USB connection, please see screen capture.


texts: I have been trying to print the letter µ on the Serial Monitor of Arduino IDE but I failed to do so. Is there any way to print µ or any other Non ASCII characters such as Ó,ß,Ô,Ò,õ,Õ,þ, etc using Serial.print()?


texts: Programming Arduino with FTDI via Tx and Rx pins

texts:
How program Arduino with a FTDI cable/breakout_board via pins 0 (Rx) and 1 (Tx)?

In case the USB to UART chip (16U2 or other) is broken, you can program Arduino with a FTDI instead of 16U2 or other chip.

What are the connections to reset the Arduino microcontroller automatically when sketch is upload?


texts: Serial Monitor stops working when using PinMode

texts:
I'm having a lot of trouble with my recent Arduino sketch. I need to reset an IC by setting a pin high then low. I also am using the serial monitor for some testing but as soon as I try and do a Serial.print, nothing appears. My Arduino is also on a custom PCB, where D7 is connected to the IC's (MAX3421) reset pin, and also to the Arduino's reset pin.
To try and make my issue clearer, ill post some code and the serial monitor output below:
void setup()
{
  Serial.begin(9600);

  pinMode(7, OUTPUT);
}

void loop()
{
  Serial.println("TEST");
}

[nothing in serial monitor]

void setup()
{
  Serial.begin(9600);

  //pinMode(7, OUTPUT);
}

void loop()
{
  Serial.println("TEST");
}

[lots of TESTs]
Any help is appreciated,
Thomas


texts:
Board: Arduino Leonardo

IDE version: 1.6.5(also tried with 1.8.3)

Try Arduino Web Editor as well

The problem: after connecting Arduino to PC via USB in 5-7 seconds IDE says that connection is losted.

Everything was OK, but after one deploy happened thing, that I described.

If it help: I connect OLED display and use it with OLED_I2C library. Sketch contains one cpp and one h file.

I'm already fully reinstall USB drivers with Arduino USB as well


texts: How to write http response from HttpClient to Serial monitor with a ESP32 (Wemos Lolin32)?

texts:
With my ESP32 Board, Wemos Lolin32, I would like to make a http GET request to "http://www.arduino.cc/asciilogo.txt", read the text file and print the text file to the serial monitor.

The question is: Why isn't basically the txt file written to the serial monitor? How can it be achieved? Do I need some kind of conversion of the char?

I am using similar code to that from this example https://www.arduino.cc/en/Tutorial/HttpClient.
Basically the code can be reduced to this minimal example:

#include <WiFi.h>
#include <HttpClient.h>

void setup() {

  Serial.begin(9600);

  WiFi.begin(ssid, password);
  Serial.println("Connecting to WiFi..");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println(".");
  }
  Serial.println("Connected to the WiFi network");

  pinMode(LED_BUILTIN, OUTPUT);
  Serial.println("SETUP FINISHED");
}

void loop() {
  Serial.println("Connecting to httpClient");

 HttpClient httpClient;
  httpClient.get("http://arduino.cc/asciilogo.txt");
  while (httpClient.available()) {
    char c = httpClient.read();
    //Serial.print(c);
    Serial.write(c);
  }
}

The expected result is: I would like to see the characters from the txt file (https://www.arduino.cc/asciilogo.txt) in the serial monitor.

The actual result is: The connection to the WiFi can be established. In the serial monitor either question marks or strange symbols are displayed.

I have checked the baud and it is the same in the code and in the monitor. I tried to change this value, but it did not help.


texts: Detecting the presence of a specific smartphone

texts:
I would like you to give me some clues about a projet I have: I want to make sure that my little brother's smartphone stays in a shelf overnight and during school hours in order to monitor the time he spends with it.

In order to fulfill my needs, I thought of using an Arduino to detect that the smartphone stays in proximity at certain hours.

Since this is my first Arduino project, I'm not quite sure what I could do, and what is possible to do.

Hence I've got a lot of questions:

Can I easily detect that a specific smartphone is in range?
Can I use the smartphone's NFC (RFID) to do so?
What kind of output could I possibly get from an Arduino? I would like to make statistics, so it must be stored somewhere, and I know Arduino doesn't have a lot of memory.
Is it possible to write on a USB key?
Which Arduino is best suited for my needs Should I consider buying an Arduino with Ethernet in order to send emails?

Thanks a lot!


texts: More missed messages with longer cables with nRF24L01+?

texts:
I am using nRF24L01+ 2.4 GHz transceiver.

When I connect them directly (with SPI pins 10..13 from Arduino) to the adapter board for the nRF24L01 I get occasionally errors (meaning the receiver does not get the sent message).

However, I want to use one nRF24L01 purely for transmitting, and one for receiving. So each Arduino will have 2 nRFs, one for receiving, one for transmitting.

Since they both use SPI, I need to take the pins 10..13 to a breadboard and forward them from there to both nRFs. However, I did a test with only the transmitter, and found out I get more errors than direct wiring.

The only difference is that I now use extra jumper wires (4" / 10 cm). Can the extra cable length cause problems?
Would it help if I use less long M/F dupont cables? (so the total length still is 8"/20cm)? ... I don't have such short ones, so I cannot try.

I use for the breadboard to the nRFs 8"/20cm M/F dupont cables.

See picture below. The white/grey/red/blue 20cm/8" dupont cable directly wired to pins 10..13 Arduino gives less errors than the situation on the photo where the white/orange/red/blue 4"/10cm cables are added.


texts: How to generate musical notes using an uno without using tone() function? Can anyone share the embedded c language code for it?

texts: I also want to know how can we make it without functions like digitalwrite


texts: Possibility to program the ATmega32u4 on the Arduino Yun using a configuration file

texts:
Is it possible to send a Configuration File viz. conf.json that can be sent to the Arduino Yun via Ethernet and a Python Program can parse the configuration and set for example Sampling Rate of a Sensor which is connected to the 32u4?

The problem for me is that Sampling Rate in the Arduino Sketch is actually a preprocessor directive and I understand that C++/Arduino Sketches need to be compiled once before the changes take place.

However, how can I change the preprocessor directive in the sketch using a configuration file?

e.g.

#define SAMPLE_RATE (100)

in a conf.json file somewhere there might be:

{"sample_rate": 1000}

Once the .json file is parsed using python is it possible to change

#define SAMPLE_RATE (100) // to #define SAMPLE_RATE (1000)


texts:
I have a prototype using RedBear Lab's Blend micro platform (http://redbearlab.com/blendmicro/). I am able to discover the BLE chip on my iPhone and connect / control the unit. However, the device is constantly advertising - how do I enable advertising only on user request.

For example, if I use my bluetooth headphone, it pairs only when I press a button to enable pairing. Can I do the same with this BLE chip?


texts: How do I see the command line equivalent of clicking Verify?

texts:
I am using the ESP8266 board manager. I want to see how Arduino IDE compiles my code once I click Verify.

Why do I want to do this?

I am trying to integrate a C library for which there is now Arduino library package available. So I have to integrate it from source. I want to be able to specify custom -I, -L  and -l flags when I compile my code.


texts: Can Arduino Leonardo use USB port and RX TX serial pins at the same time?

texts: Can I use the TX/RX on pins 0, 1 (to a serial slave device) while also having the USB port dedicated PC communication?


texts:
I'm currently working on HC-12 transceivers. Normal operations are fine and I was able to successfully transmit basic strings between an Arduino UNO and and Arduino Nano, both of which use HC-12s.
However, when I'm trying to configure the HC-12s using AT commands, the commands that I send through the serial monitor, like the basic "AT" or "AT+VERSION" return no response.
Here's my wiring setup

HC-12 VCC to Arduino 5V
HC-12 GND to Arduino GND
HC-12 RXD to Arduino D11
HC-12 TXD to Arduino D10
HC-12 SET to Arduino GND

And here's my arduino code fore sending AT commands
#include <SoftwareSerial.h>

#define RX 11 //Connect to the TX pin of the HC-12
#define TX 10 //Connect to the RX pin of the HC-12

SoftwareSerial mySerial(RX, TX);

void setup() {
  Serial.begin(9600);
  mySerial.begin(9600);

  while(!Serial);

  Serial.println("Input AT commands");
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

Things I've already tried include switching to different baud rates from 300 to 9600. I've also tried the HC-12 GUI configuration tool, but that one returns an error "Serial I/O error: CreateFile failed"
Is there any way to find out if this is a problem of the HC-12 itself, or just a configuration issue?


texts: How does this code line detect if a serial interface is connected?

texts:
I am working with some code for remote temperature sensor nodes. They turn the debug interface on and off depending on if anything is conneced to the serial port or not.

The code is on Github here. Line 111 is the line of interest:

if (Serial) debug = 1; else debug=0; //if serial UART to USB is connected show debug O/P.

So, a simple question: On a hardware and software level, how does this work? I can't see anything in HardwareSerial or Stream that would return true/false if anything was connected or not.

Note that I am not confident that it actually works. This simple test indicates it doesn't work as the LED flashes regardless of the presence of a serial adapter or connection:

boolean debug;

const int toggle = 6;

void setup()
{
  if (Serial) debug = 1; else debug = 0;

  pinMode(toggle, OUTPUT);
  digitalWrite(toggle, LOW);

  if (debug)
  {
    Serial.begin(9600);
    Serial.println("Setup");
    digitalWrite(toggle, HIGH);
    delay(1000);
    digitalWrite(toggle, LOW);
  }
}

void loop()
{
  if (debug)
  {
    Serial.println("Loop");
    digitalWrite(toggle, HIGH);
    delay(1000);
    digitalWrite(toggle, LOW);
    delay(1000);
  }
}


texts: NFC PN532 SPI - Error: Timeout when waiting for ACK

texts:
I've been struggling to get the PN532 module working over SPI with an Arduino Uno.
I have the wires connected as follows:

SCK   -> 13
MISO  -> 12
MOSI  -> 11
SS    -> 10
VCC   -> 5V
GND   -> GND

And the board mode set for SPI as follows:

When I run the code below I get this output:

-------Peer to Peer HCE--------
write:  02
Time out when waiting for ACK
Didn't find PN53x board

Code:

#include <SPI.h>
#include <PN532_SPI.h>
#include "PN532.h"

PN532_SPI pn532spi(SPI, 10);
PN532 nfc(pn532spi);

void setup() {
    Serial.begin(115200);
    Serial.println("-------Peer to Peer HCE--------");

    nfc.begin();

    uint32_t versiondata = nfc.getFirmwareVersion();
    if (! versiondata) {
      Serial.print("Didn't find PN53x board");
      while (1); // halt
    }

    // Got ok data, print it out!
    Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
    Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
    Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

    // configure board to read RFID tags
    nfc.SAMConfig();
}

void loop()
{
    // Truncated
}

I've been trying to edit the source files and find the problem but I cannot seem to find whats causing it. Some help is much appreciated :)


texts: 20x4 LCD will write but then won't update

texts:
I am controlling a solar tracker, and it needs to be reset every 10 minutes or it loses its mind.  My program works fine, controlling power relays, so I have added I2C&Power to be able to see the status remotely.  For now it is set up on the workbench with fairly short cables.  I also have a RTC and the i2cscanner finds them all..

LCD init code is pretty basic:

// 20 x 4  LCD Display
#include LiquidCrystal_I2C.h
// set the LCD address to 0x3F for a 20 chars 4 line display\/ Set the pins on the I2C chip used for LCD connections:
//                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

then

lcd.begin(20,4);
lcd.clear();
lcd.setCursor(2,0);
lcd.print("PV Control 3.9");

My LCD (20x4) works fine at first, writing the top line with the name of the program, then the bottom line with a temperature reading, then every 10 minutes I need the second line to show when the power is off for 10 seconds.  It shows "power off" just fine, but after the delay(10000) it is supposed to overwrite that line with  "power on" but nothing changes...

Serial.println("POWER OFF");
lcd.setCursor(4,1);
lcd.print("-Power Off- ");
digitalWrite(power1,HIGH);  // DC HOUSE power off
digitalWrite(power2,HIGH);  // DC HOUSE power off
delay(10000);
Serial.println("POWER ON");
lcd.setCursor(4,1);
lcd.print("-Power On-  ");
digitalWrite(power1,LOW);  // DC HOUSE power on
digitalWrite(power2,LOW);  // DC HOUSE power on

The problem is that it continues to say "power off" and doesn't overwrite it.

I can see from the Serial Monitor that the program is running fine, but the LCD doesn't change after the first set of lcd.prints at those character positions.

I haven't heard of anybody having this problem, but perhaps someone out there know about this.   Any suggestions would be very welcome.

Question is:  How can I make the LCD update lines that have been originally written?

UPDATE:  Problem solved by simply clearing and rewriting the display when things change.  I can't debug libraries but at least it is working now.


texts: I need to change this code to start the section of code when the switch is on and not when the switch is released

texts:
I have this section of code. It works fine and how I want it only, it executes when the button is released not when it is pressed. My application needs to execute this code when a switch is on. The issue is that it the vairable "fsrOnMillis" is updated constantly when the button is high. I have tried a few things but can't figure out the best way to get this to function how I want.

Hardware description:
Switch when turned on will provide 5V. When off 0V.
2 Led's one green and one red.

What I want to happen is when the switch is on the green led lights up and turns off. Then after a time 60,000 ms the red LED will light up to say that the process is complete.

What is happening is that when the switch is turned on nothing happens but when it is turned off the code executes. I want the process to execute once the switch is turned on.

if (digitalRead(BUTTON) == HIGH) {
  // update the time when button was pushed

  fsrOnMillis = currentMillis;
  greenReady = true;
  redReady = true;
 }

 // make sure this code isn't checked until after button has been let go
 if (greenReady) {
   //this is typical millis code here:
   if ((unsigned long)(currentMillis - fsrOnMillis) >= greenOnDelay ) {
     // okay, enough time has passed since the button was let go.
     analogWrite(greenLedPin, 153);
     // setup our next "state"
     greenState = true;
     // save when the greenLedPin turned on
     greenTurnedOnAt = currentMillis;
     // wait for next button press
     greenReady = false;
   }
 }

 // see if we are watching for the time to turn off greenLedPin
 if (greenState) {
   // okay, led on, check for now long
   if ((unsigned long)(currentMillis - greenTurnedOnAt) >= greenOffDelay) {
     greenState = false;
     analogWrite(greenLedPin, 0);
   }
 }

 if (redReady) {
   //this is typical millis code here:
   if ((unsigned long)(currentMillis - fsrOnMillis) >= redOnDelay) {
     // okay, enough time has passed since the button was let go.
     analogWrite(redLedPin, 153);
     // setup our next "state"
     redState = true;
     // save when the greenLedPin turned on
     redTurnedOnAt = currentMillis;
     // wait for next button press
     redReady = false;
   }
 }

 // see if we are watching for the time to turn off greenLedPin
 if (redState) {
   // okay, led on, check for now long
   if ((unsigned long)(currentMillis - redTurnedOnAt) >= redOffDelay) {
     redState = false;
     analogWrite(redLedPin, 0);
   }
 }

Any help is much appreciated.


texts:
I want to connect an arduino uno both to a TGAM module: http://www.seeedstudio.com/document/pdf/TGAM%20Datasheet.pdf
and a bluetooth shield. The arduino is to receive data from the TGAM module and sent it to an android device. The problem is I should connect the bluetooth and the TGAM to the same pins on the arduino. Is that a problem (I am still a novice, doing my research)? If it is a problem what is the work around?

Arduino <> TGAM

Arduino RX (0) <> TGAM T (TX)

Arduino TX (1) <> TGAM R (RX)

Arduino 3.3V <> TGAM + (VCC)

Arduino GND <> TGAM - (GND)

Arduino <> HC-06

3.3v    <> VCC

GND     <> GND

TXD     <> RXD

RXD     <> TXD


texts:
I have a Arduino Mega with Wiznet 5100 Ethernet shield. Am trying to post some data onto localhost for started later on which will be accepted by a website.
But when I try to post the data I get some error. When I try to send the same data via postman it gets accepted . But when it goes from arduino error occurs.
The arduino Code is as follows:

client.println("POST /api/trackers/5a28eddaf57a6e2060e85601/solars/5a3bb2adf57a6e1a71ca135b/arduino_data HTTP/1.0");

client.println("Host: 192.168.6.16");

client.println("Accept: application/vnd.mirasol.v1");
Serial.println("After Accept application vnd");

client.println("User-Agent: Arduino/1.0");
Serial.println("After User Agent Arduino");

client.println("Accept: application/json");
Serial.println("After Accept application json");

client.println("Content-Length: ");
Serial.println("After content length");

client.println(postdata.length());

client.println("Content-Type: application/json");
Serial.println("After content type application json");

client.println("Connection: close");
Serial.println("After connection close");

client.println();
Serial.println("After client println");

client.println(postdata);
Serial.println("After post data");
Serial.println(postdata);

The output in the serial monitor is as follows:

    connecting...
connected
After Accept application vnd
After User Agent Arduino
After Accept application json
After content length
After content type application json
After connection close
After client println
After post data
{"current":10.50, "voltage":10.50}
H
disconnecting.

And the error shown in localhost is as follows:

2017-12-27 15:21:57 +0530: HTTP parse error, malformed request (): #<Puma::HttpParserError: Invalid HTTP format, parsing fails.>

I have the application in Ruby on Rails with Mongoid as the DB.

FYI: New to coding..


texts:
I've an Arduino Mega 2560 R3 and recently bought a Wifi Shield CC3000 from ebay http://www.ebay.de/itm/201405512301
They write that the firmware has the version ServicePack 1.11.1.
The WiFi shield is connected to the Arduino and green status light is on.

I try to run this example code:

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
}

// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
  Serial.println("WiFi shield not present");
    // don't continue:
  while(true);
}
...

It seems that Wifi.status() always returns WL_NO_SHIELD.
What can I do?

Thanks for help.


texts: Can Arduino UNO permanently store a code?

texts:
I'm really new to Arduino and wanted to know if I can make Arduino a permanent controller?
and could you help me with a cheaper alternative?
I also wanted to know about "fuse", i read it somewhere that i can protect the code from someone else who wishes to use, using a FUSE.
Thanks a lot for helping me out:)


texts: Arduino Uno: external power supply +5V and serial communication with pc over USB

texts:
I have connected to my Arduino Uno outputs relay module. Relay module has 16 relays (5VDC) which are controlled by transoptors pins (HIGH from Arduino = specific relay is off).

Link to relay module (lang: polish): https://botland.com.pl/pl/przekazniki/6940-modul-przekaznikow-16-kanalow-z-optoizolacja-styki-7a240vac-cewka-5v.html?search_query=modul+przekazniko&results=75 (SRD-05VDC-SL-C relays).

Arduino is supplied by +5V pin and GND pins with external power supply MDR-5-10. Relay module is supplied with the same power supply.

I control Arduino from PC using serial communication over USB (I send a command eg. 1;1;1;1;1;1;, then 6 outputs goes to HIGH). And now there is a problem. When I disconnect relay module control pins from Arduino outputs everything works fine. But when it is connected, I get serial com. error "device not found" (after some switches: sometimes it works for about 20 output switches, sometimes for 1 output switch) and I have to open serial communication again. Probably error appears only when I'm switching outputs.

I think the problem is because my external power supply +5V drops for a while when switching and then Arduino switches to +5V from USB (which doesn't drop), which has not enough power and then error occurs.

Am I right? Any suggestions to fix the problem?

EDIT #1:
Thank you for help. Answers:

@Jot, after disconnecting +5V Arduino pin, but with connected relay module, I get serial error immediately with first relay switch. If i dosconnect both +5V pin and relay module control pin, my application works fine.
My wires: external power supply - Arduino: 0,5 mm2; Arduino - relay module control pins: 23 AWG (~0,25 mm2); external power supply - relay module +5V and GND: 1,5 mm2. It flows through relays: 24VDC <30W or 230VAC ~20mA.

@CrossRoads, no I use A0-A4 and Q3-Q12 (for relay module: Q3-Q7, Q9-Q11, Q13).

@Duncan C: Currently, I use only 9 relays, other control pins are disconnected and off. Here - http://botland.com.pl/index.php?controller=attachment&id_attachment=244 (power consumption per relay - 0,36W 5VDC) - you can see relay datasheet. Relays are isolated from Arduino with opto-isolators (signal HIGH from Arduino = relay is off).
I never switch them all at once. In specific function I never use more then 5 relays together.

@Majenko, thank you, I'll give it a try in Tuesday!

Further informations:

Probably problems occur more often when I connect wires to relays pins (I use them all as NO: 7x 30W 24VDC - coils, 2x 230VAC ~20mA - contactor).
Serial communication error can occur during both reading or writing to serial.


texts:
I try to control a Stepper motor with an arduino and a L298. I use the library stepper.h and it works well but i have a problem : the L298 become very hot. So i want to disable the break (the thing that we can't turn the motor by hand), but i don't know how to do this.
Do you have an idea ?
My code is simple :

#include <Stepper.h>

const int stepsPerRevolution = 200;  // change this to fit the number of steps per revolution
// for your motor

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

void setup() {
  // set the speed at 60 rpm:
  myStepper.setSpeed(60);
  // initialize the serial port:
  Serial.begin(9600);
}

void loop() {
  // step one revolution  in one direction:
  Serial.println("clockwise");
  myStepper.step(stepsPerRevolution);
  delay(500);

  // step one revolution in the other direction:
  Serial.println("counterclockwise");
  myStepper.step(-stepsPerRevolution);
  delay(500);
}

I took it from here : https://coeleveld.com/arduino-stepper-l298n/

Thanks !


texts:
On Arduino Uno Wifi rev2 I want to create an SSL socket to my own SSL socket server implementation.

The board can download a webpage with encryption (after I've installed the certificate into it of course).

For my own SSL socket server implementation I'm using OpenSSL.

The board can connect to my own SSL socket server without any issues.

I want to enable SSL_VERIFY_PEER in my socket server.

With this option I can verify if peer is valid and true.

However after enabling this option, the Arduino is not able to connect to my socket anymore.

My question: is peer certificate sending can be achieved on Ublox NINA W10x?


texts: Dimming 6W (24V DC 0.25A) LEDs using Arduino

texts:
I want to dim 24 LEDs which are powered by a transformer outputting 24V 6W at 0.25A

I am worried about temperatures, especially considering the circuit has to stay on for several hours keeping the LEDs off.

Would a TIP122 transistor be ok?

Any tips for keeping the transistor off until the dimming process starts?


texts:
I am trying to send a simple GET/POST request to a dummy end point on https://requestbin.com/. I am using an ESP8266 module. I am using the arduino serial monitor to send these AT commands. I connect to wifi and then use the following AT commands
AT+CIPSTART="TCP","54.166.71.140 ",443  (the IP address from requestbin)

I then do
AT+CIPSEND=80

followed by
GET / HTTP/1.0\r\nHost: fc35001f8ec49962d182320446070d.m.pipedream.net\r\n\r\n

I get the output as follows
Recv 80 bytes

SEND OK

+IPD,272:HTTP/1.1 400 Bad Request
Server: awselb/2.0
Date: Mon, 07 Dec 2020 13:28:01 GMT
Content-Type: text/html
Content-Length: 122
Connection: close

<title>400 Bad Request</title>

400 Bad Request

CLOSED

Is there problem with the length of CIPSEND or the format of the request itself.


texts:
I've search on how to do statistic calculation in EEPROM, but non related.
The data that I stored in EEPROM is body temperature.
Currently I stored the data using float.

Below is my code for data store in eeprom.
I'm stuck at the void function named "printTemp". I know how to calculate average in array using for loop statement, but not EEPROM. From average/mean, I can find standard deviation.

Does anyone have an idea on how can we do calculation using data from EEPROM?

#define LM35 A1
#define READSAMPLES 100

float bt;
int buttonPin1 = D5;     // the number of the pushbutton pin 1 MEASURE
int buttonPin2 = D6;     // the number of the pushbutton pin 2 RESET CYCLE
int buttonState = 0;         // variable for reading the pushbutton status
int ButtonState = 0;         // variable for reading the pushbutton status
int address = 0;      //EEPROM address counter
int count, counT;
int sample[READSAMPLES];

void setup() {

    int contCount = EEPROM.get(5, count) / 10;

}

void loop() {

  buttonState = digitalRead(buttonPin1);
  ButtonState = digitalRead(buttonPin2);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW) {
        Serial.println("Measuring your Body Temperature:");

        count = counting();
        counT = count / 10;
        Serial.print("Data count entering: ");
        Serial.println(counT);

        writeTemp();
  }

  if (ButtonState == LOW) {

        Serial.println("Update New Cycle of body temp...");
        printTemp();
        clearEEPROM();
        Particle.publish("DONE new Cycle");

  }

}

void printTemp()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    float cel = EEPROM.read(i);                //read EEPROM data at address i
    //How to find MEAN of all data?
  }
}

void clearEEPROM()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    if(EEPROM.read(i) != 0)                     //skip already "empty" addresses
    {
      EEPROM.write(i, 0);                       //write 0 to address i
    }
  }
  Serial.println("EEPROM erased");
  address = 0;                                  //reset address counter
}

void writeTemp()
{
  //getting the voltage reading from the temperature sensor
  int j;
  float average;
  for (j = 0; j < READSAMPLES; j++)
  {
    sample[j] = analogRead(LM35);        //read sensor value
    delay(50);
  }

  average = 0;
  for (j = 0; j < READSAMPLES; j++)
  {
    average += sample[j];
  }
  average /= READSAMPLES;

  //float mv = ( average / 4096.0) * 3300;
  //float cel = ( mv / 10 ) - 55.01;
  float mv = ( average / 1024.0) * 5000;
  float cel = ( mv / 10 );

  EEPROM.write(address, cel);         //write value to current address counter address

  Serial.print("Sensor value stored at address ");
  Serial.println(address);

  address++;                      //increment address counter
  if(address == EEPROM.length())  //check if address counter has reached the end of EEPROM
  {
    address = 0;              //if yes: reset address counter
  }
}

float counting()
{
  count = count + 10;   // plus 10 is because to give a space for data entering the eeprom for LATER CODE. Just live it here.
    Particle.publish("Start Count =", String(count));
  return count;
}

What I can share from my problem findings are, to do the calculation of statistic from EEPROM data;

we need to know how to read back all the data in EEPROM. As in my code I know how to read the data, but the data cannot be hold because in FOR loop the the process will running until the end of 'i'.
we need to know how many data are there in EEPROM that have entered. To solve this, I'm using count; in order to count the entering data.

I need suggestion links or maybe any idea on how to do statistics in EEPROM.

Thanks.


texts:
New Arduino Uno, Arduino 1.6.3, MBP running 10.10.5.

The Arduino IDE is running, I connect to the laptop via usb. The green LED is on the amber light is on but it's not blinking.

I attempted to upload the blink file from File>Example>Basic>Blink. It compiles without issue but won't upload. I get the can't open device "/dev/cu.usbmodem1421" : No such file or directory...

I have attempted using the reset button, changing ports, cycling the IDE and the computer. The killer is that I've had an Arduino on this laptop before.

Any suggests for getting the Arduino linked and operational.


texts: How can I use both ultrasonic and IR sensor and ultrasonic sensor at ones with Arduino

texts: I  want to use both the ultrasonic sensor and IR sensor with Arduino + motors for a car project. Will I have to do any kind of multithreading on Arduino, or is it something else


texts:
I have corrected my code for reading the optical encoder index but I am now getting a different calculation error.  At the index the encoder reset's to zero but now my readouts are as follows:
Index point - resets to zero.
- At the 90 degree rotation mark I have a readout of 180 degrees.
- At the 180 degree rotation mark I have a readout of 0 because the code has it reset to zero after 359 degrees.
- At the 270 degree rotation mark I have a readout of 180 degrees.
- At the 0 degree mark it is zero again and that's what I would expect from the index.  If I restart the Arduino Mega at the 270 degree mark, the index resets itself to zero like it should.  Being new to this, before I had the index working it was working correctly minus the index function, now it seems to be double counting.  Any ideas?

// Wiring connections for my encoder:
// Brown : VCC = 5V
// Blue + Shield : 0V = GND
// Black : ENCODER0PINA, Pin 20
// White : ENCODER0PINB, Pin 17
// Orange : ENCODER0PINI, Pin 19

#define ENCODER0PINA         20      // this pin needs to support interrupts
#define ENCODER0PINB         17      // no interrupt required
#define ENCODER0PINI         19      // this pin needs to support interrupts

// variables modified by interrupt handler must be declared as volatile
volatile long encoder0Position = 0;
volatile long interruptsReceived = 0;
volatile byte INTFLAG1 = 0;

// track last position so we know whether it's worth printing new output
long previousPosition = 0;

void setup()
{

  // inputs
  pinMode(ENCODER0PINA, INPUT);
  digitalWrite(ENCODER0PINA, HIGH);  // turn on pullup resistor
  pinMode(ENCODER0PINB, INPUT);
  digitalWrite(ENCODER0PINB, HIGH);  // turn on pullup resistor
  pinMode(ENCODER0PINI, INPUT);
  digitalWrite(ENCODER0PINI, HIGH);  // turn on pullup resistor

  // interrupts
  attachInterrupt(3, onInterrupt, CHANGE);  // encoder track A on interrupt 3 - pin 20
  attachInterrupt(4, onReset, CHANGE);  // encoder Index track on interrupt 4 - pin 19

  // enable diagnostic output
  Serial.begin (115200);
  Serial.println("Ready.");
}

void loop()
{
  // only display position info if has changed
  if (encoder0Position != previousPosition )
  {
    Serial.println(encoder0Position, DEC);

    previousPosition = encoder0Position;
  }
}

// interrupt function needs to do as little as possible

void onReset()
{
  // read Index input
  int i = digitalRead(ENCODER0PINI);
  if (i == 1)
  {
  encoder0Position = INTFLAG1;
  }
}

void onInterrupt()
{
  // read both directional inputs
  int a = digitalRead(ENCODER0PINA);
  int b = digitalRead(ENCODER0PINB);

  if (a == b)
  {
    // b is leading a (counter-clockwise)
    encoder0Position--;
    if (encoder0Position < 0)
    {
      encoder0Position = (encoder0Position + 360);
    }
  }
  else
  {
    // a is leading b (clockwise)
    encoder0Position++;
    if (encoder0Position >= 360)
    {
      encoder0Position = (encoder0Position - 360);
    }
  }
}


texts:
I'm developing a wearable data logging device. Sensors are sampled at 20Hz, and written to a SD card through a buffer. There is an Android app that could query the status of data collection (size of written files, latest timestamp etc) through bluetooth LE.

// timer interrupt 20Hz
// reading sensors to buffer
ISR() {
    int a = analogRead(A0);
    buffer.push(a);
}

void loop(){
    if buffer.isFull() {
        myFile.open("data.csv", FILE_WRITE);
        myfile.print(buffer.getData());
        myFile.close();
    }
}

// possibility of blocking data collection process
RFduinoBLE_onConnect() {
    int freeSpace = SD.vwd()->fileSize();
    // other operations for monitoring data collection process
    RFduinoBLE.sendInt(freeSpace);
}

I am worried that long operations inside RFduino callback function might block the data collection process. (freeSpace is an example, I am planning for other useful data for monitoring process). Also, one could repeatedly try to connect to get updated status data.

What is the recommended technique to make sure that data collection process will not be affected?

UPDATE:

The actual usage is that RFduinoBLE_onConnect will be called every hour or on demand only. On the other hand, I am trying to deal with worst case of someone trying to call onConnect repeatedly. Is there any way to see that if data collection is busy then reject the RFduinoBLE_onConnect requests?


texts: How to detect the absence of an RFID tag?

texts:
I have installed an MFRC522 RFID reader in my house. The main use so far is to tell the house I've arrived using an RFID keychain, by leaving it in the key holder.

I would also like for the house to detect when I'm gone, and I was thinking that, if I can detect when a tag is present, I should also be able to detect when it is not.
However, this poses some challenges like the following:

Should I be constantly reading the tag until it disappears from range? (when I take it from the key holder).
What if I have more than one RFID Keychain/Tag in the range of the reader? (because there could be other keychains in the same key holder). Would I get multiple readings or could one tag interfere with another in some way?

I realize that maybe this is not the typical RFID scenario when the tag is scanned and then moved away from the reader. I've been searching about "RFID tag absence detection" but I've only found what seemed to me like very theoretical papers.

Do you have any advice or experience in implementing something like this?

Thanks!


texts: Do You Put a Break after the Last case in a Switch?

texts:
The Arduino Switch Case Reference has a switch structure written two different ways:

First in the Syntax as:

switch (var) {
  case label1:
    // statements
    break;
  case label2:
    // statements
    break;
  default:
    // statements
}

and then in the Example code as:

  switch (var) {
    case 1:
      //do something when var equals 1
      break;
    case 2:
      //do something when var equals 2
      break;
    default:
      // if nothing else matches, do the default
      // default is optional
      break;
  }

Is there any reason to (or not to) add a break; in the default: case? Does the need for 'break;' change if the final case is not default:?


texts: SAMD21 Programming with Atmel ICE Fail to Write

texts:
I am trying to program my Adafruit M0 with the SAMD21G18 chip with Atmel studio and the Atmel ICE programmer. I have pin 1 on the ICE connected to 3.3V on the M0, pin 2 connected to SWDIO, pin 4 to SWDCLK, pin 10 to Reset, and pins 3, 5, and 9 to ground. This was all according to the ARM SWD connection section of the Atmel ICE manual. In Atmel Studio, I can read the device signature, but when I go to program the chip, I get the following error:

Timestamp:      2017-04-20 22:03:32.563
Severity:       ERROR
ComponentId:    20100
StatusCode:     131103
ModuleName:     TCF command: Modules:writeToMemory failed.

Failed to write segment at 0x0 to target for memorytype

I have searched the internet for hours, finding no solution to this problem.


texts:
I have a 24BYJ48 stepper motor, and my main problem is that I cannot make it rotate quickly. I've understood that in order to achieve a high speed I must start at a low speed and carefully accelerate the motor to higher speeds.

I'm not quite sure how this acceleration ought to be done, though. My idea is to execute the control sequences with an initially long delay, and then decrease the delay between each time I change the sequence for the motor wires.

Below is the code I have written. When I run it, the motor accelerates for a little while, but then all of a sudden it just stops and makes a high pitched noise.


texts: How to get current time and date in arduino without external source?

texts:
I'm working on a project using Arduino Uno and SD card shield.
I'd like to store a variable at a specific time everyday in the SD card. How can I get the current time in Arduino ?
Any help would be appreciable.

NOTE : Arduino is NOT connected to PC.


texts:
I have a potentiometer of 10k and I connected it this way:

5v -> potentiometer -> analog input pin of Arduino

When I turn the potentiometer I change the resistance of the circuit but in the Arduino documentation they say that an analog pin in INPUT mode will have 1 megaohm resistance. So, for example, if I turn the potentiometer to the middle it will generate 5k of resistance + 1 megaohm of the analog pin it will result in a tiny, very tiny current. If I use U = R x I across the potentiometer it will be:

U = 5000 x 0.0000001

U ~ 0 across the potentiometer. So U will be 5 V at the analog input because there was no drop of voltage in the circuit. If turn the potentiometer all way up to 10k resistance the voltage in the analog input will also be 5 V because the voltage drop across the potentiometer is still really small.

I know that an analog pin in INPUT mode will read 0 V as 0 and 5 V as 1023. But as I showed you it should always read 5 V even when I turn the potentiometer all way up because the voltage is not being changed. I know I am wrong cause when I log the input pin it shows different values as I turn the potentiometer. So how does this work?


texts:
I have a server with files that may be downloaded.

How do I go about detecting when a download is cancelled by a client?

The function that handles reading files for download:

void readFile()
{

EthernetClient client = server.available();

// Open file for Reading.
SdFile webFile;
webFile.open(&root, &MyBuffer[1], O_READ);
if (!webFile.isOpen()) error("readFile");

do   // @ adafruit_support_rick's do-while loop
{
    int count = 0;
    char buffers[BUFSIZE];
    bool done = false;

    while ((!done) && (count < BUFSIZE) && (webFile.available()))
    {
        char c = webFile.read();
        if (0 > c)
        done = true;
        else
        buffers[count++] = c;
        delayMicroseconds(1000);
    }

    if (count)
    client.write( buffers, count);

} while (webFile.available());

webFile.close();

fileDownload = 0;  //File download has finished; allow logging since download has completed

delay(500);

MyBuffer[0] = '\0';

}


texts:
So I think the title says it all. I recently purchased an ESP32 CAM in India for a pretty cheap price.

It looks like an AI Thinker but doesn’t have the tag on the chip itself. Nonetheless, to get it setup before my use case I decided to test the camera. I loaded up the CameraWebServer example and set my camera type to AI thinker.

The code uploads successfully and runs successfully. I can open up the IP address and it shows the page. However whenever I try to get a still or start a stream, it gives this error:

[E][camera.c:1344] esp_camera_fb_get(): Failed to get the frame on time!
Camera capture failed

It’s pretty annoying and this happens in both 5V power and 3V power. The camera does physically get a bit hot after loading the website. Oh yeah, I have an OV 2460 Camera attached to the ESP.

Any advice is appreciated. Thanks!


texts: Arduino serial read data conversion, getting garbage values

texts:
I am developing code on Arduino to read 9 bytes of data from other controller.

I am getting same arrya elements which is transmitted from controller, but when I convert the same it gives me garbage values, Please help.

Below is my code snippet:

int Test::ID_001(void) {
  int result = 1;
  int i = 0;
  char FWV_AB[84];
  digitalWrite(DIR485,HIGH);
  delay(100);
  delay(10);

  int res = proto485Write(RS485_ADDRESS, CMD_COMMAND_FW_AB, CMD_ACTION_FW_AB, 0x0000);      // Send msg to controller board

  Serial.print("msgsend: ");
  Serial.println(" ");
  Serial.println("Received message from controller is: ");

  int  bufferIn1[9] = { int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00), int(0x00) };
  digitalWrite(DIR485,LOW);
  delay(100);
  delay(10);

  delay(DELAY);
  if (Serial2.available()== 0) {Serial.print("Error01 "); result = 0;} // Error for response timeout
  while(Serial2.available() > 0)
   {
   bufferIn1[i] = Serial2.read();

   Serial.print(bufferIn1[i],DEC);     // PRINTS CORRECT VALUES HERE SAME AS SENT BY CONTROLLER
   Serial.print(" ");
   i++;
   if(i == 9){
   Serial.println("Controller board version is: ");
   for(int j=3;j<7;j++){
    Serial.print(int(bufferIn1[j]-48)); } // HERE I AM CONVERTING VALUES INTO READABLE FORM
   }
   }
  digitalWrite(DIR485, HIGH);
  delay(100);
 return result;
}

GETTING VALUES AS "9 49 51 48 48 48 50 48 54" while serial read takes place.
MY DATA is "48 48 48 50" i.e. START FROM 3rd POSITION TO 6th POSITION OF RECEIVED BYTE. IT SHOULD PRINT AS "0002" but it gives me "GQQQ" some times "s)))" and such garbage data instead of 0002 value. Kindly guide.

Thanks you


texts: What's the difference between setting a variable outside a function and setting a variable inside a function?

texts:
I'm programming C++ for arduino and today I have seen an example like this

void loop() {
    byte variable = 0; // << This variable is the question.
    //more stuff here
}

Is the same as this?:

byte variable = 0;

void loop() {
    //stuff here
}

If the answer is "no", my question is "why?".

Thanks for your time!


texts: Why does the serial monitor needs to be repeated a command?

texts:
I am experimenting with the serial monitor in an Arduino Uno. My project consists in a simple LED turning on and off at will with the commands "ON" and "OFF" respectively.

To achieve this, I use an HC-06 Bluetooth module, but because of the nature of the test I decided to disconnect it and 'debug' my project using the serial monitor as an equivalent.

The circuit has the following connection table:

LED +: Pin 12 on my Arduino.
LED -: GND on my Arduino.

...as you can see, I have tried to simplify as much as I can the circuit, as I wanted to make sure I didn't have wire problems.

Here's the code:

char command;
String string;
#define led 12

void LEDOn()
    {
          digitalWrite(led, HIGH);
    }

void LEDOff()
    {
      digitalWrite(led, LOW);
    }

void setup()
{
      Serial.begin(9600);
      pinMode(led, OUTPUT);
}

void loop()
{
     if (Serial.available() > 0)
           {string = "";}

     while(Serial.available() > 0)
    {
           command = ((byte)Serial.read());

           if(command == ':')
           {
                  break;
           }

           else
           {
                  string += command;
           }

           delay(1);
    }

    if(string == "LO")
    {
           LEDOn();
     }

   if(string == "LF")
    {
           LEDOff();
    }

The problem comes when I type the commands. Normally, an LED in the board will react (I think it's the RX one), but the LED in pin 12 will not react at all. After testing ten times with each command alternatively, I calculated the serial needs an average of 6 command repetitions in order to react. Exactly the same happens when the HC-06 is connected.

Is there a reason for this?


texts:
I am looking for a microcontroller that is small (like a attiny10) which is the smallest one I could find.
Requirements I need: analogRead on 1 pin, 7 pins for analogWrite to micro leds so in total 10 pins (ground, power, analogRead, analogWrite). It's circuitry has to be basic no adding extra things like a crystal oscillator etc.. This will allow me to send a certain code to the recieving pin and then the microcontroller decide which led to turn on.


texts: Zigbee Relay board communication with Arduino

texts:
I have bought this wireless ZigBee relay board.

I was wandering about an arduino sketch to get started, I have searched for 2 days now but with no results.

What I was thinking of is to have an Arduino with ZigBee module to send signal to another ZigBee device on top of the relay, to be able to open/close relay.

So, can anyone share a sample sketch for that board?


texts: Do ISRs have to be defined in top level Arduino program?

texts:
I'm currently attempting to implement some interrupts on an Arduino project. Looking through some of the examples, it appears that all the ISRs are defined in the top level Arduino program. I'm organizing my project by C++ classes and namespaces, so I'm curious, is it possible to reference an ISR that is not declared and defined in the top level Arduino program? Could I instead reference an ISR that is declared in a separate C++  namespace? This question has been spawned primarily for organizational purposes.

Otherwise, I could always just use a #include to import a file that defines the ISR such that they're imported to the top level.

Thanks!


texts: Is there an easy way to turn integer values to pixels?

texts:
I'm working with a black & white camera and it gives me integer values to represent the amount of light hitting the sensor. Very bright is 1023 and totally dark is 0. The values are printed through serial and everything works fine but now I want to recreate the image based on the values.

Does anyone know if there is a simple way of doing this? I'm assuming the process would consist of looking up the value and giving a specific colored pixel in return, but I have no idea how to do this.


texts: Writing "theremin" outputs to a MIDI file on an SD card

texts:
I am making a musical instrument (theremin simulator). I want there to be a "record" capability which stores the volume and note the user is playing, into a MIDI file. Note this doesn't actually record audio, just data for the frequency and volume at a certain point in time.

So far I've done some research and have found how to play MIDI files (which is useful and I plan to take this on as well) and read/write to SD cards. However I haven't found a source which allows me to create and produce MIDI files.

How should I accomplish this feature?

Specs:

I am using an Arduino Nano, I have an Uno too if needed
The SD card is a 64GB micro SD, inserted into an SD adapter, with header pins soldered onto it. (I am too cheap to buy an actual shield)
It was previously XCSD, I formatted it to FAT32 to be compatible with Arduino

Also: I am recording from a self built replica of a theremin, which is basically two ultrasonic sensor readings for volume and pitch. Is this "too basic" for a MIDI file type? (Edit: I guess this is too advanced)

EDIT: This project has been abandoned because of no good way to play between semitones (i.e. at specific frequencies), which is what I need for my theremin. Although there is the pitch bend functionality, the amount of pitch bend translates to different frequency changes based on the receiver.

Instead, I will create my own custom file to achieve the record/playback, because using the pitch bend + note method using MIDI is just too much work and it won't be compatible with other devices anyway.

Nick Gammon's answer is really thorough for those who only need to record/play specific tones and semitones in MIDI format.

Thanks


texts:
I recently got a Adafruit TFT screen and an ESP-32 development kit. I was trying to interface these two the pin connections I used areas follows:

TFT   |   ESP-32
------+----------
3V3   |   Vcc
Gnd   |   Gnd
MOSI  |   GPIO19
SCK   |   GPIO18
CS    |   GPIO5
D/C   |   GPIO16
RST   |   GPIO 17

I used this library: https://github.com/MartyMacGyver/ESP32_Adafruit_ILI9341

The SPI library used was the one that comes while installing Arduino support for ESP-32.

The code compiles and uploads without any error/ warning but the TFT screen does not show any response (except powering up).

This is the code I used for testing:

//#include <Adafruit_ST7735.h>

#include<Adafruit_ILI9341.h>
#include <Adafruit_GFX.h>
#include "SPI.h"

#define TFT_CS     5
#define TFT_RST    17
#define TFT_DC     16

// Use hardware SPI (on Uno, #13, #12, #11) and the above for CS/DC
//Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
// If using the breakout, change pins as desired
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS ,TFT_DC, 23, 18, TFT_RST);

void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);
    Serial.println("In the setup.");
    //tft.initR(INITR_BLACKTAB);
    unsigned long t=micros();
    tft.fillScreen(ILI9341_RED);
    Serial.println(micros()-t);
}

void loop() {
    // put your main code here, to run repeatedly:

}

The code compiles and uploads without any error/warning but the TFT screen does not show any response (except powering up).

NOTE: The library works fine with Arduino Mega and TFT display.


texts: Custom Bootloader on Atmega328p - PU - 28 pin DIP

texts:
I am experimenting with low-power wireless arduino modules. For that, I needed 3V powered arduino so that I can do away with voltage regulators which eat up a lot of battery juice.

I am using 28 pin Atmega328p-PU dip IC with 8 MHz external crystal oscillator. Just for trying, I dumped the arduino pro mini 3.3V 8 MHz bootloader into it and it was a success. Everything is working as expected. However, I realized that SMD package which is being used in pro mini has 8 ADC pins compared to 6 in the DIP version.

Should I be worried about it?

Second feasible option is modifying the Arduino UNO board definition to use 8 MHz clock source as compared to 16 MHz and leave everything else same. Do you think this will serve my purpose?


texts:
I am using a Python3 GUI on my RPi3 to control my DFRobot Bluno Mega 2560 via USB.  The Mega is hooked up to a breadboard with 4 LED's and I am trying to control each LED with their own toggle switch.  I was able to do this with one LED but for some reason when I try to achieve the same with more than one it doesn't work, I get absolutely no response from the LED's whatsoever.  It is something to do with how the arduino is receiving the ASCII code, or I think it may be a problem with how I am implementing tkinter as I have little experience with it.  If anyone can tell me what I am doing wrong please let me know.

Here is the Python3 GUI code:

import serial # import the serial library
import time # import the time library
from tkinter import * #import Tkinter GUI library

def toggleRed():
    if redBtn.config('relief')[-1] == 'sunken':
        redBtn.config(relief="raised")
        arduino.write('a'.encode())
    else:
        redBtn.config(relief="sunken")
        arduino.write('b'.encode())

def toggleGreen():
    if greenBtn.config('relief')[-1] == 'sunken':
        greenBtn.config(relief="raised")
        arduino.write('c'.encode())
    else:
        greenBtn.config(relief="sunken")
        arduino.write('d'.encode())

def toggleBlue():
    if blueBtn.config('relief')[-1] == 'sunken':
        blueBtn.config(relief="raised")
        arduino.write('e'.encode())
    else:
        blueBtn.config(relief="sunken")
        arduino.write('f'.encode())

def toggleYellow():
    if yellowBtn.config('relief')[-1] == 'sunken':
        yellowBtn.config(relief="raised")
        arduino.write('g'.encode())
    else:
        yellowBtn.config(relief="sunken")
        arduino.write('h'.encode())

print ('Connecting...')
arduino = serial.Serial("/dev/ttyACM0", 9600)
time.sleep(3)
print ('Connection established successfully')

appWindow = Tk() # creates the application window (you can use any name)
appWindow.wm_title("RGB LED Control") # displays title at the top left
appWindow.config(bg ="#037481")

mainFrame = Frame(appWindow, bg="#037481") #define the main frame of the GUI
mainFrame.grid() #grid the frame into the App Window

btnFrame = Frame(mainFrame, bg="#037481") #define the frame within the main frame that holds buttons
btnFrame.grid() #grid the frame into the main frame

redBtn = Button(btnFrame, text="RED", width=12, bg="red", relief="raised", command=toggleRed)
redBtn.grid(column=0,row=0,sticky='EW')

greenBtn = Button(btnFrame, text="GREEN", width=12, bg="green", relief="raised", command=toggleGreen)
greenBtn.grid(column=0,row=1,sticky='EW')

blueBtn = Button(btnFrame, text="BLUE", width=12, bg="blue", relief="raised", command=toggleBlue)
blueBtn.grid(column=0,row=2,sticky='EW')

yellowBtn = Button(btnFrame, text="YELLOW", width=12, bg="yellow", relief="raised", command=toggleYellow)
yellowBtn.grid(column=0,row=3,sticky='EW')

appWindow.mainloop()# begins main loop

Here is the arduino code:

int ledRed = 13;
int ledGreen = 11;
int ledBlue = 9;
int ledYellow = 7;

//int ledRedStatus;
//int ledGreenStatus;
//int ledBlueStatus;
//int ledYellowStatus;

void setup() {
  pinMode(ledRed, OUTPUT);
  pinMode(ledGreen, OUTPUT);
  pinMode(ledBlue, OUTPUT);
  pinMode(ledYellow, OUTPUT);
  Serial.begin(9600);
}
void loop() {
  if(Serial.available() == '97') {
    digitalWrite(ledRed, LOW);
  }
  if(Serial.available() == '98') {
    digitalWrite(ledRed, HIGH);
  }
  if(Serial.available() == '99') {
    digitalWrite(ledGreen, LOW);
  }
  if(Serial.available() == '100') {
    digitalWrite(ledGreen, HIGH);
  }
  if(Serial.available() == '101') {
    digitalWrite(ledBlue, LOW);
  }
  if(Serial.available() == '102') {
    digitalWrite(ledBlue, HIGH);
  }
  if(Serial.available() == '103') {
    digitalWrite(ledYellow, LOW);
  }
  if(Serial.available() == '104') {
    digitalWrite(ledYellow, HIGH);
  }
}


texts: I would like to add a RGB led strip to my arduino alarm system

texts:
I am new to programming and would be grateful for any helpful answer...Thank you
I used a ping sensor, a piezo buzzer and an RGB strip. I used the Schematic from Adafruit Learning System..
Here is my code:

#define trigPin 5
#define echoPin 6
#define RED_PIN    10
#define GREEN_PIN   11
#define BLUE_PIN  9
int Buzzer = 3;

void setup() {
    //set pinModes for RGB strip
    pinMode(RED_PIN,OUTPUT);
    pinMode(BLUE_PIN,OUTPUT);
    pinMode(GREEN_PIN,OUTPUT);

    pinMode(Buzzer, OUTPUT);

    //reset lights
    analogWrite(RED_PIN,0);
    analogWrite(BLUE_PIN,0);
    analogWrite(RED_PIN,0);

    delay(5000);
    Serial.begin (9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(Buzzer, OUTPUT);
}

void loop() {
    int duration, distance;
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(1000);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;
    if (distance >= 80 || distance <= 0){
        Serial.println("No object detected");
        digitalWrite(Buzzer, LOW);
    } else {
        Serial.println("Object Detected");
        tone(Buzzer, 1000); // play 400 Hz tone for 500 ms
        delay(500);
        tone(Buzzer, 10000); // play 800Hz tone for 500ms
        noTone(Buzzer);
    }
    delay(300);
}


texts: Is it okay to short IN and GND pins of relay module with controller ground?

texts:
I have this relay module that is attached to an ESP8266 (Wemos D1 Mini). Currently, I operate the relay by shorting the IN and GND pins to ground (relay module uses low state to energize) with a transistor hooked to my D1 pin. Relay 5V comes from an external power supply

The circuit diagram can be found here.

The module works fine and all but I am wondering: is it okay to operate it like this ?