body:
I'm literally as green of a noob as I can be at this moment. Been watching a ton of tuts as I plan my project, but can't seem to find anything about settings being uploaded from an external source, and then stored on the arduino.

I want to create a board with multiple buttons. I want these buttons to then transmit MIDI PC/CC based on customizable settings uploaded via a computer. So, I'll create an app that can "create" the settings (json?) for each button. Ideally, I'd just connect the board, create the settings, then upload it to the device.

I've been reading about storing things like this in EEPROM, but that has a limited life span (which scares me). So, do I store these variables in EEPROM, or do I just compile and upload the app that has the new values in the variables?

I'm just looking for a possible direction and links for research.

Thanks in advance.

title: How to upload and store settings/variables from computer on the arduino?

Answers: 1

body:
Your question is quite broad, so I will give you some directions for the different parts.

1. **Communication with the PC to receive settings:** For the Arduino Uno you are basically left with the Serial (UART) interface to communicate with the PC. For wired communication you can simply use the USB port. On your PC you need a program to send the settings over the serial com port to the Arduino. You can either use any serial terminal program or you can write your own. That depends on your needs. On the Arduino you need code to parse the serial communication to get the settings. It seems, that your can be rather complex (not just simple numbers of the same type). So you should implement a basic message protocol. It is common to use the newline character (`\n`) as the delimiter at the end of a message. In your code you read the serial data into a buffer, until you read a newline character. Then you start to process the message in a whole. You can see the implementation of this protocol in the `SerialEvent` example that comes with the Arduino IDE. Then you can use JSON as text based data format to transmit it to the Arduino. There you can use the Arduino JSON library to decode the data and get the settings. If you don't want to use JSON, you can also use a simpler protocol.

2. **Saving the received settings**: Without any further hardware the EEPROM is the way to go. The "life span", that you mention, are the possible number of write cycles, until a cell is not longer garanteed to work correctly. Read cycles don't do any harm here. Atmel gives a number of 100.000 write cycles, but notice, that this is the minimum garanteed number. (Have a look at [this question][1] for further info) Do you really change the settings this often? Make a short calculation like this: Imagine that you want to change the settings 10 times a day on every day in the year. Even then you get about 27 years with the EEPROM write cycles, far enough for other components to break. But if you really want to go safe here, you can use wear leveling. With this technique you rotate through different EEPROM cells to save your settings. You use more space in EEPROM, but each individual cell will get only a fraction of the write load. There are even libraries ready to use for this. A quick google search gave me the [EEPROMWearLevel][2] library, though I haven't used it myself. Depending on the total size of your settings, you might get a life span multiple times bigger with this. If you still don't want to use EEPROM, you can do as jsotola wrote in his comment: You can by a SD card module for Arduino and a fitting SD card and save the data there. This will lead to more programming overhead, especially, if you want to use a file system to also be able to read and write the SD card on the PC. (Note: The storage chips in SD cards have the same problem with limited write cycles, so they have the wear leveling incorporated into the hardware of the card)

---
You might as well decide, that you don't need the settings to be persistent between resets. Then you can just use variables and fill them with the settings from the Serial interface code.

You yourself have to decide, what the best way to go is here.

  [1]: https://arduino.stackexchange.com/questions/226/what-is-the-real-lifetime-of-eeprom
  [2]: https://github.com/PRosenb/EEPROMWearLevel/


body:
I have connected esp8266 with Arduino Uno and programmed 8266 with Arduino IDE to send data to firebase over WiFi. Now I also want to interface EM18 RFID Reader with Arduino in order to read the RFID tag and send information to firebase through esp8266. I have integrated the code for the same.

Now after uploading the code, only one of the interface works at a time, i.e if both esp8266 and EM18 are connected to Arduino, esp8266 connects to WiFi and sends data(verification data to check esp8366 is working) also, but not the data I want because EM18 is not reading the tag id. Having uploaded the same code if I remove connections with esp8266, the EM18 works fine(i.e. ID is printed in serial monitor after being read by EM18 Reader module).

Please help me with this, how can I send the information read by EM18 to esp8266 because they are not working together.

P.S. In my code there is different Rx Tx pin defined for esp8266(digital pin 0,1) and for EM18(digital pin 9,10(random)). Used softwareserial library for defining new Rx Tx.

My Connections:

Arduino and ESP8266
RX with RX;
TX with TX;
GND with GND;
3.3V with VCC;
3.3v with CH_PD;
GND with GPIO0(To Flash ESP8266);

Arduino's Reset pin is connected to Ground

Arduino and EM18 RFID Module
5v wuth VCC;
GND with GND;
Pin 13(Set as Rx) with TX;

My Code:
```
#include <BearSSLHelpers.h>
#include <CertStoreBearSSL.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiAP.h>
#include <ESP8266WiFiGeneric.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266WiFiScan.h>
#include <ESP8266WiFiSTA.h>
#include <ESP8266WiFiType.h>
#include <WiFiClient.h>
#include <WiFiClientSecure.h>
#include <WiFiClientSecureAxTLS.h>
#include <WiFiClientSecureBearSSL.h>
#include <WiFiServer.h>
#include <WiFiServerSecure.h>
#include <WiFiServerSecureAxTLS.h>
#include <WiFiServerSecureBearSSL.h>
#include <WiFiUdp.h>

#include <Firebase.h>
#include <FirebaseArduino.h>
#include <FirebaseCloudMessaging.h>
#include <FirebaseError.h>
#include <FirebaseHttpClient.h>
#include <FirebaseObject.h>

#include <ArduinoJson.h>

#include <SoftwareSerial.h>
//firebase and wifi
#define FIREBASE_HOST "my-shopping-d.firebaseio.com"
#define FIREBASE_AUTH "rkyF4AuzssSIO5VYRO6iP"
#define WIFI_SSID "****"
#define WIFI_PASSWORD "****"

const int disp=9;
//int j;
int tx=10,rx=13;
SoftwareSerial emSerial(rx,tx);  //EM18 Rx,Tx
int buttonState2 = 0;
int count = 0;                                          // count = 0
char input[12];                                         // character array of size 12
int count_arr[5]={0,0,0,0,0};
int i,cnt,total=0;
int price[5]={295,20,50,500,15};
char id_arr[6]={'2','F','7','E','3'};
char *myStrings1[] = {"Rice Rs.295", "Oreo Rs.20", "Silk Rs.50",
                     "Ghee Rs.500", "Nestle Rs.15", "TOTAL : "
                    };
char *myStrings2[] = {"Removed Rice Rs.295", "Removed Oreo Rs.20", "Removed Silk Rs.50",
                     "Removed Ghee Rs.500", "Removed Nestle Rs.15", "TOTAL : "
                    };

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

   //connect to wi-fi
   WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);

   pinMode(disp,INPUT);
}
 Serial.println();
  Serial.print("connected: ");
  Serial.println(WiFi.localIP());

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Serial.println("Firebase Connected");
}

int n = 0;

void loop()
{

   if(emSerial.available())
   {
    Serial.println("Card reader");
      count=0;
      while(emSerial.available() && count < 12)          // Read 12 characters and store them in input array
      {
         input[count] = emSerial.read();
         count++;
         delay(5);
      }
      Serial.print("id inpiut");
      Serial.println(input);
      for(i=0;i<5;i++)
      {
        if(input[10] == id_arr[i])
        {
          cnt=i;
          break;
        }
      }

      if(count_arr[cnt] == 0)
      {
        total=total+price[cnt];
        Serial.println(myStrings1[cnt]);
        Serial.print("TOTAL : ");
        Serial.println(total);
        count_arr[cnt]=1;
      }
      else if(count_arr[cnt] == 1)
      {
        total=total-price[cnt];
        Serial.println(myStrings2[cnt]);
        Serial.print("TOTAL : ");
        Serial.println(total);
        count_arr[cnt]=0;
      }

   }
      buttonState2 = digitalRead(disp);   // read the state of the pushbutton value:

      // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
      if (buttonState2 == HIGH)
      {

        j=1;
        for(i=0;i<5;i++)
        {
          if(count_arr[i]==1)
          {

            Firebase.setString("Items in Cart: ", myStrings1[i]);
             // handle error
            if (Firebase.failed())
            {
               Serial.print("setting /message failed:");
               Serial.println(Firebase.error());
               return;
            }
            delay(1000);
            String name = Firebase.pushInt("Total: ",total);
             // handle error
            if (Firebase.failed())
            {
                Serial.print("pushing /logs failed:");
                Serial.println(Firebase.error());
                return;
             }
            //j++;
          }
          delay(2000);

        }
      }
      int test = 5;
  String name = Firebase.pushInt("cart",test);
  // handle error
  if (Firebase.failed()) {
      Serial.print("pushing /logs failed:");
      Serial.println(Firebase.error());
      return;
  }
  Serial.print("pushed: /cart/");
}
```

title: Problem interfacing both esp8266 and EM18 with Arduino Uno

Answers: 0


body:
I'm trying to create eyes for a project, and while I have been able to properly program the different expressions, and have them triggered by commands from the COM3 terminal, I have not been able to make any commands from the Bluetooth Terminal on my phone work.

Details:

Mega2560

2x 8x8 LED Displays - MAX7219

HC-05 Bluetooth Transceiver - default Baud - 9600

Using LEDControl.h, SoftwareSerial.h

This is the loop on my device, when I type the commands A, B, etc. into the COM3 terminal it works just fine, but the same commands on the phone are just interpreted as ASCII, even when I put parentheses around them.

    void loop()
    {
      // Feed any data from bluetooth to Terminal.
      if (EEBlue.available()){
      Serial.write(EEBlue.read());
      }
      if (Serial.available())  //verifies if there is serial data available
      {
        char cmd = Serial.read();

        if(cmd == 'A') {
          display_eyes(eye_neutral_l, eye_neutral_r);
        }
        if(cmd == 'B') {
          display_eyes(eye_shock_l, eye_shock_r);
        }
        if(cmd == 'C') {
          display_eyes(eye_love_l, eye_love_r);
        }
        if(cmd == 'D') {
          display_eyes(eye_suspicious_l, eye_suspicious_r);
        }
        if(cmd == 'E') {
          display_eyes(eye_happy_l, eye_happy_r);
        }
        if(cmd == 'F') {
          display_eyes(eye_hurt_l, eye_hurt_r);
        }
        if(cmd == '1') {
          display_eyes(eye_mad_l, eye_mad_r);
        }
      // Feed all data from termial to bluetooth
      EEBlue.write(Serial.read());
      }
    }

title: Using an Android bluetooth terminal to change preset states on 8x8 LED matrixes

Answers: 1

body:
Your problem is, that you read from the `EEBlue` serial interface, but you are just echoing it over `Serial` and don't do anything with it. The display code is only executed, when the commands come through `Serial`.

The simplest way is to copy the code in the `if(Serial.available())` statement into the `if(EEBlue.available())` statement and changing the read to use `EEBlue`. Of course you should delete the existing `EEBlue.read()` from this statement.

But that way would mean to have double the code to maintain. It is cleaner to first read data from either serial interface and then process it. Something like this:

    if(Serial.available()){
        cmd = Serial.read();
    } else if(EEBlue.available()){
        cmd = EEBlue.read();
    }

    // insert the code to check the cmd variable for the expected values and act accordingly

    cmd = 0; // Resetting the cmd to prevent multiple executions of one command


body:
When I set my board to 'Generic ESP8266 module'  then only A0 pin of arduino is working while all other analog  pins are coming out of scope ,
 when I set the board to 'arduino /genuino uno' ,
 then "Error compiling for board Arduino/Genuino Uno." this error is coming how to set the board such that all analog pins with ESP8266 will work?
[![[When board is set to Arduino/Genuino Uno ][1]][1]

[1]: https://i.stack.imgur.com/UTeom.png

[![When board is set to Generic ESP8266 module][2]][2]

 [2]: https://i.stack.imgur.com/Gz1w4.png

title: A1-A5 pins not declared in this scope error

Answers: 1

body:
If you look at the ESP8266 pinout diagram (for example [here][1]), you will only find 1 analog input: A0. This is because the ESP8266 simply just has 1 analog input. The Arduino IDE states A1-A5 being out of scope, because on that board these inputs just don't exist. That is completely correct.

Also: When you try to compile code, that is meant for an ESP, for the Arduino Uno board, it will naturally fail, because it is just different hardware. The ESP basis code just cannot run on the Uno.

You will have to compile the code for the board, that you actually want to use AND you can only use codes/libraries, that are meant for your board. You cannot mix them in general. Only some function might be transferable (if so, it will not be easy) and WiFi is definitely not something to transfer to the Uno, which doesn't have the hardware for it.

  [1]: https://circuits4you.com/2017/12/31/nodemcu-pinout/


body:
I am using this code to send message using Arduino Uno & SIM900A mini v3.8.2 module. But I need to send same message on multiple numbers.

    #include <SoftwareSerial.h>
    SoftwareSerial SIM900A(10,11);
    void setup()
    {
      SIM900A.begin(9600);
      Serial.begin(9600);
      Serial.println ("SIM900A Ready");
      delay(100);
      Serial.println ("Type s to send message or r to receive message");
    }
    void loop()
    {
      if (Serial.available()>0)
       switch(Serial.read())
      {
        case 's':
          SendMessage();
          break;
        case 'r':
          RecieveMessage();
          break;
      }
     if (SIM900A.available()>0)
       Serial.write(SIM900A.read());
    }
     void SendMessage()
    {
      Serial.println ("Sending Message");
      SIM900A.println("AT+CMGF=1");
      delay(1000);
      Serial.println ("Set SMS Number");
      SIM900A.println("AT+CMGS=\"+639176363802\"\r");
      delay(1000);
      Serial.println ("Set SMS Content");
      SIM900A.println("Sample Message");
      delay(100);
      Serial.println ("Finish");
      SIM900A.println((char)26);// ASCII code of CTRL+Z
      delay(1000);
      Serial.println ("Message has been sent");
    }
     void RecieveMessage()
    {
      Serial.println ("SIM900A SMS");
      delay (1000);
      SIM900A.println("AT+CNMI=2,2,0,0,0");
      delay(1000);
      Serial.write ("Unread Message done");
     }

Thank you in advance

title: How to send message to multiple number using arduino and SIM900A mini v3.8.2?

Answers: 0


body:
I am making a project that uses an Arduino nano and a sound detector module to power a 1m LED strip. I got the idea from [this video][1] and I am not sure how to power it. My LED strip flashes for a split second and turns off, and people say that the usb power source I am using is not enough power. I am worried though that if I use a more powerful power source that it will fry my Arduino. I am very new to this and I have no idea what to do.

  [1]: https://www.youtube.com/watch?v=5oRir4dck_w

title: How to power Arduino nano and LED strip?

Answers: 2

body: You could use a relay and have a larger power supply that will light up the LED strip on the other side, after the relay gets the signal to turn on.

body: WS2812 can draw 60mA when on full white, x 60 LEDs = 3.6A.  If you have a 4 to 5A external 5V supply powering all the components, you'd be okay.  If you're trying to power the strip from the Nano 5V line thru its regulator, the regulator will overheat and shutdown.


body:
So I have a circuit for a timer (I don't think it is the problem)

[![enter image description here][1]][1]

Sorry for it being a little messy.

And I have this code (probably the problem):

    // LiquidCrystal - Version: Latest
    #include <LiquidCrystal.h>

    /*

    */

    const int switchUnitButton = 9;
    const int selectButton = 10;
    const int startButton = 8;
    const int stopButton = 7;
    const int d4 = 5;
    const int d5 = 4;
    const int d6 = 3;
    const int d7 = 2;
    const int rs = 12;
    const int en = 11;
    String unit = "sec";
    int unitCycle = 1;
    int secCount = 0;
    int minCount = 0;
    int hourCount = 0;
    int dayCount = 0;
    int switchUnitState;
    int prevUnitState;
    int selectState;
    int prevSelectState;
    int startState;
    int prevStartState;
    int stopState;
    int prevStopState;
    LiquidCrystal lcd = LiquidCrystal(rs, en, d4, d5, d6, d7);

    void setup() {
      Serial.begin(9600);
      pinMode(switchUnitButton, INPUT);
      pinMode(selectButton, INPUT);
      pinMode(startButton, INPUT);
      pinMode(stopButton, INPUT);
      lcd.begin(16, 2);
      lcd.clear();
    }

    void loop() {

      switchUnitState = digitalRead(switchUnitButton);
      selectState = digitalRead(selectButton);
      startState = digitalRead(startButton);
      stopState = digitalRead(stopButton);

      if (switchUnitState == HIGH) {
        if (prevUnitState != switchUnitState) {
          if (unitCycle < 4) {
           unitCycle++;
          } else if (unitCycle == 4) {
           unitCycle = 1;
          }
        }
      }

      Serial.print(unitCycle + "\n");

      if (unitCycle == 1) {
        unit = "sec";
      } else if (unitCycle == 2) {
        unit = "min";
      } else if (unitCycle == 3) {
        unit = "hour";
      } else {
        unit = "day";
      }

      Serial.print(unit + "\n");

      if (selectState == HIGH) {
        if (prevSelectState != selectState) {
          if (unit == "day") {
            dayCount++;
          } else if (unit == "sec") {
            secCount++;
          } else if (unit == "hour") {
            hourCount++;
          } else if (unit == "min") {
            minCount++;
          }
        }
      }

      lcd.setCursor(0, 0);
      lcd.print("Sec: " + String(secCount) + " Min: " + String(minCount));
      lcd.setCursor(0, 1);
      lcd.print("Hr: " + String(hourCount) + " Day: " + String(dayCount));

      prevUnitState = switchUnitState;
      prevSelectState = selectState;
      prevStartState = startState;
      prevStopState = stopState;
    }

And sometimes without me clicking a button the unit value changes or sometimes when I click the selectButton for the amount to go up it changes which unit it is adding to. And sometimes the string has parts before it from other units like "inhour" what is happening?

  [1]: https://i.stack.imgur.com/lUq3o.png

title: Arduino Uno - Variables randomly changing

Answers: 1

body:
You are seriously abusing the String class.  There is absolutely no need to use any Strings at all in your program.

For example:

      if (unitCycle == 1) {
        unit = "sec";
      } else if (unitCycle == 2) {
        unit = "min";
      } else if (unitCycle == 3) {
        unit = "hour";
      } else {
        unit = "day";
      }

      Serial.print(unit + "\n");

would be better written as:

      if (unitCycle == 1) {
        Serial.println(F("sec"));
      } else if (unitCycle == 2) {
        Serial.println(F("min"));
      } else if (unitCycle == 3) {
        Serial.println(F("hour"));
      } else {
        Serial.println(F("day"));
      }

And:

      if (selectState == HIGH) {
        if (prevSelectState != selectState) {
          if (unit == "day") {
            dayCount++;
          } else if (unit == "sec") {
            secCount++;
          } else if (unit == "hour") {
            hourCount++;
          } else if (unit == "min") {
            minCount++;
          }
        }
      }

as:

      if (selectState == HIGH) {
        if (prevSelectState != selectState) {
          if (unitCycle == 1) {
            secCount++;
          } else if (unitCycle == 2) {
            minCount++;
          } else if (unitCycle == 3) {
            hourCount++;
          } else {
            dayCount++;
          }
        }
      }

And then the cardinal sin:

    lcd.print("Sec: " + String(secCount) + " Min: " + String(minCount));

All that string creation, concatenation, and destruction is just evil.  Instead, use:

    lcd.print(F("Sec: "));
    lcd.print(secCount);
    lcd.print(F(" Min: "));
    lcd.print(minCount);


body:
I had a thought about making myself an arcade cabinet. I found a nice cheap and sturdy 8 directional arcade joystick online, and now I'm thinking about the possible ways of displaying graphics.

I would like to know how can I send graphical data to a large screen using Arduino. When I was researching this I saw "TV Text" library that allows sending PAL and SECAM signals, but that's not the "modern" way. Is there a way of using DisplayPort or HDMI to simply use a cheap used PC monitor? Maybe there are other protocols that I can use? I'm looking for a "cheap" way to create a display that's physically as large as screen of arcades from "the good old days".

title: Connecting (SD or HD) TV screen to Arduino

Answers: 1

body:
I'm just going to post things that I found thanks to comment by Juraj.

 1. "TV Text" library - PAL, SECAM, NTSC
 2. "[VGAX][1]" library - [VGA][2]

And with large dedication to everyone who wrote that "it's impossible" I give you a blog post of someone who actually did create he's own NTSC console and a game from scratch (called "The Box") using ATmega328P with external 16Mhz crystal. And he did it in 2013.

http://petenpaja.blogspot.com/2013/11/toorums-quest-ii-retro-video-game.html

Original sources were deleted, but I think they can be found when looking for [Toorum Quest 2][3]

I think I'll try analyzing the VGAX. It looks promising.

**EDIT:**

There actually is HDMI shield for Arduino!

https://github.com/techtoys/HDMI-Shield/tree/master/Ra8876_Lite

And a nice and very easy VGA tutorial here:

http://www.pyroelectro.com/tutorials/arduino_basic_vga/

  [1]: https://github.com/smaffer/vgax
  [2]: http://www.gammon.com.au/forum/?id=11608
  [3]: https://github.com/NosDE/toorumquest2


body:
I tried installing the Arduino IDE in the newly released Ubuntu 19.04 Disco Dingo.
I downloaded the file from the [official downloads page][1]. I `chmod +x` ed the file and ran the install script. Then, it says:

    Adding desktop shortcut, menu item and file associations for Arduino IDE...
    rm: cannot remove '/usr/local/bin/arduino': No such file or directory
    Removing symlink failed. Hope that's OK. If not then rerun as root with sudo.
    touch: cannot touch '/root/.config/mimeapps.list': No such file or directory

`/usr/bin/xdg-mime: 848: /usr/bin/xdg-mime: cannot create `/root/.config/mimeapps.list.new:`
`Directory nonexistent`

Then, I again ran it as root user with `su root` but it still gave the same error...

Will this cause a problem..? I mean, I had prior issues related to uploading the sketch in earlier Linux IDE installations. Will this cause a problem...?
`

  [1]: https://www.arduino.cc/en/Main/Software

title: Installing Arduino IDE in the new Ubuntu Disco Dingo

Answers: 0


body:
I am running into a strange behaviour with my code. The following works without problems on an Arduino Nano but it seems to crash on a DUE

    void putData64(byte* packet, int pos, uint64_t data)
    {
        uint64_t* h= (uint64_t*) (packet+pos+2);
        *h= data;
    }

the problematic line seems to be the second one (*h= data) as commenting it out lets the program run without problems.

Similar, the following lines cause a problem on a DUE but run fine on a Nano:

    char* data;
    // ... data is filled with something
    uint64_t* t= (uint64_t*) (data+1);
    uint64_t test= *t;
Is there something I am missing?

title: Programfault when dereferencing a 64bit int on due

Answers: 1

body:
I concur with Majenko's comment: it's probably a memory alignment
problem. I don't know the specifics of the Due, but when you access
memory in chunks of 32 bit data words on a 32 bit CPU, it can
happen that the architecture requires the data words to be aligned to
32 bit (i.e. 4 byte) boundaries. This means that the address
of an `uint32_t` or `uint64_t` should be a multiple of 4. Maybe
even 8 for a `uint64_t`, you will have to check.

The only solution to this issue is to fill the packet _byte by byte_:

<!-- language: lang-c++ -->

    void putData64(byte* packet, int pos, uint64_t data)
    {
        union {
            uint64_t integer;
            byte bytes[8];
        } h = { .integer = data };
        for (int i = 0; i < 8; i++) {
            packet[pos+2+i] = h.bytes[i];
        }
    }

Note that the AVR (in the Nano) is an 8 bit architecture with no
alignment constraints whatsoever.


body: Having a hard time searching the net on how to run arduino codes on java. Can somebody please help me. Thank you.

title: How to run Arduino codes in Java netbeans?

Answers: 2

body: Java is a programming language. Arduino is a platform that is mostly accessed by the C++ programming language. You cannot run "Arduino code" in Java.

body: The Arduino can't run Java. Full stop.


body:
I'm having problems with my Arduino UNO and the ESP8266 module.
I need to send values from Arduino to my PHP web page in this way:

http://www.server.com/km/db.php?id=53

the ESP8266 module is working fine, it powers up and connects to my Wi-Fi without problems, but I'm not able to send the values to my PHP page.

This is my code:

        #include "SoftwareSerial.h"

    String ssid ="NETGEAR80";
    String password="mypassword";

    SoftwareSerial esp(10, 11);// RX, TX

    String data;

    String server = "http://www.server.com";
    String uri = "/km/db.php";//
    int DHpin = 8;//sensor pin
    byte dat [5];
    String temp ,hum;

    void setup() {
    pinMode (DHpin, OUTPUT);
    esp.begin(9600);
    Serial.begin(9600);
    reset();
    connectWifi();

    }

    void reset() {
    esp.println("AT+CWMODE_DEF=1");
    esp.println("AT+RST");
    delay(1000);
    if(esp.find((char*)"OK") ) Serial.println("Module Reset");

    }

    void connectWifi() {
    Serial.println("Collegamento");
    String cmd = "AT+CWJAP_CUR=\"" +ssid+"\",\"" + password + "\"";
    esp.println(cmd);
    Serial.println(cmd);
    delay(4000);
    if(esp.find((char*)"OK")) {
    Serial.println("Connected!");
    }
    else {
    connectWifi();
    Serial.println("Cannot connect to wifi"); }
    }

    void loop () {

    temp=11;

    data = "id=" + temp;// data sent must be under this form

    httppost();

    delay(1000);

    }

    void httppost () {

    esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.
    if( esp.find((char*)"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;

    Serial.println(postRequest);

    String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.

    esp.print(sendCmd);

    esp.println(postRequest.length() );

    delay(500);

    if(esp.find((char*)">")) { Serial.println("Sending.."); esp.print(postRequest);

    if(esp.find((char*)"SEND OK")) { Serial.println("Packet sent");

    while (esp.available()) {

    String tmpResp = esp.readString();

    Serial.println(tmpResp);

    }

    // close the connection

    esp.println("AT+CIPCLOSE");

    }

    }
    }

This is the output on the Serial Terminal:

    Module Reset
    Collegamento
    AT+CWJAP_CUR="NETGEAR80","calmgrasshopper675"
    In attesa..
    Connected!
    POST /km/db.php HTTP/1.0
    Host: www.skeetty.com
    Accept: */*
    Content-Length: 17
    Content-Type: application/x-www-form-urlencoded

    id=11&humidity=10
    POST /km/db.php HTTP/1.0
    Host: www.skeetty.com
    Accept: */*
    Content-Length: 17
    Content-Type: application/x-www-form-urlencoded

The code works fine till the POST, but then no answer is received.

This condition:

    if(esp.find((char*)">")) { Serial.println("Sending.."); esp.print(postRequest);

is never verified.

I can't understand if there is something wrong with the POST format, with the URL or something else.

Can you help me, please?

----------
**EDIT 26/04/2019**
This is the output if I manually write the AT commands directly to the ESP8266 module through the Serial Monitor.

    AT+CWJAP="NETGEAR80","my_password"

    WIFI CONNECTED
    WIFI GOT IP

    OK
    AT+CIPMUX=1

    OK

    AT+CIPSTART=1,"TCP","www.server.com",80

    1,CONNECT

    OK

If I use the Arduino code, it never connects to the server and the string "TCP connection ready" do not show, so I think it is not able to correctly connect to the server. Maybe, it's for a formatting error? I can't find the reason.

----------
EDIT2 with @Juraj code.

        #include <SoftwareSerial.h>

    SoftwareSerial Serial1(10, 11);
    #define Trash "Trash3"
    #define DHTTYPE DHT11
    #define DHTPIN 2
    #define TRIGGER_PIN 4
    #define ECHO_PIN 3

    float humidity, temp_f;
    int distance;
    long duration;

    String buff(64);
    String getStr(128);

    void setup() {

    Serial.begin(9600);

    Serial1.begin(9600);
    //Serial1.resetESP();
    delay(2000);
    Serial1.setTimeout(5000);

    if (!connectWiFi()) {
    Serial.println("Can not connect to the WiFi.");
    while (true)
    ; // do nothing
    }
    Serial.println("OK, Connected to WiFi.");

    sendCommand("AT+CIPSTA?");
    sendCommand("AT+CIPDNS_CUR?");
    sendCommand("AT+CIPSTAMAC?");
    }

    void loop() {

    temp_f = 11;

    // connect to server
    if (sendCommand("AT+CIPSTART=\"TCP\",\"www.skeetty.com\",80")) {
    Serial.println("connected to Cloud");

    // build HTTP request
    getStr = "GET /km/db.php?id=";
    getStr += temp_f;
    getStr += " HTTP/1.1\r\n";
    getStr += "Host: expository-spoke.000webhostapp.com\r\n\r\n";

    // open send buffer
    buff = "AT+CIPSEND=";
    buff += getStr.length();
    if (sendCommand(buff.c_str()) && Serial1.find(">")) { // AT firmware is ready to accept data

    // send HTTP request
    Serial.println(getStr);
    Serial1.print(getStr);

    // print HTTP response
    if (Serial1.find("+IPD,")) { // response received
    int l = Serial1.parseInt();
    while (l > 0) {
    if (Serial1.available()) {
    Serial.write(Serial1.read());
    l--;
    }
    }
    Serial.println("--------------");
    } else {
    Serial.println("no response");
    }
    } else {
    Serial.println("send error");
    }
    sendCommand("AT+CIPCLOSE");
    } else {
    Serial.println("Error connecting");
    }
    }

    bool connectWiFi() {

    if (!sendCommand("ATE0")) // echo off
    return false;
    if (!sendCommand("AT+CIPMUX=0")) // set single connection mode
    return false;
    if (!sendCommand("AT+CWMODE=1")) // set STA mode
    return false;
    return sendCommand("AT+CWJAP=\"NETGEAR80\",\"calmgrasshopper675\"");
    }

    bool sendCommand(const char* cmd) {
    Serial.println(cmd);
    Serial1.println(cmd);
    while (true) {
    buff = Serial1.readStringUntil('\n');
    buff.trim();
    if (buff.length() > 0) {
    Serial.println(buff);
    if (buff == "OK" || buff == "SEND OK" || buff == "ALREADY CONNECTED")
    return true;
    if (buff == "ERROR" || buff == "FAIL" || buff == "SEND FAIL")
    return false;
    }
    }
    }

it never connects to the Wi-Fi network because sendCommand() always return false.

title: Can't POST data with Arduino and ESP8266

Answers: 0


body:
I'm creating a program that works like a piano. I have four button, a piezo buzz and an LCD screen. I'm having a little trouble with the buttonstate.

Here is my program, when I run it the piezo buzz doesn't stop producing sound. The way it's suppose to work is when I push the green button, the piezo is suppose to produce a C sound but it doesn't. Can anyone please tell me what I've done wrong?

code:

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(13, 12, 11, 10, 9, 8);

    int buttonyellow = 3;
    int buttonred = 4;
    int buttongreen = 5;
    int buttonblue = 6;

    int C,D,E,F;
    int buzz = 7;

    int buttonstate;

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

      lcd.print("hello, world!");

      Serial.begin(9600);
      pinMode(buttonyellow,INPUT);
      pinMode(buttonred,INPUT);
      pinMode(buttongreen,INPUT);
      pinMode(buttonblue,INPUT);
    }

    void loop()
    {
      lcd.setCursor(0, 1);

      lcd.print(millis() / 1000);

      C = digitalRead(buttonyellow);
      D = digitalRead(buttonred);
      E = digitalRead(buttongreen);
      F = digitalRead(buttonblue);

      buttonstate = digitalRead(C);
      if(buttonstate == HIGH){
        tone(buzz,523);
      }  else if ( buttonstate == LOW) {
        tone(buzz,1000);
      }else{
       noTone(buzz);
      }
      delay(50);
    }

title: Need help with buttonstate

Answers: 1

body:
As jsotola has pointed out, there is a mistake in your code. Remove the line

    buttonstate = digitalRead(C)

and replace

    if(buttonstate == HIGH)
with

    if(C == HIGH)

Moreover, I suggest you take a look at the debouncing example in order to make the sound "smoother" ie no jitters because of the button


body:
 i have a nodeMCU v3(esp8266)
and what i want is: when i send  DC 5v or 3v to a pin=**D1** (idk if its possible to send 5v directly to pin) then to activate the **D0** for 20Seconds

like this:

     if (D1==Sends signal){
        digitalWrite(pinD0, HIGH);
          delay(20000);  //pinD0 is active for 20 seconds

      }else{
         digitalWrite(pinD0, LOW);

      }

title: nodeMCU - when DC is active on pin the do this

Answers: 0


body:
**SOLVED:** I "solved" the problem by cycling my Arduino's power and I haven't had an issue since. I would still like to figure out what was going on. I still think it's something in that MPU6050 library with getMotion. But anyway, if anyone eventually has any ideas post it up. Thanks
___________________________
**Original question:**
I'm using an MPU6050 accelerometer/gyro that controls a servo through a Mega.

QSTN: The sensor simply stops reading after an arbitrary time, usually between 2-4 minutes. I have to reinitialize the serial monitor/MPU to get it to work again which is not good. I suspect it has something to do with getMotion but I can't put my finger on it.

Any ideas? Thanks. Code is below:

    #include "Wire.h"
    #include "I2Cdev.h"
    #include "MPU6050.h"
    #include "Servo.h"

    MPU6050 mpu;

    int16_t ax, ay, az;
    int16_t gx, gy, gz;

    Servo servo1;

    int val;
    int prevVal;

    void setup()
    {
        Wire.begin();
        Serial.begin(38400); //38400

        Serial.println("Initializing MPU6050");
        mpu.initialize();
        Serial.println(mpu.testConnection() ? "CONNECTED" : "Connection failed");
        servo1.attach(9);
    }

    void loop()
    {

        mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

        val = map(ay, -17000, 17000, 0, 179);

        if (val != prevVal)
        {
            servo1.write(val);
            prevVal = val;
            Serial.println(val);
        }

        delay(75);

    }

title: SOLVED Accelerometer/gyro MPU6050 is freezing after random time

Answers: 0


body:
i have nodeMCU v3(esp8266) so i need to make 2 checks
1 check is the pin D1 which needs to be done continuously  and another check is web link check every 10 seconds,
problem is coz when i put delay then it stops the first check

    void loop() {

     if (digitalRead(pinD1)==1){
           digitalWrite(pinD0, HIGH);
           delay(20000);
     }else{
           digitalWrite(pinD0, LOW);
     }

          loop2();

    }

    void loop2(){
       if (json1=="ON"){
        digitalWrite(pinD0, HIGH);
          delay(20000);
    }else{
         digitalWrite(pinD0, LOW);
                   delay(10000);

      }
    }

title: nodeMCU - 2 loops at a time - one continuously and second every 10 seconds

Answers: 1

body:
Rather than using `delay`, use `millis()` and a variable to check if the some time has expired

    void loop()
    {
        static int check = 0;
        int now = millis();
        if (now >= check) {
            if (digitalRead(pinD1)==1){
                digitalWrite(pinD0, HIGH);
                check = now + 20000;
            } else {
                digitalWrite(pinD0, LOW);
                check = now;
            }
        }
        loop2();
    }

    void loop2()
    {
        static int check = 0;
        int now = millis();
        if (now >= check) {
            if (json1=="ON"){
                digitalWrite(pinD0, HIGH);
            } else {
                digitalWrite(pinD0, LOW);
            }
            check = now + 20000;
        }
    }


body:
I'm trying to parse with tinyxml2 a modest XML (3.4kb) to retrieve some data.

My ESP8266 crashes every time I try to use the `toCharArray` method.

here's my code

```
// here I'm getting an http request
String payload = https.getString();

// checking the payload, it seems fine in console but I get some garbage characters when àèéùìò are printed
Serial.println(payload);

// Length (with one extra character for the null terminator)
int str_len = payload.length() + 1;

// Prepare the character array
char xml[str_len];

// Copy it over
payload.toCharArray(xml, str_len);

// there I'll parse xml with tinyxml2 but the MCU crashes before getting here
```

the length of the string is something around 3900, which I'm not sure can fit this kind of array on this device. If it's the case, what will be a better strategy ?

As you can imagine I'm just starting with the c language :)

EDIT: `https.getString().c_str()` + less variables was the right way to save memory

title: ESP8266 crashes when trying to copy a string into a big char

Answers: 1

body:
Function local variable are created on the stack, and in the case of an ESP8266, the total size is limited to 4096 Bytes - so, 3900 for one variable is cutting it close.

I would recommend you either use malloc/free

    int str_len = payload.length() + 1;

    // Prepare the character array
    char *xml = (char *) malloc(str_len);

    // Copy it over
    payload.toCharArray(xml, str_len);

    // there I'll parse xml with tinyxml2 but the MCU crashes before getting here
    //
    // when done, free the memory malloc'd

    free(xml);

or, if you know an absolute maximum size for the string, e.g. 5000, make `char xml[5001];` in the global scope


body:
I currently have an Aurdiuno uno and a motor driver shield: (http://www.hobbytronics.co.uk/arduino-motor-shield).

Now, I would like to run the following mechatronic devices:
3 bi-direction motors,
1 servo,
1 hall effect sensor (digital),
2 infra-red sensors,
1 magnetometer,
1 ultrasonic sensor,

Will the Aurdiuno uno paired with the motor sheild be able to run these components or will I need to buy an Aurdiuno mini? Could I please gain some insight into how you figure out what pins are required and how would i connect the sensor pins to the motor sheild since it does not have any direction slip on connections like the Aurdiuno Uno. Will I need to solder the sensor connections on?

Thankyou

title: What is the maximum number of sensors that can be operated on a single Aurdino unit

Answers: 1

body:
> Will the Aurdiuno uno ... buy an Aurdiuno mini?

The main differences between the uno and mini are:

 - footprint
 - 6 (uno) vs 8 (mini) analog inputs

You will get two extra analog inputs and a much smaller size at the cost of the shield not fitting anymore.

> Now, I would like to run the following mechatronic devices: 3 bi-direction motors, 1 servo, 1 hall effect sensor (digital), 2 infra-red sensors, 1 magnetometer, 1 ultrasonic sensor, Will the Aurdiuno uno paired with the motor sheild be able to run these components?

According to the website the shield supports up to 4 motors or 5 servos, so i would guess that it would work.

if the shield can't do 3 motors and 1 servo at the same time, then you can just use the servo library and a pin for that.

The shield requires 3 pins to function; so you need 3 or 4 pins depending on configurations.

Inputs 1 digital, 4 analog; 1 Digital I\O, 1 Analog In

so it looks like you need 4-5 DIO pins and 4 analog pins, which the uno has so yes.

If you were using motor driver boards instead of a shield the cost would be

2x PWM per Motor/driver combo = 6 PWM
1 DIO for servo
1 DIO for digital input
4x Analog Inputs

Which also fits in the budget all 6 of the PWM DIO pins, + 2 more (leaving 6 of the 14) and 2/3rds of the analog pins (also good you can leave A3,4 alone since they share a timer and only use the other ones)


body:
I am using an ESP32 to capture some data and then sending it over using ArduinoJson. However, sometimes, the firmware gets stuck at the line where it is transmitting data at obj.printTo(client). I have the logs for the same. Do you have any idea as to what might be making it freeze? And any way to avoid it in the future.

Logs:

12:28:00.584 -> [V][ssl_client.cpp:276] send_ssl_data(): Writing HTTP request...

12:28:00.584 -> [V][ssl_client.cpp:276] send_ssl_data(): Writing HTTP request...
12:47:11.229 -> [E][ssl_client.cpp:33] handle_error(): UNKNOWN ERROR CODE (004E)  12:47:11.229 -> [E][ssl_client.cpp:35] handle_error(): MbedTLS message code:-78

12:47:11.229 -> [V][ssl_client.cpp:245] stop_ssl_socket(): Cleaning SSL connection.
12:47:11.229 -> request sent
12:47:12.217 -> esp32/Arduino CI has failed
12:47:12.217 -> reply was:
12:47:12.217-> ==========
12:47:12.217 ->
12:47:12.217 -> ==========
12:47:12.217 -> closing connection

The send code:

    jsonBuffer.clear();
    JsonObject &rootObject = jsonBuffer.createObject();
    JsonObject &dataObject = rootObject.createNestedObject("data");
    JsonArray &X1dataObject = dataObject.createNestedArray("X1");
    JsonArray &Y1dataObject = dataObject.createNestedArray("Y1");
    JsonArray &Z1dataObject = dataObject.createNestedArray("Z1");
    JsonArray &T1dataObject = dataObject.createNestedArray("T1");

    vTaskDelay(10);

    if (send_flag) {
      digitalWrite(2,0);
      send_flag = false;
      int connection_iterator = 0;
      int connection_iterator2 = 0;
      for (int iterator = 0; iterator < SAMPLE_SIZE; iterator++) {
        X1dataObject.add(X1dataArray[iterator]);
        Y1dataObject.add(Y1dataArray[iterator]);
        Z1dataObject.add(Z1dataArray[iterator]);
      }
      T1dataObject.add((float)(analogRead(NTC)*0.0244));

      rootObject["coreid"] = String(low, HEX) + String(high, HEX);
      //rootObject["coreid_high"] = String(high, HEX);
      rootObject["sample_time"] = int(time_taken);
      rootObject["firmware_version"] = FIRMWARE_UPDATE_VERSION;
      rootObject.prettyPrintTo(Serial);
      Serial.print("connecting to ");
      Serial.println(host);
      while ((!client.connect(host, httpsPort)) && !setup_mode) {
        connection_iterator++;
        Serial.println("connection failed! Retrying..");
        delay(5000);
        if (connection_iterator >= 10)
          ESP.restart();
      }
      if (client.verify(fingerprint, host)) {
        Serial.println("certificate matches");
      } else {
        Serial.println("certificate doesn't match");
      }
      digitalWrite(LED_BUILTIN, HIGH);
      Serial.print("requesting URL: ");
      Serial.println(url);
      client.println(String("POST ") + url + " HTTP/1.0");
      client.println(String("Host: ") + host);
      client.println("Cache-Control: no-cache");
      client.println("Content-Type: application/json");
      client.print("Content-Length: ");
      client.println(rootObject.measureLength());
      client.println();
      rootObject.printTo(client);
      Serial.println("NUMBER OF INTERRUPTS:");
      Serial.println(interruptCounter);
      Serial.println("request sent");
      while ((client.connected()) && !setup_mode) {
        connection_iterator2++;

        String line = client.readStringUntil('\n');
        if (line == "\r") {
          Serial.println("headers received");
          break;
        }
        Serial.println("Waiting for response");
        delay(500);
        if (connection_iterator2 >= 40)
          break;
      }
      String line = client.readStringUntil('\n');
      if (line.startsWith("{")) {
        Serial.println("esp32/Arduino CI successfull!");
      } else {
        Serial.println("esp32/Arduino CI has failed");
      }
      Serial.println("reply was:");
      Serial.println("==========");
      Serial.println(line);
      Serial.println("==========");
      Serial.println("closing connection");
      digitalWrite(LED_BUILTIN, LOW);
      // readRegister(INT_SOURCE, 1, &dummy_read);
    }

title: Firmware gets stuck at obj.printto(client) in esp32

Answers: 2

body:
I see that you are using SSL. SSL uses a lot of RAM and it is possible that the stack and the heap are colliding which will corrupt the running sketch. I recommend you add the amount of free heap to your log statements so that you can see how it changes, which will help you see if this is what is happening.

To obtain the free heap you can use esp_get_free_heap_size() - there's more documentation about this function in [the espressif online documentation][1].

  [1]: https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/system/system.html#_CPPv222esp_get_free_heap_sizev

body:
So I have found out that apparently there is some issue working with WiFiClientSecure to send large data packets. The secure line sends data in small packets which take up a lot of time and also if the server gets unavailable at any moment, the program will get stuck there. This problem, however, was not this prominent when I used the same mechanism in esp8266.  Nevertheless, the solution would be to use a buffer to send the data.

Also, this version of code was written with ArduinoJson V5. But, even after migrating to ArduinoJson V6 the problem persists. It seems that whatever new JsonDocument feature has been implemented in the new version is still far from providing the efficiency of a buffer and it recoils back.

However still, if anyone else finds a better solution, please do update.


body:
i bought an Arduino Mega2560 and flashed it with usbmidi. So now it comes up as a midi device.

I need more than those 16 analog ins to be able to put all my 24 piezo sensors into it to receive midi signals from it. I still have no idea how i have to put the piezo pieces into the arduino but also no clue as how to get more than those 16 analog slots. Any way to use the digital inputs as well or do i need some extension shield or so? I'm a total beginner with arduino...

title: How to get more than the 16 Analog INs on a Arduino Mega for using like 24 piezo sensors

Answers: 2

body:
You need one (or more) external ADC (analog digital converters).

For example the [ADS1115][1], the link shows an Adafruit model and how to use it.

In a DIP format (to be used on breadboards/prototype boards) it will be hard to find a 16 channel ADC, but you can add multiple I2C (or other) 4 channel ADCs to one Arduino Mega.

  [1]: https://learn.adafruit.com/adafruit-4-channel-adc-breakouts/assembly-and-wiring

body:
You can customize a controllino on their page
https://www.controllino.biz/controllino-myplc/
I just looked at it and it seems you can get 24 analog outputs.

Don't know what the cost is though.


body:
I need a function to return a 2x2 rotation matrix, something like:

    float matrix(float phi){
      float R[2][2] = { {cos(phi), -sin(phi)},
                        {sin(phi),  cos(phi)} };
    return R;
    }
But it doesn't work obviously. **What is the best way to write this function?**

title: How to write a function to return matrix?

Answers: 2

body:
One way would be to make the function return a pointer to float ie create a new array and return it

    float** matrix(float phi){
       float** R= (float **)malloc(2 * 2 * sizeof(float));
       R[0][0]= cos(phi);
       R[0][1]= -sin(phi);
       R[1][0]= sin(phi);
       R[1][1]= cos(phi);
       return R;
    }

Do not forget to free the memory once you do not need it any more!

However, I would advise you not to do it but rather pass the array to the function. See https://arduino.stackexchange.com/questions/3774/how-can-i-declare-an-array-of-variable-size-globally and https://arduino.stackexchange.com/questions/682/is-using-malloc-and-free-a-really-bad-idea-on-arduino for an explanation why it might not be a good idea to allocate the memory in the function (in an embedded aka Arduino environment)

body:
You cannot return an array from a function. There are several
alternatives, though. One of them is to allocate the memory for the
array within the function, as suggested by user2912328's answer. I would
not recommend this approach though, for the reasons already stated in
that answer.

For an overview of the other possible options, see [this response to the
question “Returning an int array from a function”][1].

Now, your problem is slightly different, as you have a 2D array.
The C/C++ syntax for dealing with those is tricky, but here we go.

If you opt for the “static array” solution (make sure you understand the
implications), you could write:

<!-- language-all: lang-c++ -->

    float (*matrix(float phi))[2]
    {
        static float R[2][2];
        R[0][0] = cos(phi);
        R[0][1] = -sin(phi);
        R[1][0] = sin(phi);
        R[1][1] = cos(phi);
        return R;
    }

and you would use it like this:

    float (*M)[2] = matrix(angle);

If you instead let the caller manage the allocation, then

    float (*matrix(float phi, float (*R)[2]))[2]
    {
        R[0][0] = cos(phi);
        R[0][1] = -sin(phi);
        R[1][0] = sin(phi);
        R[1][1] = cos(phi);
        return R;
    }

Or maybe forgo the return value to make the syntax simpler:

    void matrix(float phi, float (*R)[2])
    {
        R[0][0] = cos(phi);
        R[0][1] = -sin(phi);
        R[1][0] = sin(phi);
        R[1][1] = cos(phi);
    }

and you could use it like:

    float M[2][2];
    matrix(angle, M);

The “array in a struct” solution is more straightforward.

If the syntax for dealing with 2D arrays bothers you (which would be
understandable), you can instead use arrays of pointers to 1D arrays.
This are easier to deal with but trickier to allocate. That approach
could warrant another answer...

[1]: https://arduino.stackexchange.com/a/30214

------------------------------------------------------------------------

**Edit**: One common way to simplify a convoluted array syntax is to use
typedefs. As an identifier for a 2x2 array decays to a pointer to an
array of 2 floats, you can name that type:

    typedef float (*pmatrix)[2];  // pointer to an array of 2 floats

Then, instead of

    float (*matrix(float phi))[2] { ... }
    ...
    float (*M)[2] = matrix(angle);

you would write

    pmatrix matrix(float phi) { ... }
    ...
    pmatrix M = matrix(angle);


body:
I'm trying to make a program that whenever a button is push, a different word will show on a lCD screen. However, it seems that the two buttons provide the same output ("Screen A"), it's like there is no difference between them, and I'm not sure what's the cause.

The code is very simple:

    const int buttonPin1 = 13;     // the number of the pushbutton pin
    const int buttonPin2 = 12;     // the number of the pushbutton pin

    int buttonState = 0;

    long randNumber;

    void setup() {

      for(int x=0; x<2; x++)
      {
        pinMode(buttonPin[x], INPUT);
      }

    }
        void loop() {

          for(int x=0; x<2; x++)
          {
            buttonState = digitalRead(buttonPin[x]);

            if (buttonState == HIGH && buttonPin[x] == 13) {
              lcd.print("  Screen A ");
            }
            if (buttonState == HIGH && buttonPin[x] == 12) {
              lcd.print("  Screen B ");
            }
          }

        }

Any help is appreciated

title: Two buttons, one LCD

Answers: 1

body:
I guess it's something with the circuit ... can you add it to your question.

Also, make sure buttonPin has the values 13 and 12 in the first and second index.

Btw, The following code is functionally identical:

    void loop()
    {
        if (digitalRead(buttonPin[0]) == HIGH)
        {
           lcd.print("  Screen A ");
        }
        if (digitalRead(buttonPin[1]) == HIGH)
        {
           lcd.print("  Screen B ");
        }
    }

If you want to have the loop and a flexible amount, use something like:

    #define NR_OF_PINS 2

    int buttonPins[NR_OF_PINS] = { 8, 9 };
    String screens[NR_OF_PINS] = { "Screen A", "Screen B" };

    void loop()
    {
        for (int pin = 0; pin < NR_OF_PINS; pin++)
        {
            if (digitalRead(buttonPins[pin]) == HIGH)
            {
                lcd.print(screens[pin]);
            }
        }
    }

**Update**

My answer is related to the code before you edited.

Remarks:

- After your edited code, you forgot to declare buttonPin:

    int buttonPin[] = { buttonPin1, buttonPin2 };

- You do not use `long randNumber`

- Instead of a global variable `int buttonState`  you can create it locally in the loop function (although you do not need it according to my code above).

    buttonState = digitalRead(buttonPin[x]);

- Also, what you high likely want to add is button debouncing (check the arduino example about this), unless you add a delay after showing a screen of a considerable amount (like 100 ms or more).


body:
I have been trying to develop a connection from the arduino IDE to Processing so I can send data measured on the arduino Pins to processing to display.

I first packaged the 10-bit integers I was receiving from the arduino into characters each with their own byte. For example, 1023 was a 10-bit integer which i packaged into 4 8-bit characters, 1, 0, 2 and 3. These could then be sent over the serial port and were reconstructed on the other end by processing.

However, I have been trying to make a call and response relationship between the two where after one program is done receiving and processing the data, it asks the other to send the next set.

I used the example code given on the arduino website which works fine on its own. But when i try and implement the character packaging to it, it stops working. The output in processing always miss out the first couple of characters.

Whats more is that i deleted the myPort.print('A') from the processing code, and arduino was still sending data repeatedly, despite processing not sending it's response back.

It is a vague question, but where have i gone wrong when implementing the packaging code? and why does the arduino keep sending data regardless of whether processing responds.

Thanks a lot

===================================

Arduino Code:

    int inByte = 0;

    //void establishContact();

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
      establishContact();
    }

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

      if (Serial.available() > 0) {
        // get incoming byte:
        //inByte = Serial.read();

          int MzValue = analogRead(A0);
          int FzValue = analogRead(A1);
          int FyValue = analogRead(A2);

          char Mz_Str[10];
          char Fz_Str[10];
          char Fy_Str[10];

          sprintf(Mz_Str, "%d", MzValue);
          sprintf(Fz_Str, "%d", FzValue);
          sprintf(Fy_Str, "%d", FyValue);
          // Now str contains the integer as characters

          Serial.write(Mz_Str);
          Serial.write(",");
          Serial.write(Fz_Str);
          Serial.write(",");
          Serial.write(Fy_Str);
          Serial.write(",");
          Serial.write("\n");

          delay(20);
      }
      else {
        delay(20);
      }
    }

    void establishContact() {
      while (Serial.available() <= 0) {
        Serial.print('A');   // send a capital A
        delay(1000);
      }
    }

===================================
Processing Code:

    import processing.serial.*;

      Serial myPort;                       // The serial port
      boolean firstContact = false;        // Whether we've heard from the microcontroller
      String val;     // Data received from the serial port
      int numValues = 3;
      float[] values = new float[numValues];
      int inByte = 0;

      void setup() {
        size(256, 256);  // Stage size
        noStroke();      // No border on the next thing drawn

        // Print a list of the serial ports for debugging purposes
        // if using Processing 2.1 or later, use Serial.printArray()
        println(Serial.list());

        // I know that the first port in the serial list on my Mac is always my FTDI
        // adaptor, so I open Serial.list()[0].
        // On Windows machines, this generally opens COM1.
        // Open whatever port is the one you're using.
        String portName = Serial.list()[0];
        myPort = new Serial(this, portName, 9600);
      }

      void draw() {
        // read a byte from the serial port:
        if ( myPort.available() > 0) {
        inByte = myPort.read();
        }
        //print(inByte);
        // if this is the first byte received, and it's an A, clear the serial
        // buffer and note that you've had first contact from the microcontroller.
        // Otherwise, add the incoming byte to the array:
        if (firstContact == false) {
          if (inByte == 'A') {
            myPort.clear();          // clear the serial port buffer
            firstContact = true;     // you've had first contact from the microcontroller
            myPort.write('A');       // ask for more
            println(inByte);
          }
        }
        else {
            val = myPort.readStringUntil('\n');         // read it and store it in val
            println(val); //print it out in the console
            values = float(splitTokens(val, ","));

            myPort.write('A');
            delay(20);
          }
        }

title: Arduino and Processing Call and response not working

Answers: 1

body:
Why not just send all the data at once, in a comma separated list, with a `\n` char as a "end of message" delimiter?

Here are 2 test sketches. The Arduino sketch sends the A0 to A2 values to serial every 500ms, and the Processing sketch displays the received data. Parsing the received data into an integer array is more of a Java question, not an Arduino one, so I'll leave that up to you.

**Arduino**

    // Send the values of A0, A1 and A3
    // to serial every 500ms.
    // 2416 bytes.
    char data[20];
    char buffer[6];

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

    void loop(){
      itoa(analogRead(A0), buffer, 10);
      strcat(data, buffer);
      strcat(data, ",");
      itoa(analogRead(A1), buffer, 10);
      strcat(data, buffer);
      strcat(data, ",");
      itoa(analogRead(A2), buffer, 10);
      strcat(data, buffer);
      strcat(data, "\n");
      Serial.write(data);
      memset(data, 0, sizeof(data));
      delay(500);
    }

**Processing**

    // Display the data received from the serial port, sent every
    // 500 ms from the Arduino. The values sent are from A0, A1
    // and A2, and were sent concatenated together, as a comma
    // separated list, followed by a \n char.
    import processing.serial.*;
    import java.awt.TextArea;
    Serial myPort;
    TextArea myTextArea;
    String input;

    void setup(){

      try{
        myPort = new Serial(this, Serial.list()[0], 9600);
      }
      catch(Exception e){
        System.err.println(e);
        e.printStackTrace();
      }

      myTextArea = new TextArea("", 23, 49, 1);
      this.add(myTextArea);

      size(500, 380);

    }

    void draw(){

      if(myPort.available() > 0){
        input = myPort.readStringUntil('\n');
        myTextArea.append(input);
      }

    }

**EDIT**

As Juraj mentions in his comments, I could have just used `Serial.print()` 6 times instead of the `char` arrays. Here is a second Arduino sketch that uses `Serial.print()`. Before you use it, be aware that it's compile size is 288 bytes **more** than the `char` array method. Imagine that :)

    // Send the values of A0, A1 and A3
    // to serial every 500ms.
    // 2704 bytes.
    void setup(){
      Serial.begin(9600);
    }

    void loop(){
      Serial.print(analogRead(A0));
      Serial.print(",");
      Serial.print(analogRead(A1));
      Serial.print(",");
      Serial.print(analogRead(A2));
      Serial.print("\n");
      delay(500);
    }


body:
During a programming contest, I used the following line of code:

    symbols[i] = random() & 0b11;

After the contest, when I looked into the Arduino reference, I found out random takes one or two parameters. Based upon that, I would expect the code not to compile. However, this code somehow worked as I expected. (Assigning a random number from 0 to 3) How come?

title: Random without parameters

Answers: 1

body:
Simple: `random()` isn't an Arduino function - it's a standard C function.

> **Function random()**
>
> `long random(void)`
>
> The `random()` function computes a sequence of pseudo-random integers in the range of 0 to `RANDOM_MAX` (as defined by the header file `<stdlib.h>`).
>
> The `srandom()` function sets its argument seed as the seed for a new sequence of pseudo-random numbers to be returned by `rand()`. These sequences are repeatable by calling `srandom()` with the same seed value.
>
> If no seed value is provided, the functions are automatically seeded with a value of 1.
>
> -- [AVR LIBC Manual Page](https://www.microchip.com/webdoc/AVRLibcReferenceManual/group__avr__stdlib_1ga114aeb1751119382aaf3340355b22cfd.html)


body:
I've got a USB keyboard connected to my Arduino Uno with a USB Host Shield. I'm reading keystrokes using [this example][1] from the USB Host Shield library.

I need to toggle the LEDs in the keyboard (that indicate the state of Caps Lock, Num Lock etc.)

[This thread][2] mentions using `Usb.setReport()`, but this method doesn't seem to exist any more: there's no such method in [Usb.cpp][3] in the library. There does seem to be [a method][4] called `SetReport` in the USBHID class, which looks like it takes the same arguments, which I'm trying to use.

What I'm currently doing:

    void keyboard_setup(){
        static HIDBoot<USB_HID_PROTOCOL_KEYBOARD> HidKeyboard(&Usb);
        if (Usb.Init() == -1) {
            Serial.println("OSC did not start.");
        }
        delay(200);
        HidKeyboard.SetReportParser(0, &Prs);

        static USBHID usbhid(&Usb);
        uint8_t leds = 1;
    #define KBD_ADDR 1
    #define KBD_IF 0
        usbhid.SetReport( KBD_ADDR, 0, 1, KBD_IF, 0, &leds );
        delay(100);
        leds = 255;
        usbhid.SetReport( KBD_ADDR, 0, 1, KBD_IF, 0, &leds );
        delay(100);

Neither call to SetReport seems to work, and I'm not certain the values of KBD_ADDR or KBD_IF are correct (I'm using ones that I've seen in examples), or event that calling SetReport is right .

What am I doing wrong?

  [1]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/examples/HID/USBHIDBootKbd/USBHIDBootKbd.ino
  [2]: http://forum.arduino.cc/index.php?topic=300560.0
  [3]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/Usb.cpp
  [4]: https://github.com/felis/USB_Host_Shield_2.0/blob/06d5ed134a37e22575c0ce18c061d9ef115151e0/usbhid.h#L185

title: Controlling keyboard LEDs with USB Host Shield

Answers: 1

body:
> There does seem to be [a method][4] called `SetReport` in the USBHID class, which looks like it takes the same arguments, which I'm trying to use.

The method arguments of the new `SetReport()` method aren't quite the same and some are in a different order.

The old method signature was:

```
uint8_t setReport( uint8_t addr, uint8_t ep, unsigned int nbytes, uint8_t interface, uint8_t report_type, uint8_t report_id, uint8_t* dataptr );
```

...while the new one is:

```
uint8_t SetReport(uint8_t ep, uint8_t iface, uint8_t report_type, uint8_t report_id, uint16_t nbytes, uint8_t* dataptr);
```

It seems to me the equivalent call would be:

```
usbhid.SetReport( 0, KBD_IF, 0x02, 0, 1, &leds );
```

[4]: https://github.com/felis/USB_Host_Shield_2.0/blob/06d5ed134a37e22575c0ce18c061d9ef115151e0/usbhid.h#L185


body:
I am working on a project using an Arduino control a Stepper Motor. The motor drives a lead screw which moves coloured filters to specific positions along a linear track - forwards and backwards.
The movements are triggered by another device that counts its revolutions (using a sensor. The Arduino reads the inputs and activates the motor on specific revs ie. at 10 move 70mm forwards, at 30 move 70mm backwards.
I can control the Stepper to execute precise moves repeatedly one after another, independently of the counter. I can link the Arduino to the counter and switch on/off an LED at specified counts. But when I try to run the motors from the counter, it's triggered but only moves in tiny discontinuous steps, and only goes one way. Here is that Sketch below. Any help very welcome. Thanks.
```

// this constant won't change:
const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 7;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include <AccelStepper.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

void forwardstep1() {
  myMotor->onestep(FORWARD, DOUBLE);
}
void backwardstep1() {
  myMotor->onestep(BACKWARD, DOUBLE);
}

AccelStepper Astepper1(forwardstep1, backwardstep1);

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz
  TWBR = ((F_CPU / 500000l) - 16) / 2; // Change the i2c clock to 400KHz
  Astepper1.setAcceleration(6000.0);
  Astepper1.setMaxSpeed(600);
  Astepper1.setSpeed(600);    // rpm
  //  while (switchIsOff) {
  //turn servo one direction -
  //tell servo this is 0
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(buttonPushCounter);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
  }
  // save the current state as the last state, for next time through the loop
  lastButtonState = buttonState;

  if (buttonPushCounter == 10) {
    digitalWrite(ledPin, HIGH);
    Astepper1.moveTo(600);
    Astepper1.setSpeed(600);
    Astepper1.run();
  }

  if (buttonPushCounter == 30) {
    digitalWrite(ledPin, LOW);
    Astepper1.moveTo(200);
    Astepper1.setSpeed(600);
    Astepper1.run();
  }

  }
}

title: Controlling a Stepper Motor - sending to specific positions on a 'buttonPushCounter ==' cue, forwards and backwards

Answers: 2

body:
There are several `run`-like methods in the AccelStepper library.

The one you are using, `run()`, is intended to be called at **EVERY** pass through `loop()`, and it will only cause a step if one is necessary, based on the internal state of the library (i.e., current position, target position, acceleration profile, etc.) It is safe to call so often -- it will determine itself if there is any motion needed.

You could move the `run()` call to a place inside `loop()`, but outside of any `if` statements.

Alternatively, there is a `runToPosition()` function, which is blocking -- it will stop all execution of your code until the stepper is at the target position. This would be fine for your current code as posted, but if you wish to monitor the revolution counter also, then this would not be the best option to take.

body:
Thanks. Your description of the fault makes sense to me. As you point out blocking would be a problem as I need the counter to continue to be registering while the movement is being executed. I've revised the script as you suggest - inside the loop but outside the if statement - have I done as you meant? But the same problem occurs - the motor advances in single steps.
````

// this constant won't change:
const int  buttonPin = 2;    // the pin that the pushbutton is attached to
const int ledPin = 7;       // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include <AccelStepper.h>

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);

void forwardstep1() {
  myMotor->onestep(FORWARD, DOUBLE);
}
void backwardstep1() {
  myMotor->onestep(BACKWARD, DOUBLE);
}

AccelStepper Astepper1(forwardstep1, backwardstep1);

void setup() {
  // initialize the button pin as a input:
  pinMode(buttonPin, INPUT);
  // initialize the LED as an output:
  pinMode(ledPin, OUTPUT);
  // initialize serial communication:
  Serial.begin(9600);
  AFMS.begin();  // create with the default frequency 1.6KHz
  //AFMS.begin(1000);  // OR with a different frequency, say 1KHz
  TWBR = ((F_CPU / 500000l) - 16) / 2; // Change the i2c clock to 400KHz
  Astepper1.setAcceleration(6000.0);
  Astepper1.setMaxSpeed(600);
  Astepper1.setSpeed(600);    // rpm
  //  while (switchIsOff) {
  //turn servo one direction -
  //tell servo this is 0
}

void loop() {
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button went from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes: ");
      Serial.println(buttonPushCounter);
    } else {
      // if the current state is LOW then the button went from on to off:
      Serial.println("off");
    }
    // save the current state as the last state, for next time through the loop
    lastButtonState = buttonState;

    if (buttonPushCounter == 10 ) {
      digitalWrite(ledPin, HIGH);
      Astepper1.moveTo(20000);
      Astepper1.setAcceleration(6000.0);
      Astepper1.setSpeed(600);
      //Astepper1.setSpeed(600);
      Astepper1.run();
    }
    Astepper1.run();//this command moved out of an 'if' statement, but still within the 'loop'

    if (buttonPushCounter == 30) {
      digitalWrite(ledPin, LOW);
      Astepper1.moveTo(200);
      Astepper1.setSpeed(600);
    }
    Astepper1.run();//this command moved out of an 'if' statement, but still within the 'loop'

  }


body:
I'm recently having a hard time with my Arduino project. I'm trying to control a seven-segment display (it has a microcontroller on it) with an encoder, and I'm trying so that everytime I rotate the encoder it adds 5 to the number on the display. What am I doing wrong here???

P.S: there are some parts that are for controlling relays, they are not related to the issue. I removed them on this thread on purpose.

Code (without any attempts to change the added amount to the display):

    #include <RotaryEncoder.h>
    #include <TM1637Display.h>

    // Module connection pins (Digital Pins)
    #define CLK 10
    #define DIO 11

    // Setup a RoraryEncoder for pins A2 and A3:
    RotaryEncoder encoder(A2, A3);

    // The amount of time (in milliseconds) between tests
    #define TEST_DELAY   1000

    TM1637Display display(CLK, DIO);

    void setup()
    {
        Serial.begin(57600);
        Serial.println("SimplePollRotator example for the RotaryEncoder
        library.");
    }

    // The Interrupt Service Routine for Pin Change Interrupt 1
    // This routine will only be called on any signal change on A2 and A3:
    //exactly where we need to check.
    ISR(PCINT1_vect) {
        encoder.tick(); // just call tick() to check the state.
    }

    // Read the current position of the encoder and print out when changed.
    void loop()
    {
        static int pos = 0;
        int newPos = encoder.getPosition();
        if(newPos > -1)
        {
            if (pos != newPos) {
                Serial.print(newPos);
                Serial.println();
                pos = newPos + 4;
                display.setBrightness(0x0f);
                // All segments on
                // Show decimal numbers with/without leading zeros
                display.showNumberDec(newPos, true); // Expect: 1234
                delay(100);
            }
        } // if
    } // loop ()
    // The End

title: How to add numbers to a position when controlling a seven-segment display

Answers: 1

body:
In your code, you call:

    newPos = encoder.getPosition();

which grabs the absolute position of the encoder. When you rotate this one step, the value of `newPos` goes up (or down) by one.

Then, you make `pos = newPos + 4`, which simply adds 4 to the value that is going up or down by one step at a time.

    newPos: 1    pos: 5
    newPos: 2    pos: 6
    newPos: 3    pos: 7
    newPos: 4    pos: 8
    newPos: 5    pos: 9

Instead, it sounds like you wish the display to always read 5 times the encoder position. If so, then you should write `pos = newPos*5`.

    newPos: 1    pos: 5
    newPos: 2    pos: 10
    newPos: 3    pos: 15
    newPos: 4    pos: 20
    newPos: 5    pos: 25

Then, when you write to the display, you do so as:

    display.showNumberDec(newPos, true); // Expect: 1234

But `newPos` is not the newly calculated value. Instead, call

    display.showNumberDec(pos, true); // Expect: 1234


body:
Im working in a project where i have to deal with multiple sensor data.

1. BME 280
2. WindSpeed Sensor
3. Water level Sensor x 10
4. Soil moisture x 5
5. Soil pH sensor x 2

i have found this code for both arduino uno and nodemcu esp8266

    //Arduino code
    #include <SoftwareSerial.h>
    SoftwareSerial s(5,6);

    void setup() {
    s.begin(9600);
    }

    void loop() {
    int data=50;
    if(s.available()>0)
    {
     s.write(data);
    }
    }

    //for nodeMCU
    #include <SoftwareSerial.h>
    SoftwareSerial s(D6,D5);
    int data;
    void setup() {
    s.begin(9600);
    Serial.begin(9600);
    }

    void loop() {
      s.write("s");
      if (s.available()>0)
      {
        data=s.read();
        Serial.println(data);
      }
    }

**In this code here send 1 value from arduino uno to nodeMCU...
but if i want to send 10 values(float temperature,humidity,pressure,waterlevel,windSpeed,windDirection) from mega to nodeMCU using serial, how to do that using serail.**

title: Sending data from Arduino Mega to nodeMCU using serial (Multiple sensor data) & upload to firebase

Answers: 1

body:
As i know nodemcu still not  work as a slave device . Maybe this support will be available in the future but if you test it and it work . This how to do it
Let's assume you have tow dat to send cast them to string , concatenated characters of string_data1+string_data2 then send theme via uart communication to the nodemcu .
Now in the nodemcu take the string and decoding  [split] string to string 1 and string 2 and cast theme again to any var type you want.
If this method seems so hard to you or your level in coding is still under development use some library exist that can do the work for you i recommend. The easytransfer library by madsci1016 in github [enter link description here][1].

  [1]: https://github.com/madsci1016/Arduino-EasyTransfer


body:
`Arduino.h` defines `LOW` as `0x0` and `HIGH` as `0x1`. Does the Arduino API intend to expose that fact? Does it guarantee that this will always be that way?

In other words, what is the intended purpose of these manifest constants: `LOW` and `HIGH`?

* Is this purely cosmetic mnemonics added as an alternative for `0/1` and `false/true`, for those who like `LOW/HIGH` better?

* Or is this an attempt to abstract/isolate the user's source code from the actual representation of `LOW` and `HIGH` (e.g. in case the representation changes in the future)?

The underlying reason for this question is to figure out whether code like

    digitalWrite(some_pin, true);
    digitalWrite(some_other_pin, !digitalRead(some_other_pin));

is a good programming practice. (If `LOW` and `HIGH` are there to abstract the user's code form their actual values then code like that is definitely a bad programming practice.)

title: `LOW` being defined as `0` and `HIGH` being defined as `1` - is this a part of external specification?

Answers: 1

body:
> The underlying reason for this question is to figure out whether code like
>
>     digitalWrite(some_pin, true);
>     digitalWrite(some_other_pin, !digitalRead(some_other_pin));
>
> is a good programming practice. (If LOW and HIGH are there to abstract the user's code form their actual values then code like that is definitely a bad programming practice.)

Strictly speaking, no, that is not good programming practice.

`digitalRead()` returns an `int`. `digitalWrite()` expects an `int`.  Using `!` converts the `int` into a `bool` and then it's promoted back to an `int` again.

In fact, the "next gen" Arduino core API changes HIGH and LOW from a simple `int` to an `enum` - and that struggles with casting through `bool` like that:

    typedef enum {
      LOW     = 0,
      HIGH    = 1,
      CHANGE  = 2,
      FALLING = 3,
      RISING  = 4,
    } PinStatus;

You can see the problems that causes [here](https://arduino.stackexchange.com/questions/63624/cannot-convert-bool-to-pinstatus-for-argument-2-to-void-digitalwritepin).


body:
I'm trying to create a function that enters a key/value into a JSON file.

But, since value can be an `int` or `char`, I don't want to create 2 functions for each type.

Is there a way ?

    void setValue(char *key, char* value){
            StaticJsonDocument<512> tempJDOC;
            tempJDOC[key]=value;
    }

**EDIT1**

    #ifndef myJSON_h
    #define myJSON_h

    #include "Arduino.h"
    #include <ArduinoJson.h>
    #include "FS.h"

    class myJSON
    {
    private:
    bool _useSerial=false;
    char _filename[30];

    public:
    char *ver="myJSON_v1.1";
    myJSON(char *filename, bool useserial=false);

    bool file_exists();
    bool file_remove();
    bool format ();
    bool FS_ok();

    void saveJSON2file(JsonDocument& _doc);
    void readJSON_file(JsonDocument& _doc);

    void printJSON(JsonDocument& _doc);
    void PrettyprintJSON(JsonDocument& _doc);

    const char *getValue (char *key);

    template <class T>
    void setValue(const char *key, T value);
    //void setValue(const char *key, char *value);

    };
    #endif

**EDIT2**

    #ifndef myJSON_h
    #define myJSON_h

    #include "Arduino.h"
    #include <ArduinoJson.h>
    #include "FS.h"

    #define LOG_LENGTH 4
    #define DOC_SIZE 512

    template <class T> // . <---- line added
    class myJSON
    {
    private:
    bool _useSerial=false;
    char _filename[30];

    public:
    char *ver="myJSON_v1.1";
    myJSON(char *filename, bool useserial=false);

    bool file_exists();
    bool file_remove();
    bool format ();
    bool FS_ok();

    void saveJSON2file(JsonDocument& _doc);
    void readJSON_file(JsonDocument& _doc);

    void printJSON(JsonDocument& _doc);
    void PrettyprintJSON(JsonDocument& _doc);

    const char *getValue (const char *key);
    void removeValue(const char *key);
    // void setValue(const char *key, char *value); <--- comment out
    void updateArray(char* array_key, int val);
    void printFile();
    void setValue(const char *key, T value); <---- Added

    };
    #endif

and in .cpp file :

    void myJSON::setValue(const char *key, T value){
            StaticJsonDocument<512> tempJDOC;
            myJSON::readJSON_file(tempJDOC);
            tempJDOC[key]=value;
            myJSON::saveJSON2file(tempJDOC);
            myJSON::PrettyprintJSON(tempJDOC);
    }

title: Is it possible that function will get a parameter that can be int OR char?

Answers: 2

body:
In C++ you can create a template function. (The ArduinoJson `[]` operator is a template too.)

    #include <ArduinoJson.h>

    StaticJsonDocument<512> tempJDOC;

    template <typename T>
    void setValue(const char *key, T value){
      tempJDOC[key] = value;
    }

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

      setValue("a", 5);
      setValue("b", "xyz");

      serializeJson(tempJDOC, Serial);
    }

    void loop() {
    }

the compiler will create function based on this template for every different type you use as second parameter in your sketch

body:
The short answer is “no, it's not possible”. You will have to use two
different functions. These two functions can share the same name, using
[function overloading][overloading]. You can even have the compiler
write these functions for you, based on a template you provide, as shown
in Juraj's answer. These language features help provide the illusion of
there being a single function. But it's just an illusion, albeit a
useful one that helps with program readability. At the fundamental
level, you still have two different functions.

[overloading]: https://www.programiz.com/cpp-programming/function-overloading


body:
i want to make the stuff, which the output is written from the analogread, but when the A3 == HIGH, the output pin 9 is used, but when the A3 == LOW, the output pin 10 is used, and when i simulate it on proteus, it seems not the same as i mean, what's wrong with the code, please need your help.

      int hasil
      int reado;
      int z;
      int baca;
      bool en = false;
      void setup() {
      // put your setup code here, to run once:

      TCCR1A = 0b00100010;
      TCCR1B = 0b00011001;
      TCCR0A = 0; TCCR0B = 0;
      ICR1 = 100000;//disable millis, delay and mciroseconds function
      //disable millis, delay and mciroseconds function

       // put your setup code here, to run once:
      Serial.begin(115200);
      pinMode(A2, INPUT); pinMode(A3, INPUT);
      pinMode(9,OUTPUT); pinMode(10,OUTPUT);
      }

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

     hasil = analogRead(A2);
     baca = digitalRead(A3);
     for (z=0; z<=hasil; z++)
     reado = map (hasil, 0, 255, 0, ICR1);
     if (hasil > 30 && baca == HIGH)
     {analogWrite(9,hasil); analogWrite(10,0);}
     else if (hasil >30 && baca == LOW)
     {analogWrite(9,0); analogWrite(10,hasil);}
     else if (hasil<30)
     {analogWrite(9, 0);
     analogWrite(10, 0);}}

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/bgyVj.png

title: the code and the actual output didn't match

Answers: 2

body:
The problem as i can see exist in the if else statements . You use multiple else if statements but in the end you must end it with else statement .
Use the “if/else if” if you need to choose either one or none of a series of options. You could write the above program using separate if statements such as show below but the if/else if approach is cleaner and better indicates that the program should choose either one or none of the options
Here how you do it
If (){}....
Else if (){}.....
Else if(){} ......
Else{}
here this can help you [enter link description here][1]

  [1]: http://web.engr.oregonstate.edu/~rookert/cs162/ecampus-video/CS161/template/chapter_4/ifelse.html

body:
You wrote:

> when i simulate it on proteus, it seems not the same as i mean

The attached picture is not very clear, but it seems to me that it's
doing exactly what you asked for: a PWM output that switches between two
different output pins. The program should work as expected, with only a
few caveats. Let me comment it in some detail:

    ICR1 = 100000;

Here you are setting `ICR1` to 34464 (i.e. 100000 modulo
216). This is likely not what you mean...

    Serial.begin(115200);

There is no point in initializing the serial interface if you are not
going to use it.

    for (z = 0; z <= hasil; z++)
        reado = map(hasil, 0, 255, 0, ICR1);

There is no point in calculating many times the exact same value.
Actually, there is no point in calculating it even a single time, since
you are not using the result anywhere in your program.

    analogWrite(9, hasil);

Here you are setting the duty cycle to some number between 31 and 1023.
Given that the top value of the timer is 34464, the actual duty cycle
will always be less than 3%. This is the reason why it looks like a
series of narrow spikes on the virtual scope.

But maybe what you really meant is

    reado = map(hasil, 0, 1023, 0, ICR1); // note: 1023, not 255
    analogWrite(9, reado);

I would not recommend using `analogWrite()` with a non-standard top
counter value. There is a special case handled in `analogWrite()` where,
if the argument happens to be 255, you get instead a
`digitalWrite(pin, HIGH)`. This is most likely _not_ what you want. Now
that you started controlling the timer with raw IO access, you should
continue this way.

    else if (hasil < 30)

Did you consider what the program should do if `hasil` happens to be
exactly 30? None of the if/else cases would then match. You probably
meant

    else if (hasil <= 30)

but, as suggested by user11249082's answer, a plain `else` is the best
way to ensure you did cover all possible cases.


body:
I'm new to this so there are some poor methods in my code when I try to introduce the LCD into the loop. My issue is that the LCD delay and the servo delay are interfering with each other. How can I isolate them? I like the 50ms response for the servo. But I would like maybe a 200ms refresh for the LCD. But in their current state they are giving a very odd response if I have them both in the loop. The servo is spinning slower as though it's adding both delays. If I disable the LCD it all goes back to normal. Any ideas? Could someone please show me the correct method so I can expand in the future? Thanks!!!!

I've got this so far:

    #include<Wire.h>
    const int MPU_addr=0x68;  // I2C address of the MPU-6050
    int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

    //SERVO
    #include <Servo.h>
    Servo microservo1;
    int servo_pin = 8;

    //MAPPED VALUES
    int16_t AcXmapped, AcYmapped, AcZmapped;

    //LCD
    #include <LiquidCrystal.h>
    const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
    //initializes the library

    void setup(){

      //SERVO SETUP
      microservo1.attach ( servo_pin );

      //WIRE SETUP
      Wire.begin();
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x6B);  // PWR_MGMT_1 register
      Wire.write(0);     // set to zero (wakes up the MPU-6050)
      Wire.endTransmission(true);
      Serial.begin(9600);
      Serial.println("Transmission Line Initializing");
      delay(350);
      //print("3"); print("2"); print("1");
      Serial.println("3");
      delay(1000);
      Serial.println("2");
      delay(1000);
      Serial.println("1");
      delay(1000);

      //LCD SETUP
      lcd.begin(16,2); //setup LCD number of columns and rows
      digitalWrite(9,1); //can either go 0 --> 1 or LOW --> HIGH || turns LCD on or off ||
      analogWrite(6,70); //contrast setting for the text on the LCD
    }

    void loop(){

      //WIRE LOOP
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
      AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
      AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
      AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
      Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
      GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
      GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
      GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
      Serial.print(" | AcX = "); Serial.print(AcX);
      Serial.print(" | AcY = "); Serial.print(AcY);
      Serial.print(" | AcZ = "); Serial.print(AcZ);
      //Serial.print(" | Tmp =  "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
      Serial.print(" | GyX = "); Serial.print(GyX);
      Serial.print(" | GyY = "); Serial.print(GyY);
      Serial.print(" | GyZ = "); Serial.println(GyZ);

      //MAPPING the values from e.g. AcX to AcXmapped so they're better values for servo control.
      //set the AcX inside the map to negative if you want to invert the rotation of the servo.
      AcXmapped = map (AcX, -17000, 17000, 0, 180); //ROLL
      AcYmapped = map (AcY, -17000, 17000, 0, 180); //PITCH
      AcZmapped = map (AcZ, -17000, 17000, 0, 180); //YAW

      //SERVO LOOP
      microservo1.write(AcYmapped);
      //50 ms response between movements
      delay(50);

      //LCD LOOP
      lcd.setCursor(0,0); //set the cursor to (0,0)
      lcd.print(AcYmapped);
      delay(50);

      //EXTRA LCD
      lcd.noAutoscroll(); //turns off autoscroll
      lcd.clear(); //clears the screen for the next loop

    }

title: Cannot make LCD & Gyro work together

Answers: 2

body:
First upload the msg errors you've get .
Second the lcd can't display values in realtime because when the gyroscope move the arduino blocking the lcd and reading the data from gyroscope because you using no scheduling coding.
I recommend you to use millis  instead of delays and use  multitasking code like freertos .

body: Don't use `delay()` at all. You need to refactor your code to record the value of `millis()` at the beginning of a time interval and then wait until the new value of `millis()` is greater by the desired interval. Do a google search on "Arduino blink without delay" for articles that discuss this coding technique. It's a fundamental of programming for a single-threaded microcontroller like the Arduino, and something you must learn to do if you're going to write anything of any complexity for the platform.


body:
I am trying to determine the dev path of a USB keyboard running an Arduino Pro Micro on my Ubuntu 18.04 system. The files /dev/ttyACM0 and /dev/ttyUSB0 do not exist.

When I run dmesg I get:

    [  410.770931] usb 3-3: new full-speed USB device number 3 using xhci_hcd
    [  410.962180] usb 3-3: New USB device found, idVendor=feed, idProduct=3060, bcdDevice= 0.01
    [  410.962184] usb 3-3: New USB device strings: Mfr=1, Product=2, SerialNumber=3
    [  410.962187] usb 3-3: Product: Dactyl-Manuform (5x6)
    [  410.962189] usb 3-3: Manufacturer: tshort
    [  410.962191] usb 3-3: SerialNumber: 0
    [  411.006440] input: tshort Dactyl-Manuform (5x6) as /devices/pci0000:00/0000:00:07.1/0000:11:00.3/usb3/3-3/3-3:1.0/0003:FEED:3060.0008/input/input27
    [  411.063192] hid-generic 0003:FEED:3060.0008: input,hidraw0: USB HID v1.11 Keyboard [tshort Dactyl-Manuform (5x6)] on usb-0000:11:00.3-3/input0
    [  411.089097] input: tshort Dactyl-Manuform (5x6) Mouse as /devices/pci0000:00/0000:00:07.1/0000:11:00.3/usb3/3-3/3-3:1.1/0003:FEED:3060.0009/input/input28
    [  411.147172] input: tshort Dactyl-Manuform (5x6) System Control as /devices/pci0000:00/0000:00:07.1/0000:11:00.3/usb3/3-3/3-3:1.1/0003:FEED:3060.0009/input/input29
    [  411.147297] input: tshort Dactyl-Manuform (5x6) Consumer Control as /devices/pci0000:00/0000:00:07.1/0000:11:00.3/usb3/3-3/3-3:1.1/0003:FEED:3060.0009/input/input30
    [  411.147395] hid-generic 0003:FEED:3060.0009: input,hidraw1: USB HID v1.11 Mouse [tshort Dactyl-Manuform (5x6)] on usb-0000:11:00.3-3/input1

Dactyl-Manuform is the keyboard so it seems to recognize the device. The command lsusb returns several usb devices. The entry with no title is the keyboard (based on doing watch lsusb):

    Bus 004 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
    Bus 003 Device 003: ID feed:3060
    Bus 003 Device 002: ID 045e:02d1 Microsoft Corp. XBOX One Controller for Windows
    Bus 003 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
    Bus 001 Device 002: ID 1e7d:2c2e ROCCAT
    Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

I have installed arduino and arduino-core from the official repos.

However, I still cannot get a ttyACM0 or ttyUSB0 to appear, and in the Arduino IDE the "Serial Port" option is greyed out (even when using sudo).

What can I check for to either 1) get the ttyACM0 file to exist for my Arduino device or 2) find some other dev port to use as the serial port?

title: No ttyACM0 with Pro Micro on Ubuntu 18.04

Answers: 1

body:
A Pro Micro will only give a /dev/ttyACMx device node if the firmware installed on it creates a CDC/ACM interface.  That device obviously is running custom firmware which only provides the interfaces that the manufacturer wants to provide - in this case keyboard and mouse interfaces.

To use it as an Arduino you will first have to install the Arduino bootloader. That will then remove the existing manufacturer firmware, and you will have to write your own to make it act as a keyboard again.


body:
I'm trying to make my first chip send data through a nrf24 radio pipe and the other listen to it. After the first data is received it should switch to transmit mode and itself transmit new data. The main goal of all of this is to implement the raft protocol with at least 3 chips participating. So the requirements would be to have each chip listening all the time and to have it stop listening at random intervals to send a broadcast message to all other chips. Basically the communication is never between just two chips but always one to many. I've come across tutorials such as http://forum.arduino.cc/index.php?topic=421081 but it always comes down to a stable Master vs Slaves state while my situation is more dynamic.
This is my current task. The listener works perfectly until the first received message when it opens a writing pipe. It then does not write and does not go back to listening.

```
void test_Task(void *pvParameters){

 printf("some init\n");
 bool hastoSend = false;

 radio.openReadingPipe(1, address);
 while(1){

  radio.startListening();
  if (radio.available()) {
   radio.read(&rx_data, sizeof(rx_data));

    if (rx_data[1] == 101){
     printf("Received message: %d\n", rx_data[1]);
     hastoSend = true;
     printf("%d\n",rx_data[0]);
     //int someint = *((int*)pvParameters);

     // turn on led1
     write_byte_pcf(led1);
     vTaskDelay(pdMS_TO_TICKS(200));
     write_byte_pcf(0xff);
    }

  }else{
    if (hastoSend){

     printf("I need to send a message!\n");
     printf("sending a message\n");
     radio.openWritingPipe(address2);
     radio.stopListening();
     transmit_nrf24();
     radio.printDetails();
     hastoSend = false;
     radio.openReadingPipe(1, address);

    }
  }

 }

}
```

This is my radio setup:

```
static inline void setup_nrf() {

 uart_set_baud(0, 115200);
 gpio_enable(SCL, GPIO_OUTPUT);
 gpio_enable(CS_NRF, GPIO_OUTPUT);

 // radio configuration
 radio.begin();
 radio.setChannel(channel);
 radio.setAutoAck(false);

}
```

For testing purposes the messages being transmitted come from my other device which is just a manual transmitter. What would solve my problem is a way to completely reset the radio when the first message is received so that the pipes do not bother each other and the device could then be re-initialised as a transmitter.

Cheers!

title: Implementing sending from N and recieving from N with FreeRtos and RF24 radio module

Answers: 1

body:
Solved it by simply repeating

    gpio_enable(SCL, GPIO_OUTPUT);
    gpio_enable(CS_NRF, GPIO_OUTPUT);

    // radio configuration
    radio.begin();
    radio.setChannel(channel);
    radio.setAutoAck(false);

before opening a new writing pipe.