text:
How do i efficiently write this code for PS2 controller to USB convertion sketch for Arduino Pro Micro?
I am really new to coding and building stuff, so forgive me if it is anything offensive.i have been trying to convert my PS2 dualshock controller to USB using arduino. there is a library called ps2x that i can use to read the data and Joystick.h library to send it over USB-HID.
i just want to know if this is efficient code, if not how can i improve it.
This is the loop:

 ps2x.read_gamepad(); //This needs to be called at least once a second
                        // to get data from the controller.

  Joystick.setXAxis(ANALOGSTATE1); //Joystick.setButton(-127 to 127); 0 is center
  Joystick.setYAxis(ANALOGSTATE2);
  Joystick.setZAxis(ANALOGSTATE3);
  Joystick.setThrottle(ANALOGSTATE4); //This one is different, (0 to 255) 127 is center

  Joystick.setButton(0, DIGITALSTATE1); //Joystick.setButton(0-31, 0-1);
                                        //Joystick.setButton(Select Button to Use, Specify ON/OFF of Button);
  Joystick.setButton(1, DIGITALSTATE2);
  Joystick.setButton(2, DIGITALSTATE3);
  Joystick.setButton(3, DIGITALSTATE4);
  Joystick.setButton(4, DIGITALSTATE5);
  Joystick.setButton(5, DIGITALSTATE6);
  Joystick.setButton(6, DIGITALSTATE7);
  Joystick.setButton(7, DIGITALSTATE8);
  Joystick.setButton(8, DIGITALSTATE9);
  Joystick.setButton(9, DIGITALSTATE10);
  Joystick.setButton(10, DIGITALSTATE11);
  Joystick.setButton(11, DIGITALSTATE12);
  Joystick.setButton(12, DIGITALSTATE13);
  Joystick.setButton(13, DIGITALSTATE14);
  Joystick.setButton(14, DIGITALSTATE15);
  Joystick.setButton(15, DIGITALSTATE16);

if(ps2x.ButtonPressed(PSB_TRIANGLE)) {
  DIGITALSTATE1 = 1;
}
  else if (ps2x.ButtonReleased(PSB_TRIANGLE)){
  DIGITALSTATE1 = 0;
}
if(ps2x.ButtonPressed(PSB_CIRCLE))
  {
    DIGITALSTATE2 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_CIRCLE)){
    DIGITALSTATE2 = 0;
  }
if(ps2x.ButtonPressed(PSB_CROSS))
  {
    DIGITALSTATE3 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_CROSS)){
    DIGITALSTATE3 = 0;
  }
if(ps2x.ButtonPressed(PSB_SQUARE))
  {
    DIGITALSTATE4 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_SQUARE)){
    DIGITALSTATE4 = 0;
  }
if(ps2x.ButtonPressed(PSB_PAD_RIGHT))
  {
    DIGITALSTATE5 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_PAD_RIGHT)){
    DIGITALSTATE5 = 0;
  }
if(ps2x.ButtonPressed(PSB_PAD_UP))
  {
    DIGITALSTATE6 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_PAD_UP)){
    DIGITALSTATE6 = 0;
  }
if(ps2x.ButtonPressed(PSB_PAD_LEFT))
  {
    DIGITALSTATE7 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_PAD_LEFT)){
    DIGITALSTATE7 = 0;,
  }
if(ps2x.ButtonPressed(PSB_PAD_DOWN))
  {
    DIGITALSTATE8 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_PAD_DOWN)){
    DIGITALSTATE8 = 0;
  }
if(ps2x.ButtonPressed(PSB_L1))
  {
    DIGITALSTATE9 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_L1)){
    DIGITALSTATE9 = 0;
  }
if(ps2x.ButtonPressed(PSB_L2))
  {
    DIGITALSTATE10 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_L2)){
    DIGITALSTATE10 = 0;
  }
if(ps2x.ButtonPressed(PSB_R1))
  {
    DIGITALSTATE11 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_R1)){
    DIGITALSTATE11 = 0;
  }
if(ps2x.ButtonPressed(PSB_R2))
  {
    DIGITALSTATE12 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_R2)){
    DIGITALSTATE12 = 0;
  }
if(ps2x.ButtonPressed(PSB_L3))
  {
    DIGITALSTATE13 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_L3)){
    DIGITALSTATE13 = 0;
  }
if(ps2x.ButtonPressed(PSB_R3))
  {
    DIGITALSTATE14 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_R3)){
    DIGITALSTATE14 = 0;
  }
if(ps2x.ButtonPressed(PSB_START))
  {
    DIGITALSTATE15 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_START)){
    DIGITALSTATE15 = 0;
  }
if(ps2x.ButtonPressed(PSB_SELECT))
  {
    DIGITALSTATE16 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_SELECT)){
    DIGITALSTATE16 = 0;
  }

  ANALOGSTATE1 = map(ps2x.Analog(PSS_LX), 0, 255, -127, 127);
  ANALOGSTATE2 = map(ps2x.Analog(PSS_LY), 0, 255, -127, 127);
  ANALOGSTATE3 = map(ps2x.Analog(PSS_RX), 0, 255, -127, 127);
  ANALOGSTATE4 = (ps2x.Analog(PSS_RY));

}```

I would move the part where you send the data with Joystick.setButton and stuff to after the part where you parse the data with all those if statements for the obvious reasons.  You shouldn't send a message before you write it.  But other than that if it's written and it works it's great.  It could be shortened with an OOP approach maybe, but that has some costs as well.  Anytime you're putting numbers on the ends of variable names what you really want is an array.  That might be something worth going and learning about.

you could use ternary statement like DIGITALSTATE1 = (ps2x.ButtonPressed(PSB_TRIANGLE))? 1 : 0;  ... or, since true and false are 1 and 0, you could use DIGITALSTATE1 = ps2x.ButtonPressed(PSB_TRIANGLE); ... or Joystick.setButton(0, ps2x.ButtonPressed(PSB_TRIANGLE));

you could also put all of the PS2 button names in an array and use a loop for the joystick.setbutton()

Thanks! i put the buttons in an array but set the joystick variables separate since i would get confused. it works great. but i guess dpad doesn't function as buttons but as Hat switch. so i got some more coding to do.


text:
Reading PROGMEM results in an incorrect hex value
I'm sure I'm doing something stupid here, but the code below is supposed to write the test hex values to a I2C EEPROM, however when I attempt to read the EEPROM it has the wrong values.  Directly calling something like Wire.write(0xab) will write the 0xab as expected, so I know the EEPROM is being written to properly, just something seems to be getting lost in translation when writing test[counter++]
.
#include <Wire.h>

const byte test[] PROGMEM = {
  0x80, 0x7f, 0x7f, 0x80, 0x7f, 0x7f, 0x80, 0x7f, 0x80, 0x7f, 0x80, 0x80,
  0x7f, 0x7f, 0x81, 0x7f, 0x7e, 0x81, 0x80, 0x7f, 0x7f, 0x7f, 0x80, 0x7e,
  0x7e, 0x81, 0x7e, 0x7c, 0x7f, 0x7f, 0x7d, 0x7c, 0x7f, 0x7f, 0x80, 0x7e
};

unsigned int test_len = 36;

#define EEPROM_ADR 0x50

void setup()
{
  Wire.begin();

  int counter = 0;

  Wire.beginTransmission(EEPROM_ADR);

  Wire.write((int)(0x0 >> 8)); //msb
  Wire.write((int)(0x0 & 0xFF)); //lsb

  while (counter < test_len)
  {
    Wire.write(test[counter++]); //using page buffering to write the entire array
  }

  Wire.endTransmission();
}

The results look something like: 0x00 0x00 0x08 0x00 0x00 0x00 0x01 etc..

remove PROGMEM to test. you don't use the pgm_read function to read PROGMEM

what is the purpose of the first two Wire.write  commands?  .... i think that they both write a zero ... is something missing from those two lines?

Juraj, you're right, but in my real code the array is quite large so it needs to be in PROGMEM, is there something I'm missing about that memory location?

That was it, it works.

you learned how to troubleshoot. next time create a minimal sketch. now please delete the question.

To obtain the size of your array you can use sizeof test / sizeof test[0]. This works with any data type of an array's elements.

I needed to either remove PROGMEM from the array or use pgm_read_byte to read the array.

source: Stack Exchange

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

sort: votes


text:
Wireless programming of Arduino
I'm trying to find a convenient way to program my Arduino remotely (by Bluetooth or Wi-Fi) because it will be packed and placed outside of my working place. Found a few ways (Arduino Cloud and Blynk) but most of them are about IoT and this is not an IoT project. Maybe you already faced such a problem. If so, then how have you dealt with this?

I use ESP32 and the built in ArduinoOTA library to update over WiFi. It's so much more convenient than the Arduino boards.

My ArduinoOTA library, which is based on Arduino's WiFi101OTA library, was created for upload from IDE. But in some scenarios as for example deployed sleeping battery powered devices it is better to have the update available for download by the device.
In advanced section of examples of the ArduinoOTA library you can find examples of sketch update over download from a http server. The OTASketchDownloadWifi shows update over the InternalStorage object of the ArduinoOTA library with download over the WiFiNINA library.

Comments are not for extended discussion; this conversation has been moved to chat.

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


text:
Arduino UNO WIFI Rev 2 - MySQL trouble
I'm using an Arduno UNO WiFi Rev 2 and trying to connect to a database, but it does not connect nor shows any errors.
The arduino connects successfully to WiFi and pinging google works fine.
But when I add the part to connect to database, on line: 65, the script just stops at "DB Connecting..." on the line above.
Inside Arduino IDE you can see a difference between the includes, the MySQL ones are not luminated:
https://i.sstatic.net/ERD0N.png
This is how the code looks like:
#include <SPI.h>
#include <WiFiNINA.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

// MySQL Information
IPAddress server_addr(111,222,333,4);
char user[] = "arduino"; // MySql username
char password[] = "qwerty"; // MySql password

WiFiClient client;
MySQL_Connection conn((Client *)&client);

// WiFi Information
char ssid[] = "Router-SSID";        // your network SSID (name)
char pass[] = "router-pw";    // your network password (use for WPA, or use as key for WEP)
int status = WL_IDLE_STATUS;     // the WiFi radio's status

// Specify IP address or hostname
String hostName = "www.google.com";
int pingResult;
int pingWorks = 0;

void setup() {
  pinMode(hallPin, INPUT);
  pinMode(LED, OUTPUT);

  Serial.begin(115200);

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < "1.0.0") {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to WiFi network:
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(ssid, pass);

    // wait 5 seconds for connection:
    delay(5000);
  }

  // you're connected now, so print out the data:
  Serial.println("You're connected to the network");

  printCurrentNet();
  printWiFiData();

  delay(2000);
  Serial.println(server_addr);
  Serial.println(user);
  Serial.println(password);
  // Connected to the WiFi lets continue..
  Serial.println("DB - Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    delay(500);
    Serial.print ( "." );
  } else {
    Serial.println("Failed to connect..");
  }
  Serial.println("Connected.");
}

void loop() {
  runWifi();
}

void runWifi() {
  if (pingWorks == 0) {
    Serial.print("Pinging ");
    Serial.print(hostName);
    Serial.print(": ");

    pingResult = WiFi.ping(hostName);

    if (pingResult >= 0) {
      Serial.print("SUCCESS! RTT = ");
      Serial.print(pingResult);
      Serial.println(" ms");
      pingWorks = 1;
    } else {
      Serial.print("FAILED! Error code: ");
      Serial.println(pingResult);
      pingWorks = 2;
    }
  } else {
    Serial.println("Ping on google works..");
  }
  delay(200);
}

void printWiFiData() {
  // print your board's IP address:
  IPAddress ip = WiFi.localIP();
  Serial.print("IP address : ");
  Serial.println(ip);

  Serial.print("Subnet mask: ");
  Serial.println((IPAddress)WiFi.subnetMask());

  Serial.print("Gateway IP : ");
  Serial.println((IPAddress)WiFi.gatewayIP());

  // print your MAC address:
  byte mac[6];
  WiFi.macAddress(mac);
  Serial.print("MAC address: ");
  printMacAddress(mac);
}

void printCurrentNet() {
  // print the SSID of the network you're attached to:
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // print the MAC address of the router you're attached to:
  byte bssid[6];
  WiFi.BSSID(bssid);
  Serial.print("BSSID: ");
  printMacAddress(bssid);
  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI): ");
  Serial.println(rssi);

  // print the encryption type:
  byte encryption = WiFi.encryptionType();
  Serial.print("Encryption Type: ");
  Serial.println(encryption, HEX);
  Serial.println();
}

void printMacAddress(byte mac[]) {
  for (int i = 5; i >= 0; i--) {
    if (mac[i] < 16) {
      Serial.print("0");
    }
    Serial.print(mac[i], HEX);
    if (i > 0) {
      Serial.print(":");
    }
  }
  Serial.println();
}

What can be the problem?
No working libs for WiFi uno rev 2?

can you connect to your mysql server from other computer?

Yes, that works.


text:
Board Updating problems
I have updated Arduino AVR Boards in IDE and before I updated, ESP8266 boards were working, now after I updated, it says "Error downloading "URL for esp"" and no matter which website I listed inside the preference:
http://arduino.esp8266.com/stable/package_esp8266com_index.json
https://github.com/esp8266/Arduino/releases/download/2.3.0/package_esp8266com_index.json

None of them are being downloaded and I cannot program ESP8266. Can I get some help? Thank you.

what? what is "updating AVR"? what is "updating esp8266"? and when do you get the "Error downloading"?

Ok, inside the Arduino IDE, when you go to tools > boards > boards manager, this is where I updated Arduino AVR boards like geniuno, nano, etc. And I have no idea when I said "update esp8266" so I wasn't sure if you were reading or not. Also the error shows up when I open boards manager. Like after the board manager loads, thats when I get an error, so it saying  ESP8266 error downloading via the website url.

ok. now I understand the question. the missing information was "in IDE" or "package". try it without the github link in Additional boards URLs

If you are using windows 10 try installing from git followimg the instruction here.
https://arduino-esp8266.readthedocs.io/en/latest/installing.html
That was how I get it to work when I found updating it through the ide didn't work


text:
What are the best GPIO pins to use for my project?
I'm working on a home automation project to control my Sommer Base+ garage door opener through Home Assistant.
The project consists of a WeMos D1 Mini with two reed switches (to detect door open/closed) and a 5V relay to control the door opener.
When the door is open the 'top / open' switch is triggered, giving a status of open. Likewise when the door is closed, the 'bottom / closed' switch is triggered, giving a status of closed. When neither switch is triggered (i.e. when the door is in motion), the status is either opening or closing, depending on the previous status.

This works fine unless the WeMos is powered up while either reed switch is closed (so if the door is open or closed).
I know this is because D3 and D8 GPIO pins for the open/close sensors and those can put the device into boot mode (I think that's what it's called).
What I want to know is which pins are the best to use for this project.
Is it possible for me to just change to pins ?? and ?? without needing to update my code?
Is it possible that the WeMos D1 Mini isn't a good fit for what I want?

GPIO 4+5 are basically the only universal inputs on the 8266; no side-effects or implementation complications.

How are you hooking it into the Sommer? I have the same opener and would love to do this.

I use a combination of the conex and output oc modules to connect to the wemos that then integrate with my Home Assistant instance.

Output oc: https://www.amazon.co.uk/dp/B07XZKDFX9/ref=cm_sw_r_cp_apa_fabt1_XAkVFb6XEGZKG?_encoding=UTF8&psc=1

Conex module: https://www.amazon.co.uk/dp/B07BQYSHDV/ref=cm_sw_r_cp_apa_fabt1_bEkVFbN1XB28M

And here is my updated project: https://github.com/jampez77/garage_door_sensor

NodeMCU and "Wemos D1 R2 and Mini" esp8266 (esp-12) pins and io overview

Serial
RX io3 RX0
TX io1 TX0

boot config pins with pullup or pulldown on board
D3 io0 PULLUP (LOW for boot to flashing mode)
D4 io2 TX1 PULLUP (Serial1 TX. no RX for Serial1)
D8 io15 PULLDOWN (SS pin if esp8266 is SPI slave); TX if Serial.swap()

untroubled GPIOs with optional function for I2C or SPI bus:
D1 io5 default pin for I2C SCL
D2 io4 default pin for I2C SCA
D5 io14 SPI CLK
D6 io12 SPI MISO
D7 io13 SPI MOSI; RX if Serial.swap()

RTC pin for timed deep sleep wake-up (if connected to reset pin)
D0 io16 - optional internal pulldown, internal pullup not available

not useable: on NodeMcu Sx pins io 6 to io 11 connect QIO SPI flash memory
(in a very special setup the SPI bus can be used with other SPI device)
(in other very special setup the QIO pins can be used as gpio)
note: most digital IO start as INPUT_PULLUP


text:
What does it take to compile Linux on Arduino, if at all possible?
Is it possible to run Linux on Arduino? If yes, what steps and limitations need to be considered? If not, what are the limitations that prevent this?

http://hackaday.com/2012/03/28/building-the-worst-linux-pc-ever/

Use a RPi instead.

Linux is a very complex operating system, but it may be able to fit on an Arduino. Things to consider:

There is no current AVR port of the source code.
You would have no graphics, instead access the terminal over UART.
The filesystem driver would have to be rewritten to access internal flash or an external SD card.
It would be extremely slow! The ATmega328 would run at 16 MHz, or about 20 MHz max (overclocked). Most Linux machines run at a minimum of 400 MHz, and more with graphics.
You would probably need some extra RAM, probably a good idea to use an ATmega2650 (the one in the Mega), which has 16 times the RAM of the Uno. You could also use a Due (6x as fast as the Uno, more RAM).
You may have to write special USB drivers for OTG (on the Due) or MAX3421EE (Mega ADK, USB host shield).

In short, it would take a lot of time and effort, and probably would be too slow for everyday use. If you really want Arduino Linux, check out the Yún.

You would not "probably" need extra ram, you do need extra ram. Linux requires 1 MB+ ram. Also, the lack of a MMU would mean you'd have to figure out how to emulate one (or run ucLinux). Realistically, at best, you'd wind up emulating a more capable processor in the atmega, which would be an order of magnitude slower then native code. Even the arduino due doesn't have anywhere near the required ram.

Also, the ATmega328P has 2 KB SRAM, and the ATmega2560P only has 8 KB. That is only 4X the ram, not 16x.

It just doesn't have enough RAM. You'd also need to teach it to boot from flash memory, which would involve rewriting the bootloader.
You can instead use an Arduino Yun or a PCDuino; while not "standard" Arduinos these support Arduino shields and run Linux.
Or there's always the Raspberry Pi.

Why do you say Yun is not "standard" Arduino? I agree it may not be the most common, but it is an Arduino indeed.

@jfpoilpret Most Arduinos are atmega boards which run compiled C++ via avr-gcc and have a USB handling chip. They come in various shapes/sizes/powers, but they're essentially the same (Mega aside). It seemed pretty obvious that the OP was talking about these and not the Yun/etc, hence the distinction.

There's also the soon-to-be-released Arduino Tre, at least I'm hoping it's soon ;-)

The short answer is no.
Basically, you would need LOTS more ram then even the biggest ATmega has natively.
It is theoretically possible to add external hardware, and program the ATmega to emulate a more powerful CPU, and run linux on that. However, on a plain arduino, it is not possible.
It would be much more realistic to run linux on a Arduino Due, which is basically a AT91SAM3X8E CPU. However, you'd still need to add some additional SRAM and storage.
There are things like the Arduino Yun, but that is really a entirely separate linux module on the same PCB as a ATmega32U4, so I don't know if you can really count it as an arduino.

Possibly relevant: What does it take to run embedded linux?

There is a board called the pcDuino that can run multiple variants of Linux such as Debian, Ubuntu, Open WRT, LEDE, Raspian PIXEL (just to mention a few). This board is not a native Arduino, rather Arduino AtHeart, and is made by LinkSprite.

Arduino have a couple of boards that support running a variant of Linux called Linino:

The Arduino Yún is a microcontroller board based on the ATmega32u4 and the Atheros AR9331. The Atheros processor supports a Linux distribution based on OpenWrt named Linino OS. The board has built-in Ethernet and WiFi support, a USB-A port, micro-SD card slot, 20 digital input/output pins (7 of them can be used as PWM outputs and 12 as analog inputs), a 16 MHz crystal oscillator, a micro USB connection, an ICSP header, and 3 reset buttons.
The new Arduino Tian board is powered by Atmel’s SAMD21 MCU, featuring a 32-bit ARM Cortex® M0+ core and a Qualcomm Atheros AR9342, which is an highly integrated MIPS processor operating at up to 533MHz and feature-rich IEEE802.11n 2x2 2.4/5 GHz dual-band WiFi module. Qualcomm Atheros MIPS supports a Linux distribution, based on OpenWRT named Linino. The Arduino Tian has also a build in 4GB eMMC memory that will can be helpful to build your projects. It is possible to Switch ON/OFF the Linux port from the MCU to reduce the power consumption.
Arduino Industrial 101 is an Evaluation board for Arduino 101 LGA module. The ATmega32u4 microcontroller is integrated in the baseboard. The module supports a Linux distribution based on OpenWRT named LininoOS. The board has built-in WiFi (IEEE 802.11b/g/n operations up to 150Mbps 1x1 2.4 GHz), 3 GPIOs (of which 2 can be used as PWM Outputs), 4 Analog Inputs, 1 USB, 1 Ethernet signal on pin headers and a built-in DC/DC converter. Check out the assembling guide and simply connect your board to a computer with a micro USB cable to get started.

This is several years old, but maybe more pertinent as Arduinos get more RAM and 32 bit ATMega AVRs, etc. There's an obvious problem notably not in the most popular answer here. The Arduino uses an AVR MICROCONTROLLER, not a MICROPROCESSOR. This is a major reason why there is no port of linux. Microcontrollers are designed to perform a specific task, applications where the relationship of input and output is well defined. Microprocessors are designed to run a variety of apps on operating systems. Remember, from the beginning, Linux needed a memory management unit and could not run on 8088 or 286 PCs. Then there was μClinux, which originally targeted the Motorola DragonBall family of embedded 68k processors, for Palm Pilots. It was never particularly successful. You might have more success porting FreeDOS or even Minix than Linux, maybe something in assembler, but compiling an OS on a microcontroller is very impractical. Perhaps it's a challenging academic problem, but specifically counter to the purpose of using a microcontroller instead of a microprocessor.

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


text:
SMS in modem's memory
I am working on SMS communication with my phone and Arduino. My intension is simple. When somebody send an SMS, the Arduino should read a text file located on my server and forward the content to the same number.
The problem here is, when I send an SMS to my Arduino, which is waiting for my message, it does not read my message. But when I separately run this example code, I see my SMS is received. It means my SMS is already present in the modem memory. But why does this happen? How to solve this? Here is my code:
// libraries
#include <GSM.h>

// PIN Number
#define PINNUMBER ""

// APN data
#define GPRS_APN       "GPRS_APN" // replace your GPRS APN
#define GPRS_LOGIN     "login"    // replace with your GPRS login
#define GPRS_PASSWORD  "password" // replace with your GPRS password

// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;
GSM_SMS sms;

// URL, path & port (for example: arduino.cc)
char server[] = "yourdomain.com";
char path[] = "/current.txt";
int port = 80; // port 80 is the default for HTTP

char k[30];
char z = '*';
int s=0;
String place;
char remoteNum[20];  // telephone number to send sms

void setup() {
    // initialize serial communications and wait for port to open:
    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
    }
    Serial.println("SMS connected");
    // connection state
    boolean notConnected = true;
    while(notConnected) {
        if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
           (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
            notConnected = false;
        else {
            Serial.println("Not connected");
            delay(1000);
        }
    }
    Serial.println("GPRS connected...");
    Serial.println("Server Connecting.");
    // if you get a connection, report back via serial:
    serverr();
}

void loop() {
    if (sms.available()) {
        Serial.println("Message received from:");
        sms.remoteNumber(remoteNum, 20);
        Serial.println(remoteNum);
        sms.flush();
        Serial.println("MESSAGE DELETED");
    }
}

void smss() {
  // I just want phone number
    if (client.available()) {
        char c = client.read();
        //***************************************************
        //       Filtering a specific message
        //**************************************************
        if (z==c) {
            s=1;
        }
        if(s == 1) {
            int i=0;
            k[i] = c;
            i=i+1;
            // Serial.print(k);
        }
        place +=k;
        //Serial.print(place);
    }
    //***************************************************

    if (!client.available() && !client.connected()) {
        sms.beginSMS(remoteNum);
        Serial.print("Place =");
        Serial.print(place);
        sms.print(place);
        sms.endSMS();
        sms.flush();
        Serial.println("MESSAGE DELETED");
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();
        // do nothing forevermore:
        for(;;)
            ;
    }
}

// if you didn't get a connection to the server:
// Serial.print(server);

void serverr() {
    if (client.connect(server, port)) {
        client.print("GET /current.txt");
        Serial.print("GET /current.txt");
        client.println(" HTTP/1.1");
        Serial.println(" HTTP/1.1");
        client.println("Host: www.yourdomain.com");
        Serial.println("Host: www.yourdomain.com");
        client.println("User-Agent: Arduino");
        Serial.println("User-Agent: Arduino");
        client.println("Accept: text/html");
        Serial.println("Accept: text/html");
        client.println("Connection: close");
        Serial.println("Connection: close");
        client.println();
        Serial.println();

        Serial.println("\nCOMPLETE!\n");
        //client.stop();
    } else {
        Serial.println("connection failed");
        Serial.println("\n FAILED!\n");
    }
}

Show the content of smss() function, so that we can see how you read the SMS and then delete it.

I have given the function definition.

It would help if you told what debug messages get displayed on your serial monitor when running this program. Also, can you confirm that remoteNumber is defined as char remoteNumber[20];? Finally, I wonder if you can flush() an SMS without reading its content first.

In the serial monitor, It just waiting for my sms and stays static.But when i run this                 code, I receive that sms.  Ya the its 'char remoteNumber[20];'.

the latest code you posted is obviously wrong: the smss() function  is never called. The global structure is just a mess as you did not break down behavior into different functions; instead some functions do a mix of unrelated actions.

I see one problem with the global structure of your program; everytime loop() is run, it:

checks if an SMS is present, and gets the originating phone number if present, otherwise it just goes on, ie smss() function returns without modifying remoteNumber
send an SMS to remoteNumber

One problem here is that your loop() will repeatedly try to send an SMS to the same remoteNumber even if no SMS was received; actually, to solve this issue, you should modify smss() to:

either wait (forever) for an SMS to be received and return only in this situation
or return a value (eg bool) that indicates whether an SMS was received or not; then an SMS should be sent if and only if an SMS was just received.

Here is an example:
void setup()
{
    GSM and GPRS initialization
    Connection to server
}

void loop()
{
    if (smss())
    {
        Reading the txt file content in server

        sms.beginSMS(remoteNum);
        sms.print(txtMsg);
        sms.endSMS();
    }
}

bool smss() // I just want phone number
{
    if (sms.available())
    {
        Serial.println("Message received from:");
        sms.remoteNumber(remoteNum, 20);
        Serial.println(remoteNum);
        sms.flush();
        Serial.println("MESSAGE DELETED");
        return true;
    }
    return false;
}

Note that this code does not integrate error support as it should; indeed sms.remoteNumber() may return error codes (any value >1), in which case you should consider no SMS was received at all.

Will the sms.flush() will delete the content in remoteNum ? Because its in smss().

I have updated and added my void loop() in the question. But still,giving same problem

You've added much more to your code than just my suggestion; now we see how you get the text content from your server. And once again the whole logic of your program does not seem correct: write a function to fully read the complete content from your server (there must be a while inside it) instead of reading byte per byte at every call of loop(). And this problem is not linked to this specific question anymore.

I think, It would be better, If I give the complete code. I have updated the complete code. I have found a problem, If I don't run the serverr() function, I am able to receive sms, It means the server() conflicts the sms. Is my serverr() function correct ?

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


text:
Receiving two-byte int values over serial
I am using Python smbus write_word_data method to send int values from a Raspberry Pi to an Arduino using I²C.
This seems to be the correct method.
When I send values from 0-255, I see the following in my Arduino serial monitor

0,0,0
  0,1,0
  0,2,0
  …
  0,255,0

Sending 256 I see:

0,0,1

For 257 I see:

0,1,1

Etc, etc...
My question is, how would I modify the following Arduino code to properly 'reconstitute' the int values, and then send them back to the RPi?
#include <Wire.h>

#define SLAVE_ADDRESS 0x04
int number = 0;
int state = 0;
bool newData = false;

void setup() {
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  // initialize i2c as slave
  Wire.begin(SLAVE_ADDRESS);
  // define callbacks for i2c communication
  Wire.onReceive(receiveData);
  Wire.onRequest(sendData);
  Serial.println("Ready!");
}

void loop() {
  Serial.println(receivedValue);
  newData=false;
}

// callback for received data
void receiveData(int byteCount) {
  while(Wire.available()) {
    newData = true;
    Wire.read();
    if(Wire.available() == 2) {
      receivedValue = Wire.read() | Wire.read() << 8;
    }
  }
}

// callback for sending data
void sendData() {
  Wire.write(number);
}

Aren't you really transferring these over i2c, not (asynchronous) serial as implied in the title, and using the serial more as a debug monitor to tell what is going on?

void receiveData(int byteCount){

  // Looks like your number is sent in a 3 byte packet
  if (bytecount == 3)
  {

    // Discard first number as it is seemingly alway zero
    Wire.read();

    // Read low byte into rxnum
    int rxnum = Wire.read();

    // Read high byte into rxnum
    rxnum += Wire.read() << 8;

    // Send back
    sendInt(rxnum);

  }

}

void sendInt(int num){

  // Uncomment below if you want so send back in same format
  // Wire.write(0);

  // Send low byte
  Wire.write((uint8_t)num);

  // Send high byte
  num >>= 8;
  Wire.write((uint8_t)num);
}

Just to clarify. Wire.read() and Wire.write only work of single bytes. To send a 2 byte int, you need to split the int into 2 bytes, send them individually, and then join them again at the receiving end.

thanks!. I've edited my original code and it works, but how do I separate out my x,y coordinates in my main loop?   Serial.println(receivedValue);

This likely won't work as op expects. Each write(byte) transmits in separate transactions. If the master calls this with requestFrom(), it'll only receive the first byte, and never receive the second. To send both bytes, you need to pass a byte array to write().

Unless (and until) your application needs high enough data rates that you need to make the most efficient use possible of your data channel (or you're talking to an inflexible hardware device that dictates the data protocol), you'll save yourself a lot of headaches by sending human-readable strings, something like:
x= 12345, y=   -32
x=   432, y=-33221

You can reconstitute them at the other end with with atol(), log them  to a file, be able to understand them later, and see instantly whether the sender sent what you expected it to. Don't optimize until you have to; you may not have to.

Ir seems to me that there is something wrong with the Python Raspberry Pi code. What you show is 3 bytes of data, not 2. That's wrong.
If you're writing a 2 byte word, I would expect to see 2 bytes, not 3. You might want to post a question on the Raspberry Pi forum to get help resolving THAT problem first.
If you're stuck with the sending code you have, then here's what you would do.
Looking at your data, the first byte is always zero. You want to discard it.
The second byte is your low order byte, and your third byte of data is the high order byte. You need to do some juggling to get the data into the correct byte order, like this:
void readWordWithPadding()
{
  if (Wire.available()<3)
  {
    newData = false;
    return;
  }
    newData = true;

  Wire.read(); //Throw away the filler byte
  int lowByte = Wire.read();
  int hiByte = Wire.read();

  //Shift the high byte by 8 bits and add in the low byte
  receivedValue = (hiByte << 8) + lowByte ;
  return;
}

Thanks. The remaining problem is separating out my x,y values. On the sending side I call writeNumber(x) then writeNumber(y). So In my arduino code receivedValue alternates between x&y. But having a problem separating the 2.

That is a design problem. You need to coordinate what is sent from the Pi with what you look for on the Arduino side. If you're always sending an X/Y pair, then you should write your Arduino code to look for an X/Y pair. Always read both numbers. You might need to adjust your code logic to make sure 4 bytes (or 6 bytes if you haven't been able to get rid of those spurious zero bytes) are available before starting to read.


text:
How do functions outside of void loop work?
I am used to Arduino sketches with a void setup() part that runs once, and a void loop() part that keeps looping. What happens when you have void functions outside of the main void loop()? Will these all keep looping in parallel or do they run one after the other? Or do certain void functions only run once certain criteria has been met (like a while loop)?
For example in the code below, when will the void receiveData(int byteCount) and the void sendData() functions run?
//I2C_test

//This code demonstrates communication via an I2C bus between a raspberry pi and an arduino.
//When the Raspberry pi (master) sends data to the Arduino (slave), the Arduino uses this
//data to control a motor. After the Arduino has recieved data from the master, it then collects
//data from the external environment via a sensor and sends this data back to the Raspberry pi.

#include <Wire.h>
int number = 0; //Declare variables
int val = 0;

void setup() {
  //Anything between the curly brackets runs once when the arduino is turned on or reset
  pinMode(0, INPUT);
  //Set pin 0 as input and 3 as output
  pinMode(3, OUTPUT);
  Serial.begin(9600);
  //Set the data rate for serial transmission at 9600bps
  Wire.begin(0x04);
  //Initiate the Wire library, join the Arduino as a slave, and specify its 7 bit slave address
  Wire.onReceive(receiveData);
  //Define callbacks for i2c communication
  Wire.onRequest(sendData);
}

void loop() {
  //The code between the curly brackets keeps repeating
  delay(100);
}

void receiveData(int byteCount) {
  while(Wire.available()) {
    number = Wire.read();
    //Set the variable "number" to the data sent by the master
    analogWrite(3, number);
    //Write this number to pin 3 (PWM). This controls the motor speed
  }
  val = analogRead(0);
  //Read the voltage on pin 0 (connected to the sensor). Map input voltages between 0 and 5 volts into integer values between 0 and 1023
}

void sendData() {
  Wire.write(val);
  //Send the data read from the sensor to the master.
}

This looks interesting. I wonder if you could post links to the source of the code (and details of connections between Arduino and Pi).

@Milliways I used this* tutorial to write the code on the arduino uno and Raspberry pi (B+ model), however I made a few small changes.Connect the SDA and SCL pins of the two boards, as well as the ground pins if they are connected to different power supplies. I then had pin 3 connected to a sensor configured in a potential divider configuration, connected between the +5V and Gnd pins. Pin 0 and Gnd is connected to a motor drive board.

The setup() and loop() functions are unusual because they are called automatically for you by the Arduino code. No other functions behave this way.
Generally speaking, a function will never run unless you explicitly call it yourself (e.g. from within setup() or loop()), or instruct another part of the program to call it. (There are other ways to execute functions, but that usually involves some very advanced tinkering which is best avoided.)
For example, pinMode() is a function just like any other. It only runs when you actually put something like pinMode(3, INPUT) in your code. At that point, it runs once, finishes, and then the calling function carries on from where it left off (they never run in parallel).
The example code you've posted is quite interesting. Look at these lines in setup():
Wire.onReceive(receiveData);
Wire.onRequest(sendData);

These lines are telling the Wire object to call receiveData() and sendData() in response to I2C events. It does this by passing function pointers which are stored and used by Wire.
I'd recommend searching for information about C/C++ function pointers online if you want to learn more about this. You may also be interested to explore Arduino's attachInterrupt() function.

Thanks for your answer. This is starting to make more sense now. However, if the receiveData() and sendData() functions are not run unless they are called, then why are they called within the void setup() function and not the main void loop() function? Surely these functions will never be called unless the rare chance that there is an i2c event while the instruction pointer is still within the void setup function? Would it not be better to call these functions from within the void loop function so whenever there is an i2c event, the function is called?

@Blue7 These functions are not called in void setup(), they are passed as the parameter of onReceive and onRequest, they're callbacks as the comment states. In very short summary : this tells the (code from the) Wire library to call these functions when specific things happen (http://arduino.cc/en/Reference/WireOnReceive, http://arduino.cc/en/Reference/WireOnRequest ...)

@FredP Ah okay. Thanks for the links, I'll check them out when I'm not on my phone. I have a quick question in the meantime though, if you don't mind. Are these callbacks always ready and waiting for an i2c event? i.e, no matter where the instruction pointer is, these callbacks will instantly call the function as soon as an i2c event happens?

@Blue7 It will presumably be using interrupts to monitor I2C activity. When an interrupt executes, it takes control away from the main program temporarily.

@Blue7 The callbacks are not waiting (Arduino is not multithreaded), as @PeterRBloomfield says, the Wire library enables I2C interrupt through twi_init() when you call Wire.begin. When there is I2C activity the µC stops doing its current task (unless ... nevermind for the moment :-) and goes in the code of Wire library, that then calls the (appropriate, depending on what is happening) function you registered as callback (receiveData for example). A callback is the generic name for functions like receiveData or sendData, they're called by an interrupt handler inside Wire.

Is it not that case that setup() is called once and loop() is called repeatedly?
i.e. that there is an unseen main() which might look like this:
void main(){
  setup();
  while(True){
    loop();
  }
}

Apologies as I'm just looking into the Arduino and have almost no C/C++ experience; I'm trying to get a handle on this loop() situation myself.

Basically, yes. There is also a call to init() which gets the timers going for millis, delay etc. So init() is for general initialization, setup() is for your initialization, and loop is for, well, looping. You can write your own main if you want to take full control.

Nice post. BTW ; is not required after the penultimate } :-)

There is also call of serial_event() is it not?

I can't comment on Dee's response. The actual code that is executed in the main loop is here:
    int main(void) {
    init();
    initVariant();

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }
    return 0;
}

And yes, setup() gets called once and loop() is being called repeatedly (together with some serial stuff).

It works as normal function, it must be called to make sense. loop()/setup() are called from a main() function which is compiled from Arduino directory and linked in. receiveData/sendData are to called from your program which root is in loop/setup functions.


text:
How to burn arduino bootloader on SAMD21 chips using J-Link mini
I am planning on making my own custom PCB of a SAMD21 board. I would like to ask if anyone has experience uploading arduino bootloader on a J-link Mini although adafruit has a guide on this device, its not uploading a arduino bootloader.
On a related note which pins should I connect it to my SAMD21 chip ?

SWD pins. see the schematic of some SAMD21 Arduino. the connection is same for any bootloader or application upload. it is used for debugging too.

https://forum.arduino.cc/index.php?topic=636902.0

on the github guide he posted, it does not mention on how to upload the arduino bootloader sadly. But thank you for telling me  SWD pins are standard on most applications

I did it in Arduino IDE. I selected the Atmel EDBG programmer and then Burn Bootloader. all SAMD programmers use the same protocol

@Juraj the Atmel EDBG would work for Arduino Zero since that has the EDBG chip.     With Jlink, I usually use Atmel Studio. Once the Jlink is connected to the chip via SWD, just goto the programmer option in Atmel Studio, select the chip and programmer and burn the programmer. It is pretty straightforward. There is a nice tutorial here which walks through it.

@karan, it worked with NXP LPC-Link2. IDE calls openocd and the programmer is configured in openocd

Hey guys post your comment as answers, so i can mark them as correct when my jlink arrives. Thanks for the replies

The Atmel EDBG would work for Arduino Zero since that has the EDBG chip. With Jlink, you can use Atmel Studio. Once the Jlink is connected to the chip via the 10 pin SWD header, goto the programmer option in Atmel Studio, select the chip and programmer and burn your firmware with the selected programmer. You can follow a tutorial here which walks through it.


text:
How to read shiftOut function using arduino
(I'm sorry for my bad English, but I will do my best)
I have a Chinese MUC which already programmed. It communicates with a LED driver chip using three wires (STB,CLK,DIN).
(LED driver controls 16 digit 7 Segment display)
After some research, I found that it can be talk to LED driver using shiftout function.
Now the main coal is to connect these
 3 pins(STB,clk,din) to Arduino and read the incoming data and convert the data to numbers.
To test if this idea is working or not,
I came with two arduino (uno to send shiftout function  and mega to read it) after connect pin 2 of uno to pin 2 of mega and same 3 to 3, 4 to 4 and also Gnd of uno to Gnd of mega.
I wrote these codes:
arduino UNO side (to send shiftOut function)

    #define STB  4
#define clockPin  5
#define dataPin  6

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

  pinMode(STB, OUTPUT);
  pinMode(clockPin,  OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
 digitalWrite(STB, LOW);
    shiftOut(dataPin, clockPin, LSBFIRST, 0b10101010 ); // 1st digit
   digitalWrite(STB, HIGH);
}

arduino mega side (to read shiftOut function)

    #define STB 4
#define clockPin  5
#define dataPin  6

 int R_STB[8];
 int R_clockPin ;
 int R_dataPin ;
void setup() {
   Serial.begin(115200);

  pinMode(STB, INPUT);
  pinMode(clockPin,  INPUT);
  pinMode(dataPin, INPUT);
}

void loop() {

 R_STB = digitalRead(STB);
 R_clockPin = digitalRead(clockPin);
 R_dataPin = digitalRead(dataPin);

   for(int i=0 ; i<8;i++){
  Serial.print(R_STB[i]-2);

  Serial.print(" ");
  Serial.print (R_clockPin[i]);

 Serial.print(" ");
  Serial.print(R_dataPin[i]+2);
Serial.println(" ");
   }
 }

But the digital read at arduino mega side can't read all data due to it fast switching between High LOW statement maybe? and I am stuck here.
Please any one has any ideas?

Welcome to Arduino StackExchange. What the Chinenese MUC you have, provide us some the datasheets

You are right that you can't read the data fast enough with your method there. What you really need is the opposite of "shiftOut" - which happens to be called "shiftIn".  You use it just like shiftOut, but instead of you sending it a value to send it instead returns a value that it reads.
You trigger it using the "STB" pin:
if (digitalRead(STB) == LOW) {
    uint8_t val = shiftIn(dataPin, clockPin, LSBFIRST);
    Serial.println(val, HEX);
}

But the protocol you describe is simply SPI.  There is hardware within the Arduino to handle it for you.  A little harder to work with, but it's capable of working at much higher speeds and is more likely to be able to read your incoming data fast enough.
Resources:

https://www.arduino.cc/en/reference/SPI
http://www.gammon.com.au/spi

The latter includes how to configure an SPI "Slave" which is used for receiving data that is sent out from elsewhere.

Majenko thank you vary much . I read about the SPI and i reach to the solution, one question please what if i got just two pin (DIN,CLK) instead of three(STB,CLK,DIN) how or what should i use? thank you in advance.

For SPI there must be a third pin. It may be labelled CS or SS instead of STB. Or it may not be SPI and have a "Latch" pin (it's a shift register in that case).  If there's nothing but CLK and DIN then there must be some other non-standard method for indicating the start of a communication block.

Thank you for your fast reply, The new LED driver (TM1640), it says in it datasheet "Dual-line serial interface (CLK, DIN) " .   datasheet==>> https://datasheetspdf.com/pdf-file/838954/TitanMicro/TM1640/1

It uses a non-standard system: The starting condition of data input is: when CLK is high, the DIN becomes low from high; the ending condition is: when CLK is high, the DIN becomes high from low.

could you suggest any think which by reading it I can handle the data which comes from (MUC) through(CLK, DIN) pins using arduino?please

You already know how to receive the data, and I have highlighted the part of the datasheet that describes the start condition. There's even a picture in there to make it even more obvious.


text:
Can't Compile .ino using ArduinoJson Library
I am using an ESP32 NodeMCU for which I wrote working software before. This also occurs when I just try to compile without uploading, so no hardware problem.
I am using the newest version of ArduinoJson(6.12.0) and it is included:
#include <ArduinoJson.h>
The only Function where I use the Library (I'm not good at C/C++, so maybe there is an error):
int DeserializeJson(char *json, int *pin, int *pinmode, int *timeInMilliseconds){

  StaticJsonDocument<1024> doc;
  DeserializationError error = deserializeJson(doc,json);

  if (error) {

    Serial.println("Parsing failed");
    return -1;
  }

  memcpy(&pin, doc["Pin"], sizeof( doc["Pin"]));
  memcpy(&pinmode, doc["Mode"], sizeof( doc["Mode"]));
  memcpy(&timeInMilliseconds, doc["TimeInMilliseconds"], sizeof( doc["TimeInMilliseconds"]));

  return 0;
}

This is the error I'm getting (at least a part of it):
In file included from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Array/ArrayIterator.hpp:8:0,

                 from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Array/ArrayRef.hpp:8,

                 from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.hpp:17,

                 from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.h:9,

                 from C:\Users\error404\source\repos\IOT\esp32\esp32.ino:1:

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp: In instantiation of 'typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type ArduinoJson6120_000001::VariantRef::as() const [with T = const void*; typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type = const void*]':

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Object/MemberProxy.hpp:70:52:   required from 'typename ArduinoJson6120_000001::VariantAs<T>::type ArduinoJson6120_000001::MemberProxy<TParent, TStringRef>::as() const [with TValue = const void*; TObject = ArduinoJson6120_000001::JsonDocument&; TStringRef = const char*; typename ArduinoJson6120_000001::VariantAs<T>::type = const void*]'

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantCasts.hpp:16:35:   required from 'ArduinoJson6120_000001::VariantCasts<TImpl>::operator T() const [with T = const void*; TImpl = ArduinoJson6120_000001::MemberProxy<ArduinoJson6120_000001::JsonDocument&, const char*>]'

C:\Users\error404\source\repos\IOT\esp32\esp32.ino:70:47:   required from here

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp:240:24: error: no matching function for call to 'variantAs(ArduinoJson6120_000001::VariantData* const&)'

     return variantAs<T>(_data);

                        ^

In file included from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantOr.hpp:9:0,

                 from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantOperators.hpp:9,

                 from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp:12,

                 from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Array/ArrayIterator.hpp:8,

                 from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Array/ArrayRef.hpp:8,

                 from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.hpp:17,

                 from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.h:9,

                 from C:\Users\error404\source\repos\IOT\esp32\esp32.ino:1:

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:55:59: note: candidate: template<class T> typename ArduinoJson6120_000001::enable_if<ArduinoJson6120_000001::is_integral<T>::value, T>::type ArduinoJson6120_000001::variantAs(const ArduinoJson6120_000001::VariantData*)

 inline typename enable_if<is_integral<T>::value, T>::type variantAs(

                                                           ^

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:55:59: note:   template argument deduction/substitution failed:

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp: In substitution of 'template<class T> typename ArduinoJson6120_000001::enable_if<ArduinoJson6120_000001::is_integral<T>::value, T>::type ArduinoJson6120_000001::variantAs(const ArduinoJson6120_000001::VariantData*) [with T = const void*]':

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp:240:24:   required from 'typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type ArduinoJson6120_000001::VariantRef::as() const [with T = const void*; typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type = const void*]'

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Object/MemberProxy.hpp:70:52:   required from 'typename ArduinoJson6120_000001::VariantAs<T>::type ArduinoJson6120_000001::MemberProxy<TParent, TStringRef>::as() const [with TValue = const void*; TObject = ArduinoJson6120_000001::JsonDocument&; TStringRef = const char*; typename ArduinoJson6120_000001::VariantAs<T>::type = const void*]'

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantCasts.hpp:16:35:   required from 'ArduinoJson6120_000001::VariantCasts<TImpl>::operator T() const [with T = const void*; TImpl = ArduinoJson6120_000001::MemberProxy<ArduinoJson6120_000001::JsonDocument&, const char*>]'

C:\Users\error404\source\repos\IOT\esp32\esp32.ino:70:47:   required from here

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:55:59: error: no type named 'type' in 'struct ArduinoJson6120_000001::enable_if<false, const void*>'

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp: In instantiation of 'typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type ArduinoJson6120_000001::VariantRef::as() const [with T = const void*; typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type = const void*]':

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Object/MemberProxy.hpp:70:52:   required from 'typename ArduinoJson6120_000001::VariantAs<T>::type ArduinoJson6120_000001::MemberProxy<TParent, TStringRef>::as() const [with TValue = const void*; TObject = ArduinoJson6120_000001::JsonDocument&; TStringRef = const char*; typename ArduinoJson6120_000001::VariantAs<T>::type = const void*]'

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantCasts.hpp:16:35:   required from 'ArduinoJson6120_000001::VariantCasts<TImpl>::operator T() const [with T = const void*; TImpl = ArduinoJson6120_000001::MemberProxy<ArduinoJson6120_000001::JsonDocument&, const char*>]'

C:\Users\error404\source\repos\IOT\esp32\esp32.ino:70:47:   required from here

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:61:61: note: candidate: template<class T> typename ArduinoJson6120_000001::enable_if<ArduinoJson6120_000001::is_same<T, bool>::value, T>::type ArduinoJson6120_000001::variantAs(const ArduinoJson6120_000001::VariantData*)

 inline typename enable_if<is_same<T, bool>::value, T>::type variantAs(

                                                             ^

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:61:61: note:   template argument deduction/substitution failed:

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp: In substitution of 'template<class T> typename ArduinoJson6120_000001::enable_if<ArduinoJson6120_000001::is_same<T, bool>::value, T>::type ArduinoJson6120_000001::variantAs(const ArduinoJson6120_000001::VariantData*) [with T = const void*]':

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp:240:24:   required from 'typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type ArduinoJson6120_000001::VariantRef::as() const [with T = const void*; typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type = const void*]'

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Object/MemberProxy.hpp:70:52:   required from 'typename ArduinoJson6120_000001::VariantAs<T>::type ArduinoJson6120_000001::MemberProxy<TParent, TStringRef>::as() const [with TValue = const void*; TObject = ArduinoJson6120_000001::JsonDocument&; TStringRef = const char*; typename ArduinoJson6120_000001::VariantAs<T>::type = const void*]'

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantCasts.hpp:16:35:   required from 'ArduinoJson6120_000001::VariantCasts<TImpl>::operator T() const [with T = const void*; TImpl = ArduinoJson6120_000001::MemberProxy<ArduinoJson6120_000001::JsonDocument&, const char*>]'

C:\Users\error404\source\repos\IOT\esp32\esp32.ino:70:47:   required from here

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:61:61: error: no type named 'type' in 'struct ArduinoJson6120_000001::enable_if<false, const void*>'

C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp: In instantiation of 'typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T,

exit status 1
Fehler beim Kompilieren für das Board ESP32 Dev Module.

In its own way, the compiler tries to say "I don't know how to convert doc["Pin"] to a const void*".
Indeed, ArduinoJson doesn't support conversion to const void*; it supports conversion to const char*, but that doesn't make sense here. Instead, you want to convert doc["Pin"] to an integer and assign it to the variable passed by the caller of DeserializeJson().
The solution is to use the assignment operator instead of memcpy():
*pin = doc["Pin"];
*pinmode = doc['Mode"];
*timeInMilliseconds = doc["TimeInMilliseconds"];

It works. Thank you for the explanation!!! You really saved my day! :)


text:
Why can't I control speed of the motor? (M1 and E1)
When myservo_1,myservo_2,myservo_3,myservo_4 is commented, I can't control the speed of my M1 motor. But only when I uncomment myservo_1 and so on, I can control the motor speed again.
Can someone help me? My codes are listed down below:
#include <Servo.h>
Servo myservo_1;
Servo myservo_2;
Servo myservo_3;
Servo myservo_4;

int SensorL = 0;
int SensorR = 0;
int SensorM = 0;

#define E1 10
#define M1 12
#define E2 11
#define M2 13
int pos = 0;
int incomingByte = 0;

void setup()
{
  Serial.begin(9600);
  myservo_1.attach(9);
  myservo_2.attach(8);
  myservo_3.attach(7);
  myservo_4.attach(6);
  pinMode(SensorL, INPUT);
  pinMode(SensorR, INPUT);
  pinMode(SensorM, INPUT);
  pinMode(M1, OUTPUT);
  pinMode(M2, OUTPUT);
//  pinMode(E1, OUTPUT);
//  pinMode(E2, OUTPUT);
}

void loop()
{
  SensorR = digitalRead(2);
  SensorL = digitalRead(3);
  SensorM = digitalRead(5);

  if (SensorL == LOW && SensorR == LOW && SensorM == HIGH)
  {
    digitalWrite(M1, HIGH);
    digitalWrite(M2, HIGH);
    analogWrite(E1, 255);
    analogWrite(E2, 255);
    Serial.println(" FORWARD ");
    //delay(1);
  }
  if (SensorL == HIGH && SensorR == LOW && SensorM == HIGH)
  {
    digitalWrite(M1, HIGH);
    digitalWrite(M2, LOW);
    analogWrite(E1, 255);
    analogWrite(E2, 255);
    Serial.println(" LEFT ");
    //delay(1);
  }
  if (SensorL == LOW && SensorR == HIGH && SensorM == HIGH) //move right
  {
    digitalWrite(M1, LOW);
    digitalWrite(M2, HIGH);
    analogWrite(E1, 255);
    analogWrite(E2, 255);
    Serial.println(" RIGHT ");
    //delay(1);
  }

  if (SensorL == HIGH && SensorR == HIGH && SensorM == HIGH) //stop
  {
    digitalWrite(M1, HIGH);
    digitalWrite(M2, HIGH);
    analogWrite(E1, 0);
    analogWrite(E2, 0);
    Serial.println(" STOP ");
    //delay(1);
  }

  if (SensorL == HIGH && SensorR == LOW && SensorM == LOW) //move left
  {
    digitalWrite(M1, HIGH);
    digitalWrite(M2, LOW);
    analogWrite(E1, 125);
    analogWrite(E2, 125);
    Serial.println(" LEFT ");
    //delay(1);
  }

  if (SensorL == LOW && SensorR == HIGH && SensorM == LOW) //move right
  {
    digitalWrite(M1, LOW);
    digitalWrite(M2, HIGH);
    analogWrite(E1, 125);
    analogWrite(E2, 125);
    Serial.println(" MoVE Right ");
    //delay(1);
  }

  if (Serial.available() > 0)
  {
    incomingByte = Serial.read();
    {
      {
        if (incomingByte == 'J')//ARM OPEN
        {
          myservo_1.write(0);
          Serial.println(" ARM OPEN ");
        }
        if (incomingByte == 'L')//ARM CLOSE
        {
          myservo_1.write(180);
          Serial.println(" ARM CLOSE ");
        }
        if (incomingByte == 'I')//ARM UP
        {
          myservo_2.write(0);
          myservo_3.write(180);
          Serial.println(" ARM UP ");
        }
        if (incomingByte == 'K')//ARM DOWN
        {
          myservo_2.write(180);
          myservo_3.write(0);
          Serial.println(" ARM DOWN ");
        }
        if (incomingByte == 'U')//ROTATE LEFT
        {
          myservo_4.write(0);
          Serial.println(" ROTATE LEFT ");
        }
        if (incomingByte == 'O')//ROTATE RIGHT
        {
          myservo_4.write(180);
          Serial.println(" ROATE RIGHT ");
        }
        if (incomingByte == 'M')
        {
          myservo_1.write(90);
          myservo_2.write(90);
          myservo_3.write(90);
          myservo_4.write(90);
          Serial.println(" ALL STOP ");
        }
        if (incomingByte == 'N')//ARM STOP
        {
          myservo_1.write(90);
          Serial.println(" ARM STOP ");
        }
        if (incomingByte == 'B')//UP DOWN STOP
        {
          myservo_2.write(90);
          myservo_3.write(90);
          Serial.println(" UP DOWN STOP ");
        }
        if (incomingByte == 'V')//ROTATION STOP
        {
          myservo_4.write(90);
          Serial.println(" ROTATION STOP ");
        }
        if (incomingByte == 'W')
        {
          digitalWrite(M1, HIGH);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 200);
          analogWrite(E2, 0);
          Serial.println(" FORWARD ");
        }
        if (incomingByte == 'Z')
        {
          digitalWrite(M1, HIGH);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 255);
          analogWrite(E2, 255);
          Serial.println(" FORWARD ");
          delay(100);
        }
        if (incomingByte == 'S')
        {
          digitalWrite(M1, LOW);
          digitalWrite(M2, LOW);
          analogWrite(E1, 255);
          analogWrite(E2, 255);
          Serial.println(" REVERSE ");
        }
        if (incomingByte == 'A')
        {
          digitalWrite(M1, HIGH);
          digitalWrite(M2, LOW);
          analogWrite(E1, 255);
          analogWrite(E2, 255);
          Serial.println(" LEFT ");
        }
        if (incomingByte == 'D')
        {
          digitalWrite(M1, LOW);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 255);
          analogWrite(E2, 255);
          Serial.println(" TURNING RIGHT ");
        }
        if (incomingByte == 'X')
        {
          digitalWrite(M1, LOW);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 0);
          analogWrite(E2, 0);
          Serial.println(" STOP MANAUAL ");
        }
        if (incomingByte == 'w')
        {
          digitalWrite(M1, HIGH);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 125);
          analogWrite(E2, 125);
          Serial.println(" SLOW FORWARD ");
        }
        if (incomingByte == 's')
        {
          digitalWrite(M1, LOW);
          digitalWrite(M2, LOW);
          analogWrite(E1, 125);
          analogWrite(E2, 125);
          Serial.println(" SLOW REVERSE ");
        }
        if (incomingByte == 'a')
        {
          digitalWrite(M1, HIGH);
          digitalWrite(M2, LOW);
          analogWrite(E1, 125);
          analogWrite(E2, 125);
          Serial.println(" SLOW LEFT ");
        }
        if (incomingByte == 'd')
        {
          digitalWrite(M1, LOW);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 125);
          analogWrite(E2, 125);
          Serial.println(" SLOW RIGHT ");
        }
      }
    }
  }
}

The Servo library uses timer 1 to send the signals to the servos. But timer 1 is also used to run PWM on pins 9 and 10. It can't however do both.
So since Motor E1 uses pin 10, and timer 1 is already used by the Servo library, PWM, and by extension, analogWrite doesn't work.
E2 uses pin 11, which uses timer 2 for it's PWM, so is therefor no affected.
So move E1 to one of the PWM pins, other than 9 and 10, and thing should start working again.
I however don't know why M1 doesn't work.

I had change the pin for my servo 2 3 5 6 so it will not affect pin 9 and 10 but whoever it still doesnt work properly but my E2 M2 still works fine. Is there any other method to troubleshot it? By the way Thx alot!

That's not what I said. You can use both the servo library (it doesn't matter which pins you use for servos), and PWM on pins 9 and 10. Since you need the servo library, you can't use pins 9 and 10 for PWM. So you need to change the pin for that motor that's currently connected to pin 10. Changing servo pins does not help here.

Please correct your code there are several mistakes, such as

the lines at beginning of loop SensorR = digitalRead(2); SensorL = digitalRead(3); SensorM = digitalRead(5); doesn't make any sense.. as
you not defined 2,3,5 pin as input. And for taking analog input
please change pins 2,3,5 and analog pins..
Motor Pin M1 and M2 are connected 12,13 which are not pwm pins so you can't use to change the speed of your Motor.. Please make this
code sensible....

E1 E2 are used by pwm pins to control the speed and the ir sensor is define as input above


text:
Sim808 module HTTP Bad request
I have an Arduino UNO and sim808 EVB-V3.02.4.
I want to send a GET request to my url but I always receive 400 Http bad request error.
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

#define PIN_TX    7
#define PIN_RX    8
SoftwareSerial mySerial(PIN_TX,PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

char http_cmd[] = "GET /index.php?lat=10&long=100 HTTP/1.0\r\n\r\n";
char buffer[512];

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

void loop() {
  //*********** Attempt DHCP *******************
  while(!sim808.join(F("cmnet"))) {
      Serial.println("Sim808 join network error");
      delay(2000);
  }

  //************ Successful DHCP ****************
  Serial.print("IP Address is ");
  Serial.println(sim808.getIPAddress());

  //*********** Establish a TCP connection ************
  while(!sim808.connect(TCP,"39c309ae.ngrok.io", 80)) {
      Serial.println("Connect error");
  }
  Serial.println("Connection success");

  //*********** Send a GET request *****************
  Serial.println("waiting to fetch...");
  sim808.send(http_cmd, sizeof(http_cmd)-1);
  while (true) {
      int ret = sim808.recv(buffer, sizeof(buffer)-1);
      if (ret <= 0){
          Serial.println("fetch over...");
          break;
      }
      buffer[ret] = '\0';
      Serial.print("Recv: ");
      Serial.print(ret);
      Serial.print(" bytes: ");
      Serial.println(buffer);
      break;
  }

  //************* Close TCP or UDP connections **********
  sim808.close();

  //*** Disconnect wireless connection, Close Moving Scene *******
  sim808.disconnect();
  delay(5000);
  }

My php code:
<?php
file_put_contents('test.txt', $_GET['lat'] . '---' . $_GET['lon']);
print '
<html>
<head>
<title>Good</title>
</head>
<body>
Was Good
</body>
</html>
';
?>

I want just open http://39c309ae.ngrok.io/index.php?lat=10&long=100 with arduino and sim808.
What is wrong in my codes?

You aren't sending the Host: header with your request.  Without that the web server has no idea which website you want to get the /index.php page from.
char http_cmd[] = "GET /index.php?lat=10&long=100 HTTP/1.0\r\n"
                  "Host: 39c309ae.ngrok.io\r\n"
                  "\r\n";

nice worked! thanks a lot! becuse of low mine low reputation i can not flag your question for best answer! anyway , thanks


text:
Number of digits setting for serial printing the sensor output value
I am getting fan motor rpm as 3200. But if I get the data as 50, I should get the value like 0050. How can I do this?
I can do it like checking the value for single digit(0-9), double digit (10-99), and triple digit (100-999) and four digit(1000-9999). I need to fix digit size and send it through serial. Is there any other way for this?

Three if statements look a bit simplistic, but are much better in code size than sprintf, if that's the only usage for sprintf.
 if (number < 1000) Serial.write('0');
 if (number < 100) Serial.write('0');
 if (number < 10) Serial.write('0');
 Serial.println(number);

Saves about 1.5kB Flash, compiled with Arduino 1.8.9 for an Uno

if      (number <   10) { Serial.print("000"); }
else if (number <  100) { Serial.print("00"); }
else if (number < 1000) { Serial.print('0'); }
This saves another 200 bytes.

You can use the C function sprintf:
char text[5];
sprintf(text, "%04d", number);
Serial.println(text);

The leading 0 in 04d will add zero's for the length (4) is met, so 1 will become 0001, 10 will become 0010, 100 will become 0100 and 1000 will stay 1000.

this is what i expected... thank you very much for your comment..

Why char text[5]; ? Why 5 is entered?? Why not 4 or 3?


text:
Have I fried my arduino uno?
I made a smart dustbin using arduino, servo motor, & ultrasonic sensor. It worked pretty well for a few number of days. But once I don't know how but the Arduino 'ON' light started to become dim and switched off. I used a 9V HW battery. So I decided to plug in my arduino with a 7V AC charger, still no luck, the arduino did not turn on nor the ON light. Then I plugged the arduino to my PC, the ON light turned on for 2 to 4 seconds and switched off. I realized it became too when I touched the usb port. The ATMEGA chip did not become hot. Please help?

why do you expect the chip to become hot?

Unplug everything (servos and sensors) and try again.

If the USB chip is hot, you are out of luck.


text:
arduino mega multi integer values reading on other arduino mega
I need two Arduino communications.
The master arduino from the slave arduino needs to read 16 signals.
The sample serial port output from the slave is as follows.
@ 125 @ 13 @ 874 @ 1023 & 950 @ 547 @ 965 @ 852 @ 654 @ 478 @ 0 @ 456 @ 996 @ 789 @ 556 @ 847 @

I need to throw this output into an integer array.

So the problem is only to split up the received string? Then maybe this article from Majenkos Blog can help you

Is the & a typo? Should that have been @? Also, are there line endings added after each block of 16 values?

You can use the following C functions:

strtok: to split a string (see strtok).
atoi: to convert a string to an integer (see atoi).


text:
LCD displays bad character while counting rotation
I have been practicing RPM and rotation counter in arduino using infrared optocoupler. I try to implement number of rotation for drill machine but whenever drill starts to rotate, LCD prints bad characters instead of displaying rotation.
Here is my code:
#include<LiquidCrystal.h>

 LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);
             int SensorPin=      13;

             int Counter = 0;
void setup() {
  lcd.begin(16,2);
  pinMode(SensorPin,INPUT);
    lcd.setCursor(0,0);

}

void loop() {

           lcd .setCursor(0,0);

          if(digitalRead(SensorPin))
  {
    Counter = Counter+1;
    while(digitalRead(SensorPin));

  }
  lcd.setCursor(0,1);
     lcd.print(Counter);
  // put your main code here, to run repeatedly:

}

Here is my lcd at initial step:

When I start my drill, LCD changes to this:

I suspect you get electrical noise on the leads from the optocoupler. A few test to help find cause:
1) Does the counter work if you rotate it by hand?
2) Does the LCD go funnny if you just have the optocoupler approximatly in the same position, but not count anything.

Msquare thanks for replay i found out the problem that as you have seen i put the screen on galvanized metal whenever drill starts the screen gets noise i don't know why there is no touching part of lcd and galvanized material. thanks


text:
Stream video from camera to mobile and send control signal back from mobile to Arduino via WiFi
I want to make an Ardunio based project in which I want to stream live video from camera (which is connected to Arduino borad ) to my Android app via WiFi and send back actions/control signals from my android app to Arduino to controller servo motor which are connected to Arduino board. Right now I only have Arduino mega with me. What else components are going to be required?

Most Arduino platforms (there are many) can not handle video.  There is simply too much data. A quick internet search find this talked about many times.  Here for instance.  Where the discussion quickly elevates to a more powerful platform such as a Raspberry Pi.

Nope, a Mega is not up to the task. It may be possible with an ESP directly, but it will be way easier with a Raspberry Pi (for example the Zero W, which is quite small)

you can use independent WiFi IP camera for the live video

I had heard of esp32 cam which is suitable for live video streaming to mobile buy can we control servo motor from that.

You need good MPU with enough buffer size and nand size for such an intense process
Search esp modules
Thanks.

What do you mean by the distingtion between buffer size and NAND size? Also: can you provide a bit more information about how it would look like with an ESP?


text:
arduino firmware
Hi I was wondering if there is any way to/ how I might go about solving the following.
I am designing my own arduino board based on a mega32u4 chip and I want my arduino board to light up an indicator led depending on if an analog pin is in use. For example if a user uploads code that utilizes a certain pin say reading a voltage from A0, the arduino would light up an LED next to that pin.
I was thinking perhaps I could tie the analog pin to a digital pin in the firmware and have the digital pin go HIGH every time the analog pin is in use(is this possible/ could anyone point me to good examples online)?
The user needs to know whether or not the pin they think is writing is actually outputting a signal and/or if the pin they think is reading is reading a signal. This is beacause they will be hooking up outputs and inputs to the arduino board using conductive ink and if their circuit isnt working the indicator lights will let them know that their software is working but there is probably a break in the circuitry they drew out.

Sounds like you would like a LED per pin to indicate usage, mode, etc? You could do this with a shift register or GPIO port extender and then modify the Arduino core pinMode() and analogRead() so that the status is shown on the respective LED. If I remember correctly the mega32u4 has a few extra pins that are not used by the Arduino core. These could be used for the LED control.

First you will have to define "in use". Do you mean actively using analogRead(), or just that something is connected to the pin?

It takes about 100 microseconds (0.0001 s) to read an analog input. So I doubt you can see the leds flash that fast.

Mikael, this sounds like a feasible solution but could it be implemented behind the scenes such that the user does not see the code? Like I suppose I would have to implement my own modified core that the user would select my board in the tools>board menu. It feels like that might be bad practice to have those functions write to other pins (anyone want to weigh in?) but it is a solution.

Majenko, I was imagining that the user would have the pin mentioned in their code somewhere regardless of whether or not anything was connected. Would it be possible to have an indicator light turn on if something was connected (even if it was an input device)?

it may be possible to design a hardware solution for turning on a LED when something is connected to the pin

Any ideas @Jsotola?

using specialized connectors, such as a 2.5mm phono connectors .... one pin would be used for the signal ... the other pin would be for insertion detection  .........  pin mentioned in their code somewhere ...  this would be a problem, because having the code in the program and actually running the code are not the same thing ....... you would have to use an outside program to scan the code and find any references to any of the analog pins

i  think that you are underestimating people's level of inattention to detail ..... you can have all the flashing lights in the world, and they will still connect the wrong pin ..... also, there is this .... "Why did you connect the wire to pin 5?" .... "I don't know why, but the light told me to connect it."

@Chris, did you see my answer?

When you upload code that is the firmware. There isn't another lot of firmware (like an operating system) that is always there (excepting the bootloader which is only used for uploading new code).
Maybe you could connect an LED, via an op-amp as an amplifier, to the analog pin, so that if a voltage appears that it would light the LED. However it could be "in use" and reading zero volts so that wouldn't prove an enormous lot.

would it be ill advised to attempt a solution on the lines of what Mikael proposed in the comments?

You can make your own analogRead function and encourage your users to use it (or do it via a #define) however that will only work if people use your new function or header file.
It would also have the side-effect of making other pins not available (ie. the pins you are doing the LED on) which might be confusing for users who are trying to use all available pins.
I assume this is some sort of teaching gadget? It might be better to teach people to do an indicator LED themselves rather than trying to automate it for them.

Thanks for the clarification Nick, would it be ill advised to attempt a solution on the lines of what Mikael proposed in the comments?

See amended answer.

Create a library. User will include it and the h file will create a single instance of the handler object for your pin pairs. The handler will register a timer interrupt, and the interrupt will check the source pin and set the target pin.


text:
Reprogram Atmega 16u2 on Arduino Mega with Arduino IDE?
I had an Arduino mega 2560, suddenly Arduino didn't recognize my computer and I thought the problem is about Atmega 16u2 and I decided to copy hex file from another Arduino Atmega 16u2 and paste to damaged Arduino but it didn't work.
in fact, in our laboratory, we don't have any Linux and other software to reset or reprogram Atmega 16u2 on the other hand I know several methods to solve the problem but I need to know can I use the Arduino IDE to reset Atmega 16u2 without other software.
thanks a lot.

Another option is to use FDU to upload the 16u2

@Gerben, isn't that page outdated?

Yes, you can recover the firmware in 16u2 only with Arduino IDE installed. In subfolder hardware/arduino/avr/firmwares/atmegaxxu2/ of the IDE installation folder is the hex file of the firmware Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex. The README.txt file in that folder has sample command line to upload the firmware with avrdude.


text:
Arduino std::map returning random values
I'm working with an arduino UNO. I would like to be able to send it set and get commands over serial and have it update class data class members accordingly by key value pair. I spoke to users in the cpp room, and they suggested I try using map to map every key to value.
command structure
command:key:value
ex. set:key1:20
ex. get:key2
I created a class called Uno, assigned all my keys to private data members, and defined set and get functions. However, I am experiencing unintended behavior.
Unintended behavior
The set function ends up setting key1 and key2 to the same value, and the get function returns a random integer value that wasn't assigned.
  #include <ArduinoSTL.h>
  #include <string.h>
  #include <map>

class Uno{
  //private
    int key1;
    int key2;
    std::map<String, int Uno::*> keys;
  public:
  //Constructor
    Uno(){
      key1 = 0;
      key2 = 0;
      keys["key1"] = &Uno::key1;
      keys["key2"] = &Uno::key2;
    }
    bool setKey(String key, int value){
      if (keys.count(key)) {
          this->*keys[key] = value;
          return true;
      }
      return false;
    }
    int getKey(String key){
      if (keys.count(key)) {
          return this->*keys[key];
      }
    }
};

String inputString = "";      // a String to hold incoming data
bool stringComplete = false;  // whether the string is complete
bool scan = false;            // whether a scan is in progress
Uno myMS;                      // global declaration of Mass Spec Class

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // reserve 250 bytes for the inputString:
  inputString.reserve(250);
}

void loop() {
  if (stringComplete) {
    t(inputString); // tokenize and process string

    //RESET STRING
    inputString = "";
    stringComplete = false;
  }
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag so the main loop can
    // do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

void t(String inputString) {
    //get command
    String command = getValue(inputString, ':', 0);

    if(command == "set"){
      // get key, get value
       String key = getValue(inputString, ':', 1);
       int value = (getValue(inputString, ':', 2)).toInt();
       Serial.println(myMS.setKey(key,value));
    }
    else if(command == "get"){
       String key = getValue(inputString, ':', 1);
       int value = myMS.getKey(key);
       Serial.println(value);
    }
    else if(command == "stop"){
       scan = false;
    }
    else if(command == "scan"){
       scan = true;
       while(scan){
//        Serial.println(myMS.scan());
       }
    }
    else{
       Serial.println("not recognized");
    }
}

String getValue(String data, char separator, int index)
{
  int found = 0;
  int strIndex[] = {0, -1};
  int maxIndex = data.length()-1;

  for(int i=0; i<=maxIndex && found<=index; i++){
    if(data.charAt(i)==separator || i==maxIndex){
        found++;
        strIndex[0] = strIndex[1]+1;
        strIndex[1] = (i == maxIndex) ? i+1 : i;
    }
  }
  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}

EDIT: Here is a REPL IT working demo of concept provided by nwp.
https://repl.it/repls/AntiqueProductiveMineral
Sample output
set:key1:10 ===> 1 (GOOD)
get:key1 ===> 32512

why do you think that this is an Arduino question? ... it appears to be a C/C++ question

@jsotola It is an arduino question, because I am running the code on the arduino using the arduino String type.  I am also using Serial on the arduino. I'm open to other arduino methods for storing key value pairs.

the 32512 is the return value of getKey if it didn't found the key

Ok, but that is confusing because I am using the same method to set. I know the set function is working correctly, because if I do Serial.println(key1); from inside the class it prints the correct value.

You get random values because if the key is not found in getKey, then there is no return statement.
You attach the \n to the key in serialEvent(), then the key for getKey is "key1\n" and it is not found.
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    if (inChar == '\n') {
      stringComplete = true;
    } else {
      inputString += inChar;
    }
  }
}

If you have CR/LF set in Serial Monitor, then the \r character is send too and the parsed key is "key1\r\n".
There are obsolete things in your code, like the this->* or Uno::. Make the map std::map<String, int> keys;, because now you mix pointers and ints.

I have Newline only and it's not working anyways

change the serialEvent to not to attach the \n to the string

Right, he's not skipping it in that parser :D

Ok, I like your approach, it works!


text:
l293d is not able to drive two 300 rpm motors simultaneously
I am using l293d in a line follower but recently I am facing a problem. my l293d motor driver is not able to power 2 300 rpm motors simultaneously while with one of the motors at a time it works perfectly fine. Earlier it used to drive both the motors at optimal desired speed but recently its posing the above mentioned problems. I have tried replacing the Motor driver and Arduino itself but nothing worked and I am still facing the problem.

What is your power source, is it able to supply the current for 2 motors? The L293d with proper heatsinking should supply .6A per channel which seems like it should be sufficient for a robot under minimal load. I would check the batteries!

yeah the power source is just  fine .. I use a 12V-1A power adapter from the beginning . Earlier it worked just fine but recently this whole arrangement just got messed up with the motor driver failing to drive the 2 motors.

Do you have an earlier revision of the code? Could it be something software related?

I sense the code is all fine because the motor driver isn't able to drive the two motors simultaneously even when I directly connect them to the l293d outputs without taking any inputs from the Arduino .

Please post your code. I have seen this problem before, the OP claimed that it was a power/board problem and it turned out to be a bug in the code.

@SomitSinha Please also post your wiring/circuit diagram. You can either use the inbuilt circuit tool or you can draw it using Fritzing.

Check if both channels are working in either direction individually.
Check the current draw under the load per motor using an Digital Multimeter as an Ammeter function.

The L293 is designed to provide bidirectional drive currents of up to 1A at voltages from 4.5V to 36V.
600mA per channel for L293D

As long as your motors at drawing more than 600mA per motor, it should work fine.

Check your power supply with a multimeter. Look out for voltage drops under load, or similar problems.
Also, make some tests with another power supply in order to find out if the one you're currently using is faulty or not. You say you've tried replacing the motor driver and the arduino, but not the power supply.


text:
5V usb surge protection for circuit board?
I want to use a mini usb jack to power my device off board, but I want to make sure that the usb power coming in is not any higher than the 5V. I've read a bit about polyfuses but I am unsure if they would be useful for this scenario. Thanks!

Arduinos can handle a wide variety of voltages.  The main reason to keep it below about 7 is simply to reduce heat stress on the on-board regulator.  Putting the voltage in via the Vin pin bypasses the regulator, though.  Using the mini USB will definitely limit the current the unit can draw for driving output pins.

you can use an LM7805 or an AMS117 LDO@5v to snub any excess voltage. It might "warble" at ~5v, but it will stop higher voltages dead in their tracks.

@SDsolar below 7V? Well, according to the datasheet on Vin pin you should give voltages ABOVE 7V (otherwise the regulator cannot work properly) or give it exactly 5V on the +5V pin (bypassing the regulator). No other ways...

@dandavis LM7805 has a dropout voltage of around 2V, so if you power it with 5V you will get 3V on its output. The AMS1117 (not AMS117) has a lower dropout, but it's still greater than 1V, thus giving you at most 4V

Below 7v for the normal barrel-style plug which goes through the regulator.     Vin goes directly into the circuit and can handle 12 Volts.

@frarugi87: i measured 4.4v from 5v on an AMS, and 3.76 from a LM, but good point. A cheap 5.1v zener would be simpler, ex: http://electronics.stackexchange.com/questions/81429/why-do-we-connect-a-resistor-before-a-zener-diode

@dandavis yes, the dropout varies with the current. Maybe the datasheet data are trimmed for a 1A, I forgot to check. Anyway the zener solution has the problem of the resistor: if you want it to protect up to 6V (and no more than 6V) and a 1W zener, you can use a resistor to let at most 150mA in the zener. If the circuit draws 200mA, this means that the resistor is about 2.5 Ohm. When you give it 5V, the zener will turn off, and the 200mA will cause a 0.5V drop on the resistor, thus giving you 4.5V...

A polyfuse will limit current not voltage.
There are transient protection diodes which switch on if voltage exceeds a given level, which are often used in conjunction with a polyfuse. The diodes cause excessive current to flow, effectively turning on the polyfuse for extended overload, or just absorbing shorter transients. The Raspberry Pi uses a SMBJ5.0A device to suppress transients.
You should NOT need any of this if you use a reasonable power supply.

What is the recommended way of adding reverse polarity protection to surge protection in such a circuit ?

Raspberry Pi is different from Arduino.  The specs say to never put in more than about 5.5 Volts.  Since power supplies are widely available for Rpi boards, it should be easy to find one that is regulated enough.  The Pi itself doesn't draw all that much power, but the more USB devices you plug into it will increase the current requirements.  Total current for all 4 USB ports should not exceed 1.5 Amps.  If you are running an external hard drive it is best if it has its own power supply.

The easiest way to ensure polarity protection is with a full-wave rectifier.  4 diodes.  The only negative is that each diode would have some voltage drop.  So in my case I use approved power supplies that can only be plugged in one way.  But if you want to build a full-wave rectifier, here is what they look like:  https://www.google.com/search?q=full+wave+rectifier&newwindow=1&source=lnms&tbm=isch&sa=X&ved=0ahUKEwi4jdmimLLSAhWHCBoKHfCCChMQ_AUICCgB&biw=1211&bih=548#imgrc=yidbnb0eK_wGWM:

@SDsolar. Thanks. I don't want to incur a voltage drop because the USB supply should already be 5volts, regulated, with the correct polarity and the circuit design will assume that, but also protect itself in the case that it isn't the case, or there is a voltage spike (lightning strike in the electricity distribution network etc.). I guess I use the series polyfuse, the tvs diode across the supply after the polyfuse and say a 1N4007 normal diode reversed also across the supply after the poly fuse.

You hit the nail on the head.  That's why I just use regulated power supplies with the micro-USB plug that enforces polarity physically.

@6v6gt - this is really another question entirely (this question is about surge protection). Please post it as a new question. No-one will find your question (and any answers under it) as comments about surge protection.

@NickGammon . You're right. I've put the question here: http://electronics.stackexchange.com/questions/289649/circuit-protection-incorporating-a-transient-voltage-supressor-and-polyfuse

I second Milliways answer:

You should NOT need any of this if you use a reasonable power supply.

Anyway, if you really have a crappy power supply you can use one of the modules you find on ebay (for instance this is the first result I came across). Be sure to look for "buck boost" modules (step up/down), because they can both raise and lower the voltage.
This will do the job your power supply is not able to do, so to give you a stable voltage. You can then also vary the voltage without worrying (they usually are able to handle 4V (e.g. lithium batteries), 7.2V (e.g. 2 lithium batteries), 12V, ...
If you want also reverse protection, I suggest you to simply put a diode in series with THE INPUT (anode on the positive of your power supply, cathode on the IN+ terminal of this regulator). This way the voltage drop will be absorbed by the regulator. You can use a cheap 1N4007 or even a Schottky diode (which have less drop -> better power consumption).
I discourage you from using a full wave rectifier, since the diodes on the ground will change the ground reference (and so if you connect something else you may experience problems).
You can find a lot of "buck/boost" modules out there, just check that the input and output voltages and currents are suitable for your project.
But again, unless your power supply is really crappy you won't need this. If you just need an inversion protection, you can also use a circuit I found on a PC : put a fuse (they used a real fuse, you can use a polyfuse) between the power positive input and the circuit positive, then add a diode with the anode to ground and the cathode to the circuit positive. If you attach it correctly the diode will be reverse polarized and the circuit will work correctly, if you attach it in reverse the diode will conduct and so will create a large current which will trip the fuse.