text:
"Bad request" error (HTTP) while posting to PHP server using Arduino and ESP8266
I'm doing an IoT project where the temperature and humidity values from a DHT11 sensor is sent to a PHP server using HTTP post. When I run the Arduino, the Serial Monitor says "Bad request". The sensor values are not appearing on the webpage. Please, help me figure out the problem. I am using an Arduino Uno with and an ESP-01.
// Code to use SoftwareSerial
//The final sketch
#include "SoftwareSerial.h"
#include <dht.h>

#define dht_dpin 8

String data;
String ssid = "TRAK family";

String password = "rukman12345";

SoftwareSerial espSerial(6, 7); // RX, TX

dht DHT;

float t;
float h;

String server = "svce-ece-b.000webhostapp.com";

String uri = "esp.php";

boolean DEBUG = true;

void showResponse(int waitTime)
{
    long t = millis();
    char c;
    while (t + waitTime > millis()) {
        if (espSerial.available()) {
            c = espSerial.read();
            if (DEBUG)
                Serial.print(c);
        }
    }
}

void setup()
{
    DEBUG = true;

    Serial.begin(115200);
    delay(500);

    espSerial.begin(115200);

    espSerial.println("AT+RST");
    showResponse(1000);

    // espSerial.println("CIOBAUD=9600");
    // showResponse(1000);

    espSerial.println("AT+CWMODE=1");
    showResponse(1000);

    espSerial.println("AT+CWJAP=\"" + ssid + "\",\"" + password + "\"");
    showResponse(5000);

    if (DEBUG)
        Serial.println("Setup completed");
}

void httppost()
{
    espSerial.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");

    if (espSerial.find("OK")) {
        Serial.println("TCP connection ready");
    }
    delay(1000);

    String postRequest =
        "POST " + uri + " HTTP/1.0\r\n" +
        "Host: " + server + "\r\n" +
        "Accept: *" + "/" + "*\r\n" +
        "Content-Length: " + data.length() + "\r\n" +
        "Content-Type: application/x-www-form-urlencoded\r\n" +
        "\r\n" + data;

    String sendCmd = "AT+CIPSEND=";
    espSerial.print(sendCmd);
    espSerial.println(postRequest.length());

    delay(500);

    if (espSerial.find(">")) {
        Serial.println("Sending..");
        espSerial.print(postRequest);

        if (espSerial.find("SEND OK")) {
            Serial.println("Packet sent");
            while (espSerial.available()) {
                String tmpResp = espSerial.readString();
                Serial.println(tmpResp);
            }

            // close the connection
            espSerial.println("AT+CIPCLOSE");
        }
    }
}

void loop()
{
    // Read sensor values
    DHT.read11(dht_dpin);
    float t = DHT.temperature;
    float h = DHT.humidity;
    if (isnan(t) || isnan(h)) {
        if (DEBUG)
            Serial.println("Failed to read from DHT");
    }
    else {
        if (DEBUG)
            Serial.println("Temp=" + String(t) + " *C");
        if (DEBUG)
            Serial.println("Humidity=" + String(h) + " %");

        data = "temperature=" + String(t) + "&humidity=" + String(h);

        httppost();
    }

    delay(1000);
}

This is my PHP code:
<?php
    global $Temp;
    global $Humidity;
    if(isset($_POST['temperature'])){
        $Temp=$_POST["temperature"];
    }
    if(isset($_POST['humidity'])){
        $Humidity=$_POST["humidity"];
    }

    $Write="
Temperature : " .$Temp . " Celcius
" . "
Humidity : " .       $Humidity . " %
";
    file_put_contents('sensor.html',$Write);
?>

the serial monitor says bad request   ... the code that you posted does not contain the text bad request ... the message does not come from the code that you posted

@jsotola That's probably the response from the server.

uri should start with /.

@gre_gor thanks brother. it resolved my issure

The URI path in the HTTP request must start with a /.
It should be:
String uri = "/esp.php";


text:
ESP 8266 does not respond at all
I have a ESP8266_01, and I wired up. It does not work for me.
I have connected the ESP to an Arduino Uno. I am using a 5V pin from uP with a 3.3V regulator, and I have a voltage divider between RX(ESP) and TX(uP). And I am sure that the wiring is correct. The thing is, I am not getting anything back from ESP, not even errors. And I tried to use different baudrates as well. There is a blue LED flashing from ESP only when I am using 115200, and red LED lights up constantly at any other baudrate.
What have I done wrong here?
I did 4 hours of research already and don't know what else I can do now.
If you have any idea, please leave me a word.

I did the exact same method and got looping of "Sending an AT command...". Seems to me software serial did not print AT. When I connect using a FTDI cable, it works perfectly. I am sure the ESP8266 is working but I am unsure that my connections are correct. I use an external 2 AAA batteries to power the chip as well as 3.3V from the board. For TX RX, I use logic shifter and voltage divider. All combinations failed to produce results. Please advise.

Start by uploading blink sketch to your Arduino then connect it to your ESP8266 like this: TX-TX and RX-RX.
Now open Serial Monitor and send AT command and see if it responds. If so then you can control it using your Arduino by wiring it back to TX-RX and RX-TX.
PS: Don't forget to set the line ending in the Serial Monitor to Newline or Carriage Return.
Edit: Use this code to connect to ESP8266:
#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
const byte txPin = 3; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200); // Change this to the baudrate used by ESP8266
  delay(1000); // Let the module self-initialize
}

void loop() {
  Serial.println("Sending an AT command...");
  ESP8266.println("AT");
  delay(30);
  while (ESP8266.available()){
     String inData = ESP8266.readStringUntil('\n');
     Serial.println("Got reponse from ESP8266: " + inData);
  }
}

Since the Hardware Serial interface will be busy when connected to Computer, then you have to use another Serial interface to communicate with your ESP8266. In this case, Software Serial comes handy.

Not sure about uploading blink sketch?

Trust me, I've ran into that problem of yours. You need to upload blink sketch or any sketch that doesn't use the Serial interface (I've chosen blink since it's already there).

YOU ARE ALMOST SAVING ME! Yes it does reply me a OK, when i send AT! But when I try to wire it back to TX-RX,RX-TX, it gets stone again?

Yeah, what I've told you to do lets you bypass your microcontroller and just use the board to connect to ESP8266. When you wire it back to Rx-Tx then you must make the microcontroller take over. I'll send you a code that you can use to send an AT command and get response.

THX a lot, man!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
I2C communication in Arduino
In Arduino I2C we have the following lines of code:
wire. beginTransmission(slave addrress)
wire.write(the byte want to send)
wire. endTransmission()

As we know in I2C the master must verifies the presence of the slave address and making it sure by getting an ack by the slave. Among the three function listed, who does this job? Is it wire. beginTransmission? in their website it's just mentioned it initializes communication with the slave. I want to know what happens during the execution of wire. beginTransmission from I2C perspective.
Also wire.endTransmission() releases the buffer data which was created by wire. write. So who examines the presence of the slave? The first function or the 3rd?

All the actual I2C communication is done in Wire.endTransmission(). Before that nothing is done on the I2C lines.
Wire.beginTransaction() only initializes the libraries buffer and saves the slave address in an internal variable. Wire.write() puts data into the internal buffer.
Wire.endTransmission() can then follow the I2C protocol. It generates a start condition on the bus, sends the address byte, checks for the slaves acknowledgement on the address byte, then sends the data bytes, each followed by the slaves acknowledgement. Finally it generates a stop condition.

it means suppose i forgot to write wire. beginTransmission, does that mean I can't execute wire.endTransmission? Because it looks like the latter is depended on the first? That is, wire. endTransmission isn't an independent function.

Wire.beginTransmission() primes the library for a master write transaction. So you need it before calling Wire.endTransmission(). What makes you think that any of these functions are independent? They are working for the same hardware interface. You need to call them just as the library supposes you to.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Arduino: wrong digitalRead results from a pullup pin
A button connects GND to PIN where PIN is any digital pin.
I want to catch the moment the button is pressed, so I wrote the following code:
void setup () {
    pinMode (PIN, INPUT_PULLUP);
    Serial.begin (9600);
}

void loop () {
    static bool wasDown = false;
    bool isDown = digitalRead (PIN) == LOW;
    Serial.println (isDown);
    if (isDown && !wasDown) Serial.println ("down!");
    wasDown = isDown;
}

While the button is not pressed, everything goes as expected: the output is all zeroes. But when I press it, the following pattern appears:
0
0
0
0
<Some other zeroes, about 10 total>
1
down!
<the same number of zeroes>
1
down!
0
...

Is it some schematic flaw?

It is definitely not the case, as the pattern is very regular and stable for a long period

Also looks like a debouncing problem to me. Could your button have a repeatable bouncing behaviour?

What happens when you keep the button pressed down - do you see a constant stream of '1'? Can you give us the reference of your button used? @PlasmaHH is most likely right and you might be suffering from debouncing issues.

8 buttons connected to different pins could not, I think

@HervéGrabas no, when I press the button, I see the pattern presented in the question text: N zeroes - one - N zeroes - one - ...

Schematics and/or picture of setup could help.

Perhaps try and repeat the experiment with an external resistor?

@JorenVaes For some reason an external resistor helped... Thanks!

What output are you expecting/wanting to see?

@Mazaryk All ones when the button is pressed, all zeroes when it's not. Serial just prints the button state continuously. Anyway, the issue was solved by downloading the sketch into another board

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
ATMega328p (Arduino) Timer1 set-up
I am trying to measure AC power using an Arduino with an Atmega328p.
In summary, I want to use timer1 to make an interrupt every 400us where I measure two ADC channels (A0 and A1) and put them into an array. The problem is that instead of measuring five mains periods (mains frequency = 50Hz so 20ms * 5), I get instead 13 of these periods (260ms). What am I doing wrong?
volatile int sample_incremental = 0;

void setup() {
      Serial.begin(115200);
      pinMode(voltagePin, INPUT);
      pinMode(currentPin, INPUT);
      set_sample_interrupt();
      sei();
    }

void set_sample_interrupt() {
  //Count to 400us
  OCR1A = 99;
  //Mode 4, CTC
  TCCR1B |= (1 << WGM12);
  //Enable interrupt
  TIMSK1 |= (1 << OCIE1A);
  //Prescaler 64
  TCCR1B |= (1 << CS11) | (1 << CS10);
}

ISR (TIMER1_COMPA_vect) {
  // action to be done every 400 usec
  current_sample[sample_incremental] = analogRead(currentPin) - 504;
  voltage_sample[sample_incremental] = analogRead(voltagePin) - 512;
  if (sample_incremental < (SAMPLES * PERIODREADS))
    sample_incremental++;
  else {
    //Disable interrupt
    TIMSK1 &= ~(1 << OCIE1A);
    sample_incremental = 0;
    finishedReading = true;
  }
}

Where after I do one reading, I stop the interrupt, and SAMPLES * PERIODREADS = 250.

please post a graph of what you expect and what you actually get

The Arduino core library configures the Timer 1 for phase-correct PWM at
about 490 Hz. Then you are setting some configuration bits in the
timer's control registers without clearing the bits that had previously
been set by the Arduino core. If you want to use the timer for your own
purposes, and configure it by yourself, you should completely overwrite
the core's configuration with your own. For that, use the = operator
rather than |=, as in:
OCR1A  = 99;                         //Count to 400us
TIMSK1 = (1 << OCIE1A);              //Enable interrupt
TCCR1A = 0;
TCCR1B = (1 << WGM12)                //Mode 4, CTC
       | (1 << CS11) | (1 << CS10);  //Prescaler 64

This is the right answer, I fixed it using "  TCCR1A = 0;
TCCR1B = 0;
TCNT1  = 0;" as a "hack" but your reply goes to the problem. Thank you!


text:
Arduino i2c communication between another arduino and a sensor
Can the following scenario exist?

Microcontroller 1 sends a code to microcontroller 2 to start reading sensor data. Then Microcontroller 2 reads sensor data from sensor and sends it back to microcontroller 1.
If such a scenario is possible, then how would the pseudo code for microcontroller 2 receive-event be?
Need help with this badly!!

Can the following scenario exist?
  Yes. Such a scenario is called Multi-Master.
If such a scenario is possible, then how would the pseudo code for microcontroller 2 receive-event be?

MCU 2 would just be set up as any other slave. It waits, as normal, for an instruction in whatever for you like. Once it receives that instruction in then switches into master mode and makes a normal request exactly as you would from MCU 1 if you wanted it to read the sensor.

On receive:

Set "run as master flag"
Disable slave mode

In loop:

If "run as master flag" is set:

Perform request to get data from sensor
Clear "run as master flag"
Enable slave mode

Running a multi-master system does have its own set of caveats and things you have to watch out for. You can read more about it here:

https://www.hackster.io/chipmc/arduino-i2c-multi-master-approach-why-and-how-93f638

Thanks for the heads up regarding Bus arbiteration. Will try this out and hopefully, it works!

Hi again, wanted to try out your soultion, but had this question -How do you enable or disable slave mode on the arduino?


text:
Irrecvdemo program in or remote library gives fatal error #include<WProgram.h>
Whenever I compile irrecvdemo of or remote library it gives error saying that fatal error saying

no file or directory exists #include <WProgram.h>

#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
}

Welcome! It sounds like you've got a syntax error in your sketch. If you include your code it will be much easier to help you.

#include <IRremote.h>
int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}
void loop() {
if (irrecv.decode(&results)) {
Serial.println(results.value, HEX);
irrecv.resume(); // Receive the next value
}
}

You are using a very old library on a modern IDE.  The file that was called WProgram.h in IDE version 0023 and below is now called Arduino.h.  You will need to change any references to WProgram.h to Arduino.h instead.
Well written libraries do this with a #ifdef block:
#if (ARDUINO >= 100)
# include <Arduino.h>
#else
# include <WProgram.h>
#endif

Can I know exactly where to edit and which lib file

I can't really tell you that, no, you will have to find it for yourself. You will need to find where you installed the library to and look in the files included with it. There may be only 2 - a .cpp and a .h file - or there may be more. There may be a "utility" folder with more in as well. The include will always be near the top of the files though, so it should be easy to spot. Depending on your operating system you may have the facility to search for files with certain words in them - for instance on Linux and OS X there is the grep command line utility. Not sure what is on Windows.

I found those files and copied that codes which you gave,I tried on CCP file h file...I tried all combinations and used older version of ide also but it did not compile...

@AdithyaPai What is the library you are trying to use?

IR remote library... Just using demo codes to get binary numbers from normal ir remote...by connecting ir receiver sensor tsop-...

@AdithyaPai WHAT IR remote library? Give me a link to it.

https://github.com/z3t0/Arduino-IRremote?e_pi=7%2CPAGE_ID10%2C5785360335

Well, that library already has all the right things in it and doesn't require any modification. Your code compiles against it perfectly. My guess is that you have a second, rather ancient, copy somewhere around that is conflicting. Search your hard drive for any old copy and eradicate it.


text:
3-wire strain gauge - HX711 Issue
I have two, three-wire load sensors (https://cdn.sparkfun.com//assets/parts/4/5/9/5/10245-01.jpg) hooked up in a half wheatstone bridge (I think), with two 1K resistors.  Using a multimeter, I am reading small voltage changes when applying pressure to either strain gauge, when measured on between the pins A+ and A- on the HX711 ADC amp, however my Arduino serial output shows all 0's when using a variety of code examples (for example, this one:  http://www.dfrobot.com/wiki/index.php/Weight_Sensor_Module_V1#Sample_code).
My concern is that my circuit is not setup correctly as I am fairly novice, however everything I have researched about wheatstone bridges, and half wheatstone bridges seems fairly straightforward, and seems to match my circuit.  Any guidance/advice on the attached breadboard circuit diagram would be extremely helpful.

The white wires in your diagram are not in the center as in the linked picture.   Also, the E+/E-/A-/A+ labels seems off by one pin.   If the whites are the center wire on your device, they are likely the middle, sensing terminal of the load cells, and should connect to the A+/A- of the HX711 See the last paragraph of http://arduino.stackexchange.com/a/18698/6628 for using the sensors's other gauges as resistors.  Could be the precision of the resistors swamp the bridge.

Perhaps you should move your greens from +5/GND to the E+/E- to let the HX711 excite your bridge rather than the power supply.

I was directed in an Arduino forum to wire it up like this:  https://imgur.com/OkEuWV4   however I still cannot get it to work.  Going to move the greens around as well.

What is the no-load voltage difference across A-/A+?  I didn't dig into the code you pointed to, but it looks like it might be multiplying the value by 1992.0 and I'm not sure what offset it adds.  If the no-load voltage is far from zero, it might overflow or underflow something and give you a constant value.    I'd use the strain gauge's other halves as in the forum's diagram, instead of discrete resistors as in yours, since you need to balance things to near 0.1%.  The white-black connections they show put the tension(or compression) gauges on opposite sides, difft than your connections.

Also, check the resistances between the gauge terminals.  The sense/A+/A- should be the same color wire, and should lie halfway between the resistance between the other two terminals.  It is essentially the center tap of a ~2k potentiometer, and it should move about +/-0.1% or 2 ohms from the center at full load.

In your diagram, the fixed 1KΩ resistors both tie to +5V at one set of ends, and their other ends tie to A+ and A-.  The strain gauges are from A+ to ground and A- to ground.
In a typical scale, where several strain gauges are similarly loaded, that topology will produce about zero volts between A+ and A-.  By contrast, the following  topology (from: blog.l3l4.com) produces higher voltages for higher loading.  (Diagram uses S+, S- rather than A+, A-)
(I realize your question shows some voltage changes when sensors are separately loaded, so this answer might not be relevant to your current problem.)

The OP has the strain gauges both on the bottom side of the wheatstone bridge, where if similarly loaded would pull both E+ and E- in the same direction when loaded.  What might be more of a problem, is if the values of the discrete resistors R1, R3 do not match the strain gauges to 0.1% perhaps making zero-load S+/S- voltage too large to work with.


text:
error loading an array of strings
I'm trying to have a user enter a series of strings. This is my code.
this is my error message - cannot convert 'String' to 'char*' in assignment
char* titles[] = {"entry one", "entry two", "entry three", "entry four", "entry five"};

void setup() {
 Serial.begin(9600);
 Serial.println("Storing numbers in an array");
}

void loop()

{

for (int x =0; x < 5; x++)
{
  if (Serial.available() > 0)

  {
   Serial.println("Enter a word... ");
   titles[x] = Serial.readString();

    Serial.println(" ");
    Serial.println(chartitles[x]);

   }
  }
 }

This is really not how you want to do this.

You are confusing the concept of a "string" (C string - char array) with a "String" - the Arduino-specific class that people who don't know better use.

So, you are confusing the object String of Arduino with a string of C (char array), to solve your problem, I've changed your code in two parts:
String titles[] = {"entry one", "entry two", "entry three", "entry four", "entry five"};

void setup(){
  Serial.begin(9600);
  Serial.println("Storing numbers in an array");
}

void loop(){
  for (int x = 0; x < 5; x++){
    if (Serial.available() > 0){
      Serial.println("Enter a word... ");
      titles[x] = Serial.readString();
      Serial.println(" ");
      Serial.println(titles[x]);
    }
  }
}

So, in order to use Seria.readString(), you have to use String objects to receive the data from Serial port:
String titles[]

Instead of:
char* titles[]

The second change is related to Serial.println(chartitles[x]), I didn't understand what you mean with this code, so I changed in order to print the String that was read.

I modified the code slightly. Im getting a strange output. I placed the print statement outside the for loop to enter the strings. Now when it prints it prints the original values for the strings and the ones that are entered from the serial monitor.
See the image.
https://www.dropbox.com/sc/5ubcn2raee4vmkn/AADBvjHcQVMhpCsIIW3cahXba

@MichaelNiebauer I think this is what you want to code: https://codeshare.io/9ko5o

thank you, this does exactly what I was looking for. I have a question whats the difference between using if and while before the (Serial.available() > 0) statement. I was using an if and it didn't work it looks like by switching it to a while it does.

try to think about the else, if you were not writing something in the Serial console, the program would skip the if and continue, but since the code was inside a void loop, this would be repeated, making your program repeat the println and the for

when you use a while the program waits a response


text:
Creating a library
I created a simple library for formatting text output on the serial monitor. It has thee functions, one that creates carriage returns, one that sets the number of spaces between characters and the last one prints dashes. I followed the tutorial on the Arduino.cc site. The problem I have is that I can’t pass the value to each of the functions when I call them in the code. If you look at the screenshot from the sketch when I create an instance of nFormat it requires me to put a value in and it passes that value to each of the functions (lines, spaces, dashes). I want to be able to specify the value directly when I call the function. See the second red line on the output screenshot. I know this post is a bit long I would appreciate it if someone could point me in the right direction.
nFormat.h
#ifndef nFormat_h
#define nFormat_h

#include "Arduino.h"

class nFormat
{
  public:
    nFormat(int counter);

    void lines();
    void spaces();
    void dashes();

   private:
    int _counter;
};

#endif

nFormat.cpp
#include "Arduino.h"
#include "nFormat.h"

nFormat::nFormat(int counter)
{
    _counter=counter;
}

void nFormat::lines()
{
for (int x = 0; x < _counter; x++)
    {
        Serial.println(" ");
    }

}

void nFormat::spaces()
{
    for (int x = 0; x < _counter; x++)
    {
        Serial.print(" ");
    }
}

void nFormat::dashes()
{
    for (int x = 0; x < _counter; x++)
    {
        Serial.print("-");
    }

Why are you using a class if you want to be able to pass all the parameters directly to the functions?

I want to avoid having to make an instance of nFormating everytime I want to change the value of the number of spaces or dashes. For example if I wanted to have 10 dashes instead I would have to create nFormat nFormatTwo(10); I get an error when I compile the program when placing the value inside the function call.

If you want to specify the number of spaces/dashes/... every time you
call any of these methods, you just have to make that number a parameter
of the method:
void lines(int count)
{
    for (int x = 0; x < count; x++)
        Serial.println();
}

Then, your class does not need its private _counter. Then, since there
is no data in the class, you do not need to instantiate it: just make
all the methods static and call the methods as
nFormat::method_name(). And since you are not making instances, you do
not need a constructor either. And since the methods are really trivial,
there is no point in implementing them in a .cpp file: you can just
inline them in the class declaration. Combining all this gives this small
demo program:
class nFormat
{
  public:
    static void lines(int count)
    {
        for (int x = 0; x < count; x++)
            Serial.println();
    }

    static void spaces(int count)
    {
        for (int x = 0; x < count; x++)
            Serial.print(" ");
    }

    static void dashes(int count)
    {
        for (int x = 0; x < count; x++)
            Serial.print("-");
    }
};

void setup()
{
    Serial.begin(9600);
    nFormat::dashes(5);
    nFormat::lines(5);
    nFormat::spaces(5);
    nFormat::dashes(5);
}

void loop() {}

It could be noted than this class serves only to avoid putting all the
functions in the global namespace. It is essentially a namespace. You
could as well replace class by namespace (and remove the public
keyword) to make that more explicit.


text:
Issue with Visual Studio not seeing arduino boards
Below is a screenshot. I used Visual Studio with the Visual Micro [arduino extension] a few months back. I switched computers and installed Visual Studio on the new one but for some reason after Visual Micro has been installed its not seeing any of the boards. In the visua lMicro explorer it doesnt have an option for the board manager. If anyone can point me in the right direction that would be great.

I'm not sure if this is an Arduino question. To me, it seems more a problem with the software. Anyway, have you installed the Arduino drivers? If yes, then I only can suggest a restart of your computer and if that doesn't work a clean install of all the relevant software. That is under the assumption that your computer (in device manager) is able to detect the Arduinos, but visual studio is not.

The arduino ide has no problem uploading to the board. I reinstalled visual studio and the visual micro extension and still the same issue. I'm using the arduino ide right now but i prefer visual studio

Sorry I missed this. Did you correct the path to the Arduino IDE or version? Or was this a windows store version of Arduino which is only recently supported? Hope you got it sorted. There is a forum at visualmicro.com if anyone needs help.


text:
Using logical operators
This is a snip it of code from a program I am writing. I have the program turn an LED on and if a button is pressed when the LED is on I want it to add to a counter and print the counter value. The problem seems that my if statement is skipped. Right now the while loop is setup for 5 seconds using millis() and stays off using a short delay. This part (button_press_9())) is a function call to a Boolean I have setup for debouncing. If I put the function call in an if statement by its self for example to test it. It works and will turn an LED on and off. It seems the combination of the two is incompatible.
Thank you in advance.
unsigned long previousMillis = millis();
unsigned long currentMillis = millis();

while ((currentMillis - previousMillis) < onTime)
{
    digitalWrite(ledPin4, HIGH);
    if (ledPin4 == HIGH && (button_press_9()))
    {
        counter++;
        Serial.println(counter);
        currentMillis = onTime * 100;
    }
    currentMillis = millis();
}
digitalWrite(ledPin4, LOW);
delay(1000);

ledPin4 == HIGH? Guess you mean something else.

Also, currentMillis = onTime * 100; makes little sense. What did you actually mean?

@EdgarBonet I put it in there so if the LED was HIGH and there button pushed it would end the timer in the while loop

@MikaelPatel I set the LED to HIGH and then used an if statement to check if it's HIGH and the button was pressed at the same time. I didn't use there == to assign the HIGH state

Then you mean currentMillis = previousMillis + onTime, but that won't work because you assign currentMillis = millis(); right after. Instead, you can simply break out of the while loop.

ledPin4 == HIGH does not check if the LED is high. For instance, if ledPin4 is defined as int ledPin4 = 4; then the statement is 4 == 1.

You should use
if (digitalRead(ledPin4) == HIGH && (button_press_9()))

instead of
if (ledPin4 == HIGH && (button_press_9()))

Since the pin has been set to HIGH right before, the first part of the test seems useless. You can just do if (button_press_9()).


text:
Determine an earthquake intensity/magnitude level using ADXL345 and Arduino
I want to create a project using Arduino that monitor the Earthquake. I used an ADXL345 Accelerometer to detect if there is an earthquake. I used the Adafruit ADXL345 example to determine a acceleration of x-axis, y-axis and z-axis in terms of m/s^2. I want to used the Japan Meteorological Agency seismic intensity scale to determine the intensity level of the earthquake because it gives the Peak Ground Acceleration. If there is a way to determine the earthquake intensity level using ADXL345?


text:
Pull-down resistor value for interrupts
I wonder how to calculate pulldown resistor to make interrupt work?
I need to connect 5 buttons to A0 and get pressing event via interrupts.
Using different resistors, finally, I made work only 4 buttons. On 5th interrupt does not fire.
Currently I use the following resistors for the buttons:
R1      Vout
0       5,00
2,7K    4,45
5K      3,70
10K     2,77
22K     1,78

And Pulldown Resistor = 22K.
If pulldown Resistor = 10K I can get event for 1-3 button only.
Looks like the voltage 1,78V is quite low.
But I’d liked make it work with 1V at most.
I use RISING mode.
PS. Arduino Nano

An Arduino running at 5V needs at least 3.0V on the pin to read it as rising high.  You probably want to go a little more than that.  So that means your lowest voltage has to be like 3.3V or so.
Note that the analog pins don't have an external interrupt, you'll have to use pin change interrupts and then read with analogRead in the ISR.  So you can't use "RISING".  The pin change interrupts act on any edge.  So they'll trigger when falling as well.
That's a pretty poor way to handle these buttons.  Normally one would just poll buttons like this.  If your loop takes so long that you might miss a human pressing a button then perhaps you should look at that instead.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Get UUID from Arduino Nano, ATmega328
I need to know how to obtain the UUID from an Arduino Nano ATmega328 for a project.

Why not program a UUID in EEPROM once? There is no hardware UUID. https://stackoverflow.com/questions/21559264/unique-machine-id-for-arduino-project

You don't have a UUID.
You only get a UUID in the USB-enabled chips, like the ATMega32U4.
You would have to create your own UUID and store it in EEPROM, or embed it within your sketch.


text:
Optimizing Teensy 3.6 for data sampling?
So, I have a very basic project where I cycle through 8 IR individual transmitters. After setting the individual transmitter high, I cycle through all 8 IR receivers and print their values, RX_CYCLES many times. I need a huge amount, quality data from these loops to train a neural net, so
I want to optimize my code to where I can analogRead each receiver the fastest, but keep the maximum resolution possible.
I'm having trouble understanding Teensy's documentation and provided libraries and finding any relevant resources that are clear enough for me to weave through the jargon.

My questions are:

What would be or how do I go about calculating the optimization or balance of the fastest baudrate I can match with the Teensy 3.6, with the highest quality resolution possible?
How to optimize analogRead? I've read that the fastest way is to use continuous analogRead instead of single analogRead? I'm having trouble finding clear examples of what this actually does and how to use it effectively. I definitely could be wrong about it this.
Am I outputting data the best way possible? I was wondering if there would be any reason in my case to use print() or println() or if I should be using flush() after every cycle

These are a lot of questions, and I don't expect anyone to optimize my code for me, so if you can help point me in the direction of clear material I can use to direct me in this problem.
I'd also really appreciate any other suggestions or insight anyone would like to offer that I may be missing.

This is my very basic code:
const uint8_t RX_CYCLES = 1;
const uint8_t RX_START = 14, RX_END = 21;
const uint8_t TX_START = 0, TX_END = 7;

void setup() {
    Serial.begin(115200);
    while (!Serial);
    for (uint8_t reciever = RX_START; reciever <= RX_END; reciever++) pinMode(reciever, INPUT);
    for (uint8_t transmitter = TX_START; transmitter <= TX_END; transmitter++) pinMode(transmitter, OUTPUT);
}

void loop() {
    for (uint8_t transmitter = TX_START; transmitter <= TX_END; transmitter++) {
        digitalWriteFast(transmitter, HIGH);
        for (uint8_t i = 0; i < RX_CYCLES; i++) {
            for (uint8_t reciever = RX_START; reciever <= RX_END; reciever++) Serial.println(analogRead(reciever));
        }
        digitalWriteFast(transmitter, LOW);
    }
}

I was thinking of using DMA. It also seems that analogRead is pretty slow on the teensy because it calibrates itself every times it's called. This thread seems to contain a lot of useful info: https://forum.pjrc.com/threads/30171-Reconfigure-ADC-via-a-DMA-transfer-to-allow-multiple-Channel-Acquisition

@Gerben if the optimization would be turning off calibration before every call, wouldn't this produce uncalibrated readings which inherently agains't anyones interest?

please correct me if i'm wrong, but it seems to me that you have not explained what you are measuring and what parameter you are referring to when you say "maximum resolution" ..... just because you are using analogRead, it cannot be assumed that you are only measuring analog levels of some physical property

@jsotola I meant to imply that the IR receivers where measuring the output of the current IR transmitter in the loop. I realize now that's not so obvious. From what I understand resolution refers to the specificity of data, so having the highest resolution possible is the difference between 1024 and 1023.67. I'm going to break this question up, I think this may be too much and broad to ask.


text:
NodeMCU with HC-SR04 ultrasonic sensor
How can I interface an ultrasonic sensor with a MCU with 3.3 V GPIO like the NodeMCU? I tried powering the sensor with both 5 V and 3.3 V from the MCU. Both failed to show any results as the distance appeared to be 0 V. In both cases the trig pin of the sensor was given 3.3 V input from the GPIO pin. I assume I need to level shift the echo pin output from 5 V to 3.3 V. How can I do that? Or is something else the issue? The code I used is fine as it works with Arduino.

The datasheet I found says the logic is TTL, which as far as I know is 2 V - Vcc, so 3.3 V should be fine. Is Trig just constantly given 3.3 V? According to the datasheet, it needs a 10 us pulse. Perhaps that is your issue? Code or schematics could help if that isn't it.

I have given trig pulse High and Low at 10us interval. The code is not the issue as I have used the same code with Arduino and it works fine.


text:
NodeMCU with JHD162A LCD issue
I have uploaded a program to NodeMCU , to print "hello, world" on JHD162A 16x2 LCD module. But the text doesn't appear on the lcd display. Instead just black blocks appear on the first row on the LCD. I assume it's a hardware related issue since the software worked in simulation. I powered the NodeMCU and the LCD using 5V DC from 7805 voltage regulator IC. The 12v input to the IC is provided using a 230V AC  to 12V DC adapter with 2A max current out. I have placed a 680 ohms resistor to the anode of the lcd back led, also a 1K resistor between the Vss and Vee of the LCD to set contrast. I am using D0, D1, D2, D3 pins of the NodeMCU to the D7, D6, D5, D4 data pins of the LCD. The RW is connected to the gnd pin of NodeMCU. The RS and E pins are connected to the D8 and D7 of NodeMCU.
#include<LiquidCrystal.h>

const int RS= D8, EN = D7, d4 = D3, d5= D2, d6 = D1, d7 = D0;

LiquidCrystal lcd(RS, EN, d4, d5, d6, d7);

void setup()
{
lcd.begin(16, 2);
lcd.print("hello, world!");
}

 void loop()
{
lcd.setCursor(0, 1);
lcd.print(millis() / 1000);
}

Avoid using D8 (GPIO15), D4 (GPIO2) and D3 (GPIO0) as they have special boot-controlling uses.

@Majenko That worked ! Thank you so much.


text:
Using NodeMCU D8 (GPIO15), D4 (GPIO2) and D3 (GPIO0) pins
I am using a NodeMCU board and have already used 6 digital pins as output for interfacing with the LCD. I intend to use 2 more digital pins, one as input and other as output for interfacing an ultrasonic sensor.
D8, D4 and D3 are the only digital pins remaining. I understand that D8 (GPIO15), D4 (GPIO2) and D3 (GPIO0) pins of the NodeMCU  have special boot-controlling uses. So how can I use those pins as generic digital pins. Any help is appreciated.

I would recommend to use an I2C LCD display

you can get an I2C LCD controller for well under $1USD on ebay.

I'm aware of this. I was looking for a way to implement D8, D4 and D3 as gpio pins. Thank you.

The boot setup pins have pull-up on board (0, 2) and pull-down (15) to ensure the correct boot. io 0 (D3) is additionally wired to the reset circuit controlled over USB to put the esp8266 into bootloader a.k.a. flashing mode.
io 0 must be HIGH for normal boot, io 2 must not be LOW (can float according to spec).
If you attach a device to this pins, the device must respect the boot state. Some devices will pull-down or pull-up a wired pin. Usually it is not documented. You can't use such devices on boot config pin which requires the other state.
The pull-up and pull-down can influence the attached device or readings from the device. For some elements it can be advantageous.
Best is to use this pins for elements which would need pull-up or pull-down anyway. For example buttons/switches or sensors which behave like buttons or switches.
In my project with Wemos D1 R2 I had signal to relay module on io 0, speaker module (with amplifier) for tone() function on io 2. I could not use a relay or mosfet module on io 2. On io 15 I had a reed relay module control signal, which I didn't want to go HIGH at boot as most esp8266 io pins do.

Thank you for the info. So how can interface an ultrasonic sensor to any of those 3 pins. Obviously both the trig and echo pins change states to high or low.

only the state at startup matters to esp8266. the distance sensor could be disturbed by the pull-ups or pull-downs. you know when you try it. try io 0 and io 15 first.

Not a direct answer to your question, but some other way that solves your problem, is to use a shift register like 74HC595 and control the 6 pins for the LCD with the 74HC595 which only uses 3 (digital GPIO) pins. That saves you 3 pins for others. Actually you can use 8 pins or even 32 when you daisy chain four 74HC595s.


text:
GPS module Ublox Neo 6M issue
I using the above mentioned GPS module with Arduino UNO. I find that I cannot receive the Latitude and Longitude values in the $GPRMC string in the NMEA data, as I used the module inside a concrete building. I got the values when I placed the module just outside the window. But I have noticed that the phones we use can get the location data just fine through their in-built GPS after waiting for just some time. How is this possible? Any way I can achieve this using the Ublox Neo 6M module?

Mobile phones use the mechanism of assisted GPS.
In contrast to your Arduino U-Blox module it uses the cell tower data your phone can provide to determine your location. This is especially helpful to get a quicker first fix and to get a fix even when you have poor satellite signal conditions.
That said, this will not be possible using only your GPS module connected to your Arduino.


text:
Play a single sound using music shield
I am working on a music shield, I want to play a sound when a sensor triggers (it is very noob I know) well The music shield manufacturer provides a simple class named MusicPlayer here you can find its source
#include <SD.h>
#include <MusicPlayer.h>
#include  <avr/pgmspace.h>

// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8

static unsigned char fileBuf[32];
songtype list[15];            //song list
int ledcount;
key keys[5];

VS10XX VS1053;
Sd2Card     card;
SdVolume    volume;
SdFile root;
SdFile file;
playingstatetype playingState;
ctrlStatetype ctrlState;

/* PCM file Header */
unsigned char pcmHeader[44] = {
  'R', 'I', 'F', 'F',
  0xFF, 0xFF, 0xFF, 0xFF,
  'W', 'A', 'V', 'E',
  'f', 'm', 't', ' ',
  0x10, 0, 0, 0,          /* 16 */
  0x1, 0,                 /* PCM */
  0x1, 0,                 /* chan */
  0x40, 0x1F, 0x0, 0x0,   /* sampleRate */
  0x80, 0x3E, 0x0, 0x0,   /* byteRate */
  2, 0,                   /* blockAlign */
  0x10, 0,                /* bitsPerSample */
  'd', 'a', 't', 'a',
  0xFF, 0xFF, 0xFF, 0xFF
};

/**************************************************************/
ISR(TIMER1_OVF_vect)          //Timer1 Service
{
    for(int i=0;i<5;i++)
    {
        keys[i].scanKey();
    }

    if (playingState == PS_PAUSE) digitalWrite(LED, HIGH);
    else if (playingState == PS_IDLE) digitalWrite(LED,LOW);
    else
    if (ledcount-- == 0)
    {
        digitalWrite(LED,!digitalRead(LED));
        ledcount = 500;
    }
}

/**************************************************************/
#define RESOLUTION 65536    // Timer1 is 16 bit
void MusicPlayer::initTimer1(void)        //initialize Timer1 to 100us overflow
{
  TCCR1A = 0;                 // clear control register A
  TCCR1B = _BV(WGM13);        // set mode as phase and frequency correct pwm, stop the timer

  long cycles;
  long microseconds = 500;   //setup microseconds here
  unsigned char clockSelectBits;
  cycles = (F_CPU / 2000000) * microseconds;                                // the counter runs backwards after TOP, interrupt is at BOTTOM so divide microseconds by 2
  if (cycles < RESOLUTION)              clockSelectBits = _BV(CS10);              // no prescale, full xtal
  else if ((cycles >>= 3) < RESOLUTION) clockSelectBits = _BV(CS11);              // prescale by /8
  else if ((cycles >>= 3) < RESOLUTION) clockSelectBits = _BV(CS11) | _BV(CS10);  // prescale by /64
  else if ((cycles >>= 2) < RESOLUTION) clockSelectBits = _BV(CS12);              // prescale by /256
  else if ((cycles >>= 2) < RESOLUTION) clockSelectBits = _BV(CS12) | _BV(CS10);  // prescale by /1024
  else        cycles = RESOLUTION - 1, clockSelectBits = _BV(CS12) | _BV(CS10);  // request was out of bounds, set as maximum

  ICR1 = cycles;
  TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  TCCR1B |= clockSelectBits;                                          // reset clock select register, and starts the clock

  TIMSK1 = _BV(TOIE1);
  TCNT1 = 0;
  sei();                      //enable global interrupt
}

/**************************************************************/
void MusicPlayer::initIO(void)
{
  pinMode(SD_CS_PIN, OUTPUT);
  digitalWrite(SD_CS_PIN, HIGH);

  pinMode(VS_XCS, OUTPUT);
  digitalWrite(VS_XCS, HIGH);

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

  //keys input
  pinMode(KEY_VD, INPUT);
  pinMode(KEY_BK, INPUT);
  pinMode(KEY_PS, INPUT);
  pinMode(KEY_NT, INPUT);
  pinMode(KEY_VU, INPUT);
  //internal pull-up
  digitalWrite(KEY_VD, HIGH);
  digitalWrite(KEY_BK, HIGH);
  digitalWrite(KEY_PS, HIGH);
  digitalWrite(KEY_NT, HIGH);
  digitalWrite(KEY_VU, HIGH);
}

/**************************************************************/
void MusicPlayer::initSD(void)
{

  char i = 0;
  dir_t p;
  char name[13];

  /* init sd card */
  if(!card.init(SPI_FULL_SPEED, SD_CS_PIN))   //SPI_FULL_SPEED
  {
    Serial.println("SD initialization failed.");
    while(1);
  }
  if (!volume.init(card))
  {
    Serial.println("Could not find FAT16/FAT32 partition.");
    while(1);
  }
  root.openRoot(volume);
  Serial.println("---- songs in TF card (root dir) ----");
  while(root.readDir(&p) != 0)
  {
    SdFile::dirName(p, name);
    char *s = name;
    s = strupr(s);
    if(strstr(s,".MP3")||strstr(s,".WAV")||strstr(s,".WMA")||strstr(s,".OGG")
             ||strstr(s,".AAC"))
    {
        uint32_t curPos = root.curPosition();
        uint16_t index = (curPos - 32) >> 5;
        if (file.open(&root,index, O_READ))
        {
            file.close();
            strncpy(list[i].name, name, 13);
            list[i].index = index;
            Serial.println(list[i++].name);
        }
    }
  }
  Serial.println();
  MaxSong = (i-1);
}

/**************************************************************/
void MusicPlayer::begin(void)
{
    keys[0].setKey(KEY_PS,CS_PLAYPAUSE);
    keys[1].setKey(KEY_VD,CS_DOWN);
    keys[2].setKey(KEY_VU,CS_UP);
    keys[3].setKey(KEY_BK,CS_PREV);
    keys[4].setKey(KEY_NT,CS_NEXT);

    initIO();
    initSD();
    VS1053.init();
    initTimer1();  // init timer1
}

/**************************************************************/
void key::setKey(unsigned char io,unsigned char return_value)
{
  _io = io;
  _return_value = return_value;
  _key_st = KS_IDLE;
  _keycnt = 0;
}

/**************************************************************/
void key::scanKey(void)
{
  switch (_key_st)
  {
  case KS_IDLE:
    if (digitalRead(_io) == LOW) _key_st = KS_PRESS;
    _keycnt = 0;
    break;
  case KS_PRESS:
    if (digitalRead(_io) == LOW)
    {
        _keycnt++;
    } else
    {
        if (_keycnt > 20)   //10ms, short press
        {
            ctrlState = (ctrlStatetype)_return_value;
        }
        if (_keycnt > 1000) //50 ms,long press
        {
            if((ctrlStatetype)_return_value == CS_PLAYPAUSE)ctrlState = CS_RECORDING;
        }
        _keycnt = 0;
        _key_st = KS_IDLE;

        if(ctrlState == CS_PLAYPAUSE)
        {
            if(playingState == PS_PAUSE)playingState = PS_PLAY;
            else playingState =PS_PAUSE;
            ctrlState = CS_EMPTY;
        }
        if(ctrlState == CS_RECORDING)
        {
            playingState = PS_RECORDING;
            ctrlState = CS_EMPTY;
        }
    }
    break;
  default:
    break;
  }
}

/**************************************************************/
void MusicPlayer::play()
{

    unsigned char bytes;        // How many bytes in buffer left
    unsigned char n;

    SPI.setClockDivider(SPI_CLOCK_DIV2);
    if(file.open(&root,list[songIndex].index,O_READ))
    {
        Serial.print("Playing ");
        Serial.println(list[songIndex].name);
    }
    else
    {
        Serial.print("Could not open: ");
        Serial.println(list[songIndex].name);
        songIndex ++;
        while(1);
    }

    playingState = PS_PLAY;
    while(bytes = file.read(fileBuf,sizeof(fileBuf)))
    {
        // actual audio data gets sent to VS10xx.
        VS1053.writeData(fileBuf,bytes);

        switch (playingState)
        {
            case PS_PLAY:
                switch(ctrlState)
                {
                    case CS_UP:
                        Vol += 10;
                        if (Vol > MaxVol)Vol = MaxVol;
                        VS1053.writeRegister(SPI_VOL, Vol*0x101);     //Set volume level
                        ctrlState = CS_EMPTY;
                        break;
                    case CS_DOWN:
                        Vol -= 10;
                        if (Vol < 0)Vol = 0;
                        VS1053.writeRegister(SPI_VOL,Vol*0x101);      //Set volume level
                        ctrlState = CS_EMPTY;
                        break;
                    case CS_NEXT:
                        if (++songIndex > MaxSong)songIndex = 0;
                        file.close();
                        VS1053.softReset();
                        ctrlState = CS_EMPTY;
                        return;
                    case CS_PREV:
                        if (--songIndex < 0)songIndex = MaxSong;
                        file.close();
                        VS1053.softReset();
                        ctrlState = CS_EMPTY;
                        return;
                    default:
                        break;
                }
                break;
            case PS_PAUSE:
                while(playingState == PS_PAUSE);         //Pause
                break;
            case PS_RECORDING:
                file.close();
                VS1053.softReset();
                return;
        }

    }
    file.close();
    VS1053.softReset();
    Serial.println("[done!]");
    songIndex++;

}

/**************************************************************/
void Set32(unsigned char *d, unsigned int n) {
  int i;
  for (i=0; i<4; i++) {
    *d++ = (unsigned char)n;
    n >>= 8;
  }
}

/**************************************************************/
void MusicPlayer::recording(char *recfile) {
    unsigned long fileSize = 0;
    unsigned int n;

    VS1053.writeRegister(SPI_BASS, 0x0055);    //set accent
    VS1053.writeRegister(SPI_AICTRL0,8000);    //samplerate 8k
    VS1053.writeRegister(SPI_AICTRL1,0);       //record gain
    VS1053.writeRegister(SPI_AICTRL2,0);       //Set the gain maximum,65536=64X
    VS1053.writeRegister(SPI_AICTRL3,6);       //PCM Mode ,left channel
    VS1053.writeRegister(SPI_CLOCKF,0x2000);   //set clock

    VS1053.writeRegister(SPI_MODE,0x1804);   //mic,Initialize recording
    delay(2);

    VS1053.loadPlugin(recPlugin,sizeof(recPlugin)/sizeof(recPlugin[0]));

    SPI.setClockDivider(SPI_CLOCK_DIV2);
    file.remove(&root,recfile);

    //if(file.open(&root,recfile,O_WRITE|O_CREAT) == NULL)
    if(!file.open(&root,recfile,O_WRITE|O_CREAT))
    {
        Serial.println("Rec open fail");
        return;
    }
    playingState == PS_RECORDING;
    Serial.println("Recording ...");

    while(playingState != PS_PAUSE)
    {
        if ((n = VS1053.readRegister(SPI_HDAT1)) > 0)
        {
                //Make little-endian conversion for 16-bit PCM .WAV files
               for (char i=0; i<n;i++) {
                   unsigned int w = VS1053.readRegister(SPI_HDAT0);
                   file.write((unsigned char)(w & 0xFF));
                   file.write((unsigned char)(w >> 8));
                }
               fileSize += 2*n;
        }
    }
        /* Update file sizes for an RIFF PCM .WAV file */
        file.seekSet(0);
        Set32(pcmHeader+4, fileSize-8);
        Set32(pcmHeader+40, fileSize-36);
        file.write(pcmHeader, sizeof(pcmHeader));
        file.close();

        /* Finally, reset the VS10xx software, including realoading the
             patches package, to make sure everything is set up properly. */
        VS1053.softReset();
}

/**********************************Midi Player Part***************************/
void MusicPlayer::beginMidi(void)
{
  //Init VS105B in Midi Format
  Serial.print("Init vs10xx in MIDI format...");
  VS1053.initForMidi();
  Serial.print("done\r\n");
}

void MusicPlayer::midiWriteData(char cmd, char high, char low)
{
  while(!digitalRead(VS_DREQ));
  digitalWrite(VS_XDCS, LOW);
  midiSendByte(cmd);
  if((cmd & 0xF0) <= 0xB0 || (cmd & 0xF0) >= 0xE0)
  {
    midiSendByte(high);
    midiSendByte(low);
  }
  else
  {
    midiSendByte(high);
  }
  digitalWrite(VS_XDCS, HIGH);
}

void MusicPlayer::midiNoteOn(char channel, char note, char rate)
{
  midiWriteData((0x90 | channel), note, rate);
}

void MusicPlayer::midiNoteOff(char channel, char note, char rate)
{
  midiWriteData((0x80 | channel), note, rate);
}

void MusicPlayer::midiSendByte(char data)
{
  SPI.transfer(0x00);
  SPI.transfer(data);
}

void MusicPlayer::midiDemoPlayer(void)
{
  delay(1000);
  midiWriteData(0xB0, 0x07, 170);   //channel volume

  //GM2 Mode
  Serial.print("Fancy Midi Sounds\r\n");
  midiWriteData(0xB0, 0, 0x78);     //Bank select drums
  for(int instrument = 30 ; instrument < 31 ; instrument++)
  {
    Serial.print(" Instrument: ");
    Serial.println(instrument, DEC);

    midiWriteData(0xC0, instrument, 0);    //Set instrument number. 0xC0 is a 1 data byte command

    //Play notes from F#-0 (30) to F#-5 (90):
    for (int note = 27 ; note < 87 ; note++)
    {
      Serial.print("N:");
      Serial.println(note, DEC);
      //Note on channel 1 (0x90), some note value (note), middle velocity (0x45):
      midiNoteOn(0, note, 127);
      delay(50);

      //Turn off the note with a given off/release velocity
      midiNoteOff(0, note, 127);
      delay(50);
    }

    //delay 100ms between each instruments
    delay(100);
    }
}

This class loops over sd card and plays all of the sounds. but I only want to have a function to play a single file. So I added this function
void MusicPlayer::play(char * path)
{

    unsigned char bytes;        // How many bytes in buffer left
    unsigned char n;

    SPI.setClockDivider(SPI_CLOCK_DIV2);
    if(file.open(&root,path,O_READ))
    {
        Serial.print("Playing ");
        //Serial.println(list[songIndex].name);
    }
    else
    {
        Serial.print("Could not open: ");
        //Serial.println(list[songIndex].name);
        //songIndex ++;
        return;
        //while(1);
    }

    playingState = PS_PLAY;
    while(bytes = file.read(fileBuf,sizeof(fileBuf)))
    {
        // actual audio data gets sent to VS10xx.
        VS1053.writeData(fileBuf,bytes);

        switch (playingState)
        {
            case PS_PLAY:
                switch(ctrlState)
                {
                    case CS_UP:
                        Vol += 10;
                        if (Vol > MaxVol)Vol = MaxVol;
                        VS1053.writeRegister(SPI_VOL, Vol*0x101);     //Set volume level
                        ctrlState = CS_EMPTY;
                        break;
                    case CS_DOWN:
                        Vol -= 10;
                        if (Vol < 0)Vol = 0;
                        VS1053.writeRegister(SPI_VOL,Vol*0x101);      //Set volume level
                        ctrlState = CS_EMPTY;
                        break;
                    case CS_NEXT:
                        //if (++songIndex > MaxSong)songIndex = 0;
                        //file.close();
                        //VS1053.softReset();
                        ctrlState = CS_EMPTY;
                        return;
                    case CS_PREV:
                        //if (--songIndex < 0)songIndex = MaxSong;
                        //file.close();
                        //VS1053.softReset();
                        ctrlState = CS_EMPTY;
                        return;
                    default:
                        break;
                }
                break;
            case PS_PAUSE:
                while(playingState == PS_PAUSE);         //Pause
                break;
            case PS_RECORDING:
                file.close();
                VS1053.softReset();
                return;
        }

    }
    file.close();
    VS1053.softReset();
    Serial.println("[done!]");
    //songIndex++;

}

if I compile the above class with this addition function it will compile but I have no idea if I upload it on arduino it harms the device or not, Does this code works or no?
thanks

I cannot find anything, that would harm your Uno or shield. When I were in your position, I would simply try, since you haven't changed much from the original play function. But as Look Alterno wrote, if there is a datasheet for your shield, you should also look into it.


text:
Arduino Editor: Monitor menu show "Serial port unavailable"
Ubuntu 16.04LTS 64bit, Arduino Pro Mini board (ATmega 328P, 3.3V 8Mhz)
I have problem with WEB editor: I selected Arduino Pro mini and ticked "8Mhz ATmega 328P". I tried to upload "blink" test program from Examples, but Web editor show "Error uploading, check if selected board is currently available." And Monitor menu show "Serial port unavalable".
$ dmesg | grep tty
[    0.000000] console [tty0] enabled

I tried to reboot, not help. The green LED on Arduiono is "on" and red LED is blinking. I tried to verify the built-in COM port, in terminal run command    dmesg | grep FTDI, but no any output returned.
$ ls -l /dev/ttyUSB*
ls: cannot access '/dev/ttyUSB*': No such file or directory

It looks that FTDI USB to Serial port converter not recognized on Ubuntu?

I've had this in Windows before now. There, I was able to resolve it by reinstalling the driver from device manager. I don't have an Ubuntu box with me so can't test the steps for Ubuntu yet. I'll try later, but let me know if this works in the meantime.

This guide was for Ubuntu 13.04. I'm working from a mobile phone screen, so I couldn't find a more current guide.

What are you uploading through? The Pro Mini has no USB interface of its own.

Mini Pro connected via FTDI USB to Serial converter Breakout (FT232RL).

I believe, the FTDI drivers already have been built in Ubuntu, not?

Have you tried a different cable?

Tried another cable, FTDI adapter now recognized, $ ls -l /dev/ttyUSB* return
crw-rw---- 1 root dialout 188, 0 Aug 26 19:45 /dev/ttyUSB0. But Serial port is still grayed out.

And have you added yourself to the dialout group as per the Linux Arudino instructions?

I missed that, after adding user to the group 'dialout', the serial port is now enabled. sudo usermod -a -G dialout username. Thanks a lot!

type "tail -f /var/log/kern.log" into a terminal window. This will show you the messages that the kernel produces. Hit enter a few times so you can easily see when something new is added.
Now remove (hmm. easier if you do that before typing the command above).  and insert the arduino. Now your kernel should produce a few messages stating it found a new device. Linux has drivers for all popular USB chips so no driver issues expected.
With a bit of luck you'll see something like:
   Aug 27 18:53:23 kernel: usbcore: registered new interface driver ch341
   Aug 27 18:53:23 kernel: usb 3-3: ch341-uart converter now attached to ttyUSB0
What comes after "now attached to" is what you need to use for the serial port....

Do a ls -l /dev/tty* in a console screen and then search for the tty* port that your arduino is connected to (mine is ttyACM0), you will see which group (my group is dialout for Ubuntu 17.10) you need to add yourself to in order to be able to access your arduino via the Serial Monitor.


text:
can Arduino IDE link to other libs / files in other directories?
can Arduino IDE point to a file in another directory? If yes how?
With my code
../../main.h

the compile fails.
Error:
In file included from D:\Eigene Dateien\Entwicklung\SIGNALDuino_MR\src\arduino-ide\SIGNALDuino\SIGNALDuino.ino:1:0:

main.h:1:1: error: expected unqualified-id before '.' token

 ../../main.h

 ^

exit status 1
expected unqualified-id before '.' token

--------------- structure ------------------
TEST
  |--main.h
  |-----Ordner 1
             |-----Ordner 3
                       |--files.h
  |-----Ordner 2
             |-----Ordner 4

#include "../../main.h"

No it doesn't work. The file exists in the directory (2 times back in the structure)
:-( `#include "../../main.h"
                    ^

compilation terminated.
exit status 1
../../main.h: No such file or directory`

I  didn't expect it to work. the Arduino IDE builds the sketch in a temporary folder, not in the sketch folder. but to include the #iinclude directive is the only possible syntax

But he should read the file from there :-( No absolute position should be given. The file is 2 levels up.

it is not two levels up from the temporary folder

to avoid misunderstandings, it is a path \ src \ which has the first main.h. This contains the structure \ arduino-ide \ project \ where the main.h file is located. This should call the "first" main.h.

The answer is in the wrong direction. The user wants from MCUa.ino in TimerLib.h.
But my plan is backwards. Jump back directories. Based on the example, from TimerLib.h to MCUa.ino

it is the same question as yours. include in sketch something on relative path

it does not work #include ../../main.h or  #include "../../main.h"

read the answer to the other question.


text:
ESP8266, sporadically no write access to the file system
I have an ESP8266 project which reads my gas consumption. The hardware and the project run satisfactorily. Sporadically, the ESP8266 can no longer write to its file system and therefore cannot save any data. As soon as I upload the complete data and the sketch to the device again, it works for a few months. After that, the mistake occurred again and again. What could that be?
The ESP8266 then has an "Exception" error. Unfortunately, I have not yet been able to find the reason for the error, why it always happens.
Does anyone have a tip on how I can isolate the problem?
https://github.com/HomeAutoUser/ESP-Gaszaehler-GZ16/tree/pre-release_v1.91

what is what you write? configuration or log files? if you upload the data does it contain the files with logged data? isn't the file system simply full?

does https://github.com/me-no-dev/EspExceptionDecoder give you any more info about what's exploding? Does rebooting once a day fix it?

The link is now revised.

I have faced the same issue with my water leak detector, based on esp8266. It was caused by memory leak in the ESP binaries, so, I've updated it to ver 2.6.3
So, you can try to log (print to serial) free memory amount:
extern "C"
{
    #include "user_interface.h"
}
uint32_t free = system_get_free_heap_size();

Thanks for the answer. I now have the problem that it can be compiled with the Core 2.5.2 but not with the Core 2.6.3.
I added the code above.
Suddenly a variable should not be declared.
exit status 1 StaticRequestHandler has not been declared

The line 'extern "C" {
#include "user_interface.h"
}' is in code already in.

the memory leak was with WiFiClient in 2.4.1 2 years ago

@Juraj, okay, so, any other ideas?


text:
Is it possible to program Arduino in transpiled JavaScript?
Coming from JS, I find it very difficult to program Arduino in C++ (not even knowing which version or what features are supported), being bound to the loop and delay, not being able to (easily) use anonymous functions in parameters or async code.
I know JS isn't natively supported by Arduino, but I know languages can be transpiled.
I have seen many solutions, so just to pick few:
JohnnyFive J5, which runs via cable on a host PC,
NectarJS with their arduino-uno target,
or andrei-markeev/ts2c which converts ES3 to C89.
Each of them come with their own limitations and it's very difficult to find the right without prior experience with IoT. Did anyone walk this path already and found a viable solution?

Forgive me if this question is inappropriate for this site. This is my first Q here and I am totally new to IoT. However, outright downwoting, without providing a feedback isn't really constructive and welcoming to new members.

I suggest you look at the boards and components that are supported by these frameworks before you commit to any one. Maybe start here, http://johnny-five.io/api and see if the supported components will cover what you are trying to achieve.

my recommendation is, learn C++

Just dive in and learn C++ while you go. You could also try learning Python so you can program your Teensy in Circuitpython or Micropython (although I now see it might not be easy to get it going on the Teensy).

Even if such a transpiler exists (which I don‘t know) you will still have to deal with the loop structure and the fact that you should avoid using delays. On a microcontroller you have to forget about things like multithreading and even dynamic memory allocation should be used carefully.
Most of those things that make a programmer‘s life easy on bigger systems are usually paid with ram or cpu power, but on a microcontroller with some kB RAM there are only few resources to pay with.
So my recommendation is to learn C++ instead of looking for ways to convert code from another language, which will probably introduce its own problems. You‘ll soon find yourself one layer below and there are exciting things that higher languages hide from you.

Is it possible that some of the C++ constructs are valid, but not working specifically on IoT devices? (In my case the Teensy LC or 3.2.)

With JavaScript, you don't use delay(), nor multithreading: you do non blocking programming, in a single thread running an event loop. That's exactly the approach you would use in C++ on a microcontroller.

andrei-markeev/ts2c JavaScript/TypeScript to C transpiler looks promising.
I'll probably give it a go tonight.
According to the github page:
Produces readable C89 code from JS/TS code.
For example, this JavaScript:
console.log("Hello world!");

transpiles to the following C code:
#include <stdio.h>

int main() {
    printf("Hello world!\n");
    return 0;
}

src: https://github.com/andrei-markeev/ts2c

Why don't you just start with a microcontroller that supports Javascript?
I find the Adafruit Circuit Playground Express quite fun to work with. You can still connect sensors and other hardware, the same as you can do with Arduino. It also has a bunch of sensors built-in.
You can try it out right now without owning a hardware board at adafruit.makecode.com. Click the Javascript tab on the top of the page.
Using a JS>Arduino transpiler will probably cause a lot of headache, since it often won't do what you expect it to do.

I bought the Teensy specifically because it's best for HID. I want to repurpose an old keyboard, but if I were to do something larger, I would probably choose a board that supports node.js and JavaScript.

There aren't any boards that support node.js sadly. You can run Johnny Five with almost every board, but that runs on your PC. It allows you to read the board through the USB cable.

I had to put the project away for a while, but now that I think of that... The keyboard must be connected to the PC anyway, so I can as well run nodejs to control it. Johny Five may be the best solution for hacking after all. After the PoC works, I may rewrite it in C++.


text:
Problems recycling c++ lib with templated class for Arduino
I have a header & cpp file located in Arduino\libraries\Parentfolder\Header&Cpp. Arduino IDE recognizes my lib (the class is color coded & Sketch->include library->MyLibrary shows in the dropdown menu and #includes properly).
Problem: Arduino IDE gives undefined reference to MyClass . . . error in my sketch for every reference of the class including function calls. The function fully in other IDEs as header/cpps so I don't think pasting the cody is necessary -- what could I be missing? I've read a million Stack Exchange posts with similar error/watched a million YouTube guides on writing Arduino libs and I can't seem to find the differentiating factors that would make my code not work for Arduino IDE.
tl;dr what are the reasons that a working c++ library (self-made) would not work with Arduino IDE?
/e
Queue.h
#ifndef Queue_h
#define Queue_h

#include "Arduino.h"

template <typename T>
class Queue
{
  public:
    typedef struct node
    {
      T data;
      node * next = nullptr;
    } * nodePtr;

    nodePtr head; // = nullptr;
    nodePtr tail; // = nullptr;
    nodePtr curr; // = nullptr;
    nodePtr temp; // = nullptr;

    unsigned int counter;

    Queue();
    void push(T);
    T& peek();
    T pop();
    int size();
    bool isEmpty();
    void clear();
};

#endif

Queue.cpp
#include "Arduino.h"
#include "Queue.h"

template <typename T>
Queue<T>::Queue()
{
    nodePtr head = nullptr;
    nodePtr tail = nullptr;
    nodePtr curr = nullptr;
    nodePtr temp = nullptr;

    counter = 0;
}

template <typename T>
void Queue<T>::push(T data)
{
  if (head == nullptr)
  {
    head = new node;
    head->data = data;
    tail = head;
  }
  else
  {
    temp = head;
    head = new node;
    head->data = data;
    head->next = temp;
  }
  counter ++;
}

template <typename T>
T& Queue<T>::peek()
{
  if (head == nullptr)
  {
    return 0;
  }
  return head->data;

}

template <typename T>
T Queue<T>::pop()
{
  // Empty
  if (head == nullptr)
  {
    return 0;
  }

  // Head = tail
  if (head == tail)
  {
    T data = head->data;
    delete head;
    return data;
  }

  // Size > 1
  curr = head;
  while (curr->next != tail)
  {
    curr = curr->next;
  }
  T data = curr->next->data;
  tail = curr;
  curr = curr->next;
  delete curr;
  counter --;
  return data;
}

template <typename T>
int Queue<T>::size()
{
  return counter;
}

template <typename T>
bool Queue<T>::isEmpty()
{
  if (counter ==0)
  {
    return true;
  }
  return false;
}

template <typename T>
void Queue<T>::clear()
{
  while (head->data != nullptr)
  {
    temp = head->next;
    delete head;
    head = temp;
  }
  if (head == nullptr)
  {
    return;
  }
  delete head;
  return;
}

.ino
. . .
Queue<float> avgQueue;
. . .

error
. . . In function `__static_initialization_and_destruction_0':
. . . undefined reference to `Queue<float>::Queue()'

SOLVED:
Combining the .cpp contents in the .h and removing the .cpp worked.

Please post a Minimal, Complete, and Verifiable example. Do you have a single sketch file, or have you broken your code into multiple files (eg. cpp/h files)?

The header and cpp are in the forementioned subfolder which is inside of the Arduino library folder. The errors come from a simple sketch meant only to test the (already-working-in-other-IDEs) library.

one thing that jumps out is the ampersand & in the path ... maybe the compiler does not like it

That's not the real path, that's just me saying that both the header&cpp are there.

SOLVED:
Putting the .cpp contents in the .h and removing the .cpp from the lib folder entirely worked.

Yes, tempates are instantiated on demand so you have to have complete class inside of header. However I wonder how the pop works if you have the last element. Your head wasn't set to the nullptr - and delete can't do that for you.

Your code doesn't totally prove the problem, however libraries are not included unless you include them in the .ino file which might be your underlying issue.

This, for example, is not complete code: . . . Queue<float> avgQueue; . . .

@NickGammon fortunately I'm not that much of a noob! The lib was included and everything is now functioning well as a result of the above workaround

I'm glad it is working, however I'm not sure what you did exactly (that didn't work) and what you did (that did work). However this looks relevant.


text:
How do i run multiple functions simultaneously on a LCD screen?
I have little to no experience in programming and i'm very slowly and gradually getting the hang of it. My next project is that i'm making a clock, and wanted to use multiple functions for the hour:minute:seconds instead of just using one for everything. But after reading some i came to the conclusion that the arduino can only run one function at a time. So my question is how can i make the illusion of multiple functions running simultaneously on a LCD screen.
My code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

int lcd_key     = 0;
int adc_key_in  = 0;
#define btnRIGHT  0
#define btnUP     144
#define btnDOWN   329
#define btnLEFT   504
#define btnSELECT 741
#define btnNONE   5

int read_LCD_buttons()
{
 adc_key_in = analogRead(0);

 if (adc_key_in > 1000) return btnNONE;
 if (adc_key_in < 50)   return btnRIGHT;
 if (adc_key_in < 195)  return btnUP;
 if (adc_key_in < 380)  return btnDOWN;
 if (adc_key_in < 555)  return btnLEFT;
 if (adc_key_in < 790)  return btnSELECT;
 return btnNONE;

}
unsigned long minInterval = 60000UL; // Interval for minutes in milliseconds
unsigned long secInterval = 1000UL;  // Interval for seconds in milliseconds
unsigned long prevMinMillis = 0UL;   // Holds the timestamp of the last time Minute() was called
unsigned long prevSecMillis = 0UL;   // Holds the timestamp of the last time Second() was called

void setup()
{
 lcd.begin(16, 2);
}

void loop()
{
  unsigned long currentMillis = millis();

  if (currentMillis - prevMinMillis > minInterval)
  {
    prevMinMillis = currentMillis;
    Minute();
  }

  if (currentMillis - prevSecMillis > secInterval)
  {
    prevSecMillis = currentMillis;
    Second();
  }

}

void Second(){
  int First_Digit = 0;
  int Second_Digit = 0;

  for(Second_Digit; Second_Digit<10; Second_Digit++){
    if(Second_Digit==10){
      First_Digit = First_Digit + 1;
      }

    lcd.setCursor(0, 0);
    lcd.print(First_Digit);
    lcd.setCursor(1, 0);
    lcd.print(Second_Digit);
    lcd.clear();

    if(First_Digit==5 && Second_Digit==9){
      First_Digit = First_Digit - 5;
      Second_Digit = Second_Digit -10;

      }
    if(Second_Digit==9){
      First_Digit = First_Digit + 1;
      Second_Digit = Second_Digit - 10;
      }

  }
}
void Minute(){
  int First_Digit = 0;
  int Second_Digit = 0;
  for(Second_Digit; Second_Digit<10; Second_Digit++){
    if(Second_Digit==10){
      First_Digit = First_Digit + 1;
      lcd.print(First_Digit);
      }

    lcd.setCursor(3, 0);
    lcd.print(First_Digit);
    lcd.setCursor(4, 0);
    lcd.print(Second_Digit);
    lcd.clear();

    if(First_Digit==5 && Second_Digit==9){
      First_Digit = First_Digit - 5;
      Second_Digit = Second_Digit -10;
      lcd.print(First_Digit);

      }
    if(Second_Digit==9){
      First_Digit = First_Digit + 1;
      lcd.print(First_Digit);
      Second_Digit = Second_Digit - 10;
      }

  }
}

You ought to be able to write to specific positions on the LCD by specifing setCursor() as you have. Is this not working? If not, please describe what it displays, and what you want to see it display?

imagine that you are cooking a pot of stew and a pot of soup.  you have to stir the stew every 10 minutes and you have to stir the soup every 15 minutes.  you have a clock that displays time and beeps every minute. what process do you use for that scenario if you have other things to do? (your LCD program will do something very similar)

@josecanuc It's only showing the Second() function on the first line and nothing else, i want to see the Minute() function beneath that on the second line.

@jsotola i think you're referring to the millis() command which shows the amount of milliseconds that have passed after you start a program. But how could i integrate that in my code so that it seems like they're both shown on the lcd simultaneously.

Examine closely the non-popular-enough Arduino example called BlinkWithoutDelay https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay  Your problem is that the use of delay() as you guessed. You need to think about your program flow as though loop() runs millions of times per second, but you only want to execute a particular function less frequently. Expand to running multiple functions at different frequencies.

@josecanuc But a function can't have a high or low state, it's not attached to a pin so how would i translate that example to printed values? Sorry that i'm terrible at this but thanks anyway for your patience.

See my answer -- but the digitalWrite() call in the BlinkWithoutDelay example is a function call, not a pin.

@josecanuc It's still not functioning properly and i have absolutely no idea what i can do, all i can see now is that there are number, rapidly changing. i've integrated your code into mine but i can't for the life of me find the solution, i've tried tinkering with the Blink Without Delay and all it did was make me feel more stupid :D.

Do you understand how BlinkWithoutDelay works, and how it's different from the standard Blink? Do you understand why? Update your question to show your new code that's still not working.

Yes instead of using delay, which pauses the program. it uses millis and if the millis exceeds the interval it changes the value of the pin from either high to low or low to high. it does this every second because the currentMillis gets larger everytime but so does the previousMillis so that it needs another 1000 milliseconds before it can run the if statement again. The ledpin and ledstate i don't fully understand because i'm terrible at hardware. Neither do i understand the digitalwrite but i thought it was unnecessary for my sketch. I'll upload all of my code this time.

My answer updated to reflect the new code sample.

Use the state machine model shown in BlinkWithoutDelay
unsigned long minInterval = 60000UL; // Interval for minutes in milliseconds
unsigned long secInterval = 1000UL;  // Interval for seconds in milliseconds
unsigned long prevMinMillis = 0UL;   // Holds the timestamp of the last time Minute() was called
unsigned long prevSecMillis = 0UL;   // Holds the timestamp of the last time Second() was called

void setup()
{
 lcd.begin(16, 2);
}

void loop()
{
  unsigned long currentMillis = millis();

  if (currentMillis - prevMinMillis > minInterval)
  {
    prevMinMillis = currentMillis;
    Minute();
  }

  if (currentMillis - prevSecMillis > secInterval)
  {
    prevSecMillis = currentMillis;
    Second();
  }

}

With this example, Second() is called only when the difference between "now" and the last time it was called is greater than secInterval. Likewise for Minute().
[Note, the code above will not run as-is, but I assume you have initialized the LiquidCrystal library and assigned the pins as per your schematic.]
EDIT BASED ON UPDATED CODE SAMPLE
Issue 1:
In both your Minute() and Second() functions you have a sequence like:
lcd.setCursor(0, 0);
lcd.print(First_Digit);
lcd.setCursor(1, 0);
lcd.print(Second_Digit);
lcd.clear();

After writing the characters, you immediately clear the LCD screen. Don't do this, it erases all the output on your LCD.
Issue 2:
At the start of the Minute() function, you have the following:
int First_Digit = 0;
  int Second_Digit = 0;
This means the variables First_Digit and Second_Digit are initalized to zero every time the function is called. This means you won't get an increment of the value, it will start at zero every time you try to update the LCD. You can declare those variables as static so that the value remains the same between calls of the function. Static variables are automatically initialized to zero. Thus:
static int First_Digit;
static int Second_Digit;

and similarly in the Second() function.
You're correct that digitalWrite() is not needed in your function as it is described. digitalWrite() is for changing a physical pin on the Arduino to a LOW or HIGH value (that is, a 0V or 5V voltage.) In the Blink without Delay example, ledPin and ledState are just variables to hold the pin identifier for the blinking LED, and the current state (LOW or HIGH) of that pin. Again, not necessary for your code, as you have described it.
SECOND UPDATE
Having tackled the issue of how to run multiple functions "simultaneously", now move on to fixing the overly complicated code for writing the minute and second values to the LCD... I'm not sure why you put the for loop in the Minute() and Second() functions, but it's unnecessary.
You also are treating each digit way too complicated. If your value for the seconds counter is 0 to 59, why not keep track of it that way, and then display each digit as necessary:
void Second() {
  static int second;

  second++;
  if (second>59) {
    second = 0;
  }
  lcd.setCursor(0, 0);
  lcd.print(second/10);   // Prints the 10s digit
                          // Note, lcd.print automatically moves to the next column
  lcd.print(second % 10); // Prints the remainder after dividing by 10
}

void Minute() {
  static int minute;

  minute++;
  if (minute>59) {
    minute = 0;
    // Probably want to increment an Hour counter here?
  }
  lcd.setCursor(3, 0);
  lcd.print(minute/10);   // Prints the 10s digit
                          // Note, lcd.print automatically moves to the next column
  lcd.print(minute % 10); // Prints the remainder after dividing by 10
}

After updating my code i only get what it seems like the function Second, furthermore it's unreadable untill i reset it so that it stops for a moment, and then it shows the correct seconds. So it works but it's unreadable until you stop it. Any solutions to this?

Added another part of this answer to deal with the other functions, which are not strictly related to how to run multiple functions simultaneously...

It works properly for each individual part but the hour only shows after an hour and the minute only shows after a minute, how can i display this instantly?

Write the hour and minute in setup() so they run at least at startup


text:
Operating AD5780 EVAL Board Via MicroController
OK, so thanks in advance because I am new here. I am reading the AD57XX drivers here  https://wiki.analog.com/resources/tools-software/uc-drivers/renesas/ad5780 and am struggling to understand how to get the device working and understanding it properly.
I am using code here https://github.com/maxgerhardt/arduino-ad57xx-driver/blob/master/src/main.cpp in order to test the DAC. I have several questions about the drivers and operation in general. I will itemize them if that is ok

Where in the drivers am I performing Slave Select and where am I determining Clock Speed? I have looked through the C in the drivers library, and it seems that each command, whether reading or writing selects the Slave/Master each time? I see no reference to which pins on my microcontroller it is reference though so I do not know if any of this is right.
Why do I need to be reading in the Control Register or anything from the DAC at all? Why does this matter? All I want is to output a voltage
How do I perform the right conversion to a voltage that I want? The command " AD57XX_SetDacValue() " takes a long, but I do not understand how that relates to a float value of voltage. Say I want 2.35 Volts, or a Sine Function from -2 to 2 Volts, how do I do this conversion?
I don't know how to debug the system in general. When I run the example code, which is supposed to output a triangle wave function, I get a sin function, which seems to just be noise.

In my experience analog devices eval board software is crap, I've had a few that I couldn't even get working with their software. I eventually layed out my own board with microprocessor.

@laptop2d Do you have any suggestions / alternatives of how to get the DAC running? I can't find proper githubs of this running and I'm a little pannicked

Note for readers interested in this topic: The same question has been asked at the Analog Devices "EngineerZone" here. Therefore answers / new information / etc. may appear there.

I use the AD5780, but with a STM32 on my own board. What I would do is write my own code for the eval board if you can find a way to program it.

@laptop2d Do you have documented code you use for the STM32? I understand there will be differences, but any reference for me is useful? I'm not competent enough to really write my own drivers

Where in the drivers am I performing Slave Select and where am I determining Clock Speed? I have looked through the C in the drivers library, and it seems that each command, whether reading or writing selects the Slave/Master each time? I see no reference to which pins on my microcontroller it is reference though so I do not know if any of this is right.

The slave select is controlled within the SPI_Write() function.  It uses the PinMgt_PinWrite() function to do the slave select control, which in turn selects a pin from the pinMapping[] lookup table.
The clock speed is set in AD5780_Init().

Why do I need to be reading in the Control Register or anything from the DAC at all? Why does this matter? All I want is to output a voltage

You don't. The code is just for demonstration purposes. It shows you how you could query those registers. If you don't need to, then don't.

How do I perform the right conversion to a voltage that I want? The command " AD57XX_SetDacValue() " takes a long, but I do not understand how that relates to a float value of voltage. Say I want 2.35 Volts, or a Sine Function from -2 to 2 Volts, how do I do this conversion?

That value is the raw value to set the DAC to. You refer to the DAC datasheet to know what that value equates to.  In this case the range is from \$V_{REFN}\$ to \$V_{REFP}\$.  Divide that range by 218 and you have the voltage per bit.

I don't know how to debug the system in general. When I run the example code, which is supposed to output a triangle wave function, I get a sin function, which seems to just be noise.

You need some debugging tools. Things like a logic analyser to be able to acually see what the IO pins of your MCU are doing.  An oscilloscope can be used to see if a signal is present, but to see all the SPI signals together you really want a logic analyser.

Thank you for responding. I understand the equation for the raw value. I understand if I send 0x3FFFF (18 1's, I would get the maximum value). What I dont understand is that the command AD57XX_SetRegisterValue and AD57XX_SetDacValue both use "unsigned longs" but then the code just stores binary inside these longs instead? When I adapt that code to just send  AD57XX_SetDacValue(0x3FFFF) I don't get 10 Volts coming out

I have read the datasheet over and over again, I don't mean to appear lazy, but it doesn't seem to be helping me

but then the code just stores binary inside these longs instead? -- What is that supposed to mean?

Also in the pinMapping[] doesn't have MOSI, MISO, or SCK, how is this supposed to work?

MOSI, MISO and SCK are the SPI hardware pins. You have no control over them. The SPI hardware controls them.

Isn't a long a integer value? Why is it sending in 0x3FFFF ? I know I should be sending in 18 bits, but I don't understand why the command asks for a long

A long is a 4-byte area of memory for storing information in.  We choose to use base 10 to represent the value that is stored in that memory. You could just as well use (as you do there) base 16. It's all just base 2 (binary) in memory anyway.

Could I be following some tutorial or other github repo or something for this? Without any formal EE experience I'm pretty lost and don't know how to do anything really.


text:
Encrypting data between NRF24L01 using AES
I am trying to send encrypted data using AES  via a pair of NRF24L01 and two Arduino Uno boards. I have made two sketches but can not get it working.
The used library for AES:
enter link description here
Transmitter code:
// TrackControl - the master or the transmitter

 // http://tmrh20.github.io/RF24/

 //~ - CONNECTIONS: nRF24L01 Modules See:
 //~ http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
 //~ 1 - GND
 //~ 2 - VCC 3.3V !!! NOT 5V
 //~ 3 - CE to Arduino pin 9
 //~ 4 - CSN to Arduino pin 10
 //~ 5 - SCK to Arduino pin 13
 //~ 6 - MOSI to Arduino pin 11
 //~ 7 - MISO to Arduino pin 12
 //~ 8 - UNUSED

#include <SPI.h>
//~ #include <TMRh20nRF24L01.h>
//~ #include <TMRh20RF24.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <AESLib.h>

#define CE_PIN   9
#define CSN_PIN 10
uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};

// NOTE: the "LL" at the end of the constant is "LongLong" type
// These are the IDs of each of the slaves
const uint64_t slaveID[2] = {0xE8E8F0F0E1LL, 0xE8E8F0F0E2LL} ;

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

char  dataToSend[]="123456789012345";

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000;
int txVal = 0;
float ackMessg[2]={1,2};
byte ackMessgLen = 4; // NB this 4 is the number of bytes in the 2 ints that will be recieved

void setup() {

    Serial.begin(9600);
    Serial.println("Track Control Starting");
    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.enableAckPayload();
    radio.setRetries(10,5); // delay, count
}

//====================

void loop() {

    currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {

    radio.openWritingPipe(slaveID[0]); // calls the first slave
                                        // there could be a FOR loop to call several slaves in turn
    aes256_enc_single(key, dataToSend);

    bool rslt;
    rslt = radio.write( dataToSend, sizeof(dataToSend) );
    Serial.print("\nRSLT (1 = success) ");
    Serial.println(rslt);

    if ( radio.isAckPayloadAvailable() ) {
        radio.read(ackMessg,ackMessgLen);
        Serial.print("Acknowledge received: ");
        Serial.print(ackMessg[0]);
        Serial.print("  ");
        Serial.println(ackMessg[1]);
    }
    prevMillis = millis();
 }
}

Receiver code:
// HandController - the slave or the receiver

    // http://tmrh20.github.io/RF24/

    //~ - CONNECTIONS: nRF24L01 Modules See:
    //~ http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
    //~ 1 - GND
    //~ 2 - VCC 3.3V !!! NOT 5V
    //~ 3 - CE to Arduino pin 9
    //~ 4 - CSN to Arduino pin 10
    //~ 5 - SCK to Arduino pin 13
    //~ 6 - MOSI to Arduino pin 11
    //~ 7 - MISO to Arduino pin 12
    //~ 8 - UNUSED

#include <SPI.h>
//~ #include <TMRh20nRF24L01.h>
//~ #include <TMRh20RF24.h>
#include <nRF24L01.h>
#include <RF24.h>

#include <AESLib.h>

#define CE_PIN   9
#define CSN_PIN 10

// NOTE: the "LL" at the end of the constant is "LongLong" type

const uint64_t   deviceID = 0xE8E8F0F0E1LL; // Define the ID for this slave
uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};

int valChange = 1;

RF24 radio(CE_PIN, CSN_PIN);

char  dataReceived[32];
int ackData[2] = {12,23};

void setup() {

    Serial.begin(9600);
    delay(1000);
    Serial.println("Hand Controller Starting");
    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.openReadingPipe(1,deviceID);
    radio.enableAckPayload();
    radio.writeAckPayload(1, ackData, sizeof(ackData));
    radio.startListening();
}

void loop() {

    if ( radio.available() ) {
        radio.read( dataReceived, sizeof(dataReceived) );
        radio.writeAckPayload(1, ackData, sizeof(ackData));
         for (int x = 0; x <32; x++) {
      //if (dataReceived[x] < 16) {
      //  Serial.write('0');
    // }

    //  Serial.print(dataReceived[x]);}
    // Serial.println();

        ackData[0] += valChange; // this just increments so you can see that new data is being sent
    }
   aes256_dec_single(key, dataReceived);
    Serial.println("decrypted:");
    Serial.println(dataReceived);
}}

I cannot receive the same message after decryption.

attach your output here so we have better understanding what is the issue.

i got strange characters at the receiver side
when i test AES encryption/decryption a lone without nRf24l01 i receive the input data normally after decryption
when i use nRF24l01 without encryption decryption i receive the sent data on the receiver side normally

aes256_dec_single requires dataToSend to be 256 bits as-well. From what I know, AES only works on multiples of block sizes. It can't handle variable length data. The way to work around that is to pad the data with, for example, zeros, till it's a multiple of the block size.

I still think serial terminal output will help us for better understanding.


text:
Storing hash values from SHA256
I am using this code and I can not save the output of the hash function to an array of char. Can you help me how to do that?
#include "sha256.h"
#include <Arduino.h>
#include "./printf.h"

void printHash(uint8_t* hash) {
  int i;
  for (i=0; i<32; i++) {
    Serial.print("0123456789abcdef"[hash[i]>>4]);
    Serial.print("0123456789abcdef"[hash[i]&0xf]);
  }
  Serial.println();
}

void setup()
{ String FinalStr="1234567890";
Sha256.init();
  Sha256.print(FinalStr);
  printHash(Sha256.result());
}
void loop()
{

}

instead of printing it, put it in an array of char - you'll need an array 64 long of course

hello jaromanda,thank u for ur suggestion,i can not copy from the output of printhash function

This is the code that worked for me:
#include "sha256.h"
void setup(void)
{char encoded[64];
    Serial.begin(9600);

    // this is actually the RFC4231 4.3 test

    Sha256.init();
    Sha256.print("123");
    uint8_t * result = Sha256.result();

    Serial.println("Expect: 2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881");
    Serial.print(  "Got   : ");
    for (int i = 0; i < 32; i++) {
            Serial.print("0123456789abcdef"[result[i] >> 4]);
            Serial.print("0123456789abcdef"[result[i] & 0xf]);

            for(int i = 0; i < 64; i+=2)
                {
                  encoded[i] = "0123456789abcdef"[result[i / 2] >> 4];
                  encoded[i + 1] = "0123456789abcdef"[result[i / 2] & 0xf];
                }
    }
    Serial.print("\n");
            for(int z = 0; z < 64; z++)
            Serial.print(encoded[z]);
}

void loop(void)
{}

this is the code that worked for me

Save to a character vector (64 characters + NULL):
void copyHash(char* buf, uint8_t* hash) {
  int i, j = 0;
  for (i = 0; i < 32; i++) {
    buf[j++] = "0123456789abcdef"[hash[i]>>4];
    buf[j++] = "0123456789abcdef"[hash[i]&0xf];
  }
  buf[j] = 0;
}

void setup()
{
  String FinalStr="1234567890";
  Sha256.init();
  Sha256.print(FinalStr);
  char buf[65];
  copyHash(buf, Sha256.result());
}

Cheers!

hello mikael,thank u 4 ur help,i will try and tell u the results,deeply appreciated

I have tried and got different outputs
"c775e7b757ede630cd0aa1113bd102661ab38829ca52a6422ab782862f268646
2f64612d9642afc666117f4d4fc87c17dba06ad091e1ce611f70020f2278337e"