text:
Arduino AT Cmd Not Working
We are Using I-CUBE-LRWA Lora Module AT Cmd with Arduino ProMini
Set of commands set with DockLight working Perfectly but with Arduino, we are getting some coded response and well every time RXTimeout response.
Docklight Response

Arduino Response :

Arduino Code:
mySerial.flush();
lora.flush();
Serial.flush();
digitalWrite(lorapin, HIGH);
delay(500);
lora.listen();
lora.print(“AT\r\n”);
String dr = lora.readStringUntil("\r\n");
delay(10);
Serial.print(“AT:” + dr);
Serial.println();

                lora.print("ATZ\r\n");
                String ATZ = lora.readStringUntil("\r\n");
                delay(10);
                Serial.print("ATZ:"+ATZ);
                Serial.println();

                lora.print("AT+NJM=0\r\n");
                String NJM = lora.readStringUntil("\r\n");
                delay(10);
                Serial.print("AT+NJM:" + NJM);
                Serial.println();

                lora.print("AT+DADDR=as:23:00:00\r\n");
                String DADDR = lora.readStringUntil("\r\n");
                delay(10);
                Serial.print("AT+DADDR:" + DADDR);
                Serial.println();

                lora.print("AT+APPSKEY=90:22:53:85:44:7A:22:32:75:35:26:35:63:30:A9:56\r\n");
                String APPSKEY = lora.readStringUntil("\r\n");
                delay(10);
                Serial.print("AT+APPSKEY:"+APPSKEY);
                Serial.println();

                lora.print("AT+DEUI=5bb1605000032as\r\n");
               String DEUI = lora.readStringUntil("\r\n");
                delay(10);
                Serial.print("AT+DEUI:" + DEUI);
                Serial.println();
                lora.print("AT+NWKSKEY=23:43:67:9A:22:44:22:69:50:67:3A:A3:34:27:26:72\r\n");
                String NWKSKEY = lora.readStringUntil("\r\n");
                delay(10);
                Serial.print("AT+NWKSKEY:" + NWKSKEY);
                Serial.println();

                lora.println("AT+CFM=1\r\n");
                String CFM = lora.readStringUntil("ok\r\n");
                delay(10);
                Serial.print("AT+CFM:" + CFM);
                Serial.println();

                lora.println("AT+ADR=1\r\n");
                String ADR = lora.readStringUntil("\r\n");
                delay(10);
                Serial.println();
                Serial.print("AT+ADR:" + ADR);
                Serial.println();

                lora.print("AT+CLASS=C\r\n");
                String CLASS = lora.readStringUntil("ok\r\n");
                delay(10);
                Serial.print("CLASS:" + CLASS);
                Serial.println();

                lora.print("AT+JOIN\r\n");
                String JOIN = lora.readStringUntil("ok\r\n");
                delay(10);
                Serial.print("JOIN:" + JOIN);
                Serial.println();
                delay(500);

                lora.print("AT+NJS=?\r\n");
                String NJS = lora.readStringUntil("ok\r\n");
                delay(10);
                Serial.print("NJS:" + NJS);
                Serial.println();
                delay(500);

                String sendatavar="AT+SEND=2:30";
                Serial.print(sendatavar);
                Serial.println();
                lora.print(sendatavar);
                delay(10000);
                String sedndr = lora.readStringUntil("rxDone\r\n");
                delay(1000);
                Serial.print("AT+send:" + sedndr);

So how exactly did you connect the hardware? Can you show a photo? Also is this running on an Arduino Nano or Pro Mini? You have added both question tags. What voltage is the Pro Mini running on?

What Baud rate you used in the Arduino code?

@Fahad Baud Rate 9600

@MaximilianGerhardt i'm using 5v pro mini

Can you show a wireup or schematic?

The COM Output image you posted, the baud rate is showing 57600. Maybe that's why you are seeing garbage output?


text:
Arduino UNO + USB Host Shield 2.0 + RFID RFC522
I'm trying to get done following. Connect a Keyboard over USB -> USB Host Shield -> Grab the pushed key (char) from the keyboard and write them to the rfid writer.
So the code for the rfid writer is done, and works well - but only over the serial monitor (osx) / putty(win10).
Watt also works is the USBHIDbootKbd from the examples of the USB_Host_Shield_Library_2.0.
So was I exactly need is grab the key'(s) from the keyboard until e.g. '/', store them into a buffer and send / write it to the code line of the rfid writer.
First line for input is where comment:  // Ask personal data: Password
and second  // Ask personal data: user name.
attached is the code for the rfid writer
Thanks in advice
Cheers
    /*
 * Write personal data of a MIFARE RFID card using a RFID-RC522 reader
 * Uses MFRC522 - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 *
 * Hardware required:
 * Arduino
 * PCD (Proximity Coupling Device): NXP MFRC522 Contactless Reader IC
 * PICC (Proximity Integrated Circuit Card): A card or tag using the ISO 14443A interface, eg Mifare or NTAG203.
 * The reader can be found on eBay for around 5 dollars. Search for "mf-rc522" on ebay.com.
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         5           // Configurable, see typical pin layout above
#define SS_PIN          6          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

void setup() {
  Serial.begin(9600);        // Initialize serial communications with the PC
  SPI.begin();               // Init SPI bus
  mfrc522.PCD_Init();        // Init MFRC522 card
  Serial.println(F("Write personal data on a MIFARE PICC "));
}

void loop() {

  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  Serial.print(F("Card UID:"));    //Dump UID
  for (byte i = 0; i < mfrc522.uid.size; i++) {
    Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte[i], HEX);
  }
  Serial.print(F(" PICC type: "));   // Dump PICC type
  MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
  Serial.println(mfrc522.PICC_GetTypeName(piccType));

  byte buffer[34];
  byte block;
  MFRC522::StatusCode status;
  byte len;

  Serial.setTimeout(20000L) ;     // wait until 20 seconds for input from serial
  // Ask personal data: Password
  Serial.println(F("Type your Password, ending with #"));
  len = Serial.readBytesUntil('#', (char *) buffer, 30) ; // read family name from serial
  for (byte i = len; i < 30; i++) buffer[i] = ' ';     // pad with spaces

  block = 1;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("PCD_Authenticate() success: "));

  // Write block
  status = mfrc522.MIFARE_Write(block, buffer, 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

  block = 2;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  // Write block
  status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

  // Ask personal data: User Name
  Serial.println(F("Type your User Name, ending with #"));
  len = Serial.readBytesUntil('#', (char *) buffer, 20) ; // read first name from serial
  for (byte i = len; i < 20; i++) buffer[i] = ' ';     // pad with spaces

  block = 4;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  // Write block
  status = mfrc522.MIFARE_Write(block, buffer, 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

  block = 5;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  // Write block
  status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

  Serial.println(" ");
  mfrc522.PICC_HaltA(); // Halt PICC
  mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD

}

what is your question? ... you said nothing about any problem

i'm not able to store / use the input from the keyboard and write them into the query from the rfid code. The rfid code waiting for an input from the Serial monitor. So o need to change that is it waiting for the input from the keyboard

source: Stack Exchange

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

sort: votes


text:
Creating a library for arduino
I found a really nice 24 bit I2C adc which was fairly cheap as well (ADS1219) but as far as I could tell there are no libraries for it so I decided to make my own. I have managed to write functions and get everything working on the arduino itself but I've been having massive issues with converting it into a library.
So I tried a very basic sketch to see if I can do something as simple as printing hello world using the library.
Here is my ADS1219.h file:
#ifndef ADS1219
#define ADS1219

#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

class ADS1219{
public:
 ADS1219();
 void begin();
 void printHello();
};

#endif

And the ADS1219.cpp:
#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

#include

ADS1219::ADS1219{
 Serial.println("New object created!");
}

void ADS1219::begin(){
 Serial.begin(9600);
}

void ADS1219::printHello(){
 Serial.println("Hello World");
}

and my main sketch:
#include

ads = new ADS1219;

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

void loop() {
  ads.printHello();
  delay(2000);
}

but I get this really long error which basically says I've failed with creating the ads object.
I tried ADS1219 ads; as well but same error ... not sure what's wrong tbh.
Arduino: 1.8.8 (Windows 10), Board: "Arduino Nano, ATmega328P (Old Bootloader)"

In file included from sketchADS1219.cpp:7:0:

ADS1219.h:14:11: error: expected unqualified-id before ')' token

   ADS1219();

           ^

ADS1219.h:12:14: error: an anonymous struct cannot have function members

 class ADS1219{

              ^

ADS1219.h:18:1: error: abstract declarator '' used as declaration

 };

 ^

ADS1219.cpp:9:17: error: expected id-expression before '{' token

 ADS1219::ADS1219{

                 ^

ADS1219.cpp:13:21: error: explicit qualification in declaration of 'void begin()'

 void ADS1219::begin(){

                     ^

ADS1219.cpp:17:26: error: explicit qualification in declaration of 'void printHello()'

 void ADS1219::printHello(){

                          ^

In file included from C:UsersOM222ODesktopadslibadslib.ino:1:0:

ADS1219.h:14:11: error: expected unqualified-id before ')' token

   ADS1219();

           ^

ADS1219.h:12:14: error: an anonymous struct cannot have function members

 class ADS1219{

              ^

ADS1219.h:18:1: error: abstract declarator '' used as declaration

 };

 ^

adslib:3:1: error: 'ads' does not name a type

 ads = new ADS1219;

 ^

C:UsersOM222ODesktopadslibadslib.ino: In function 'void setup()':

adslib:7:3: error: 'ads' was not declared in this scope

   ads.begin();

   ^

C:UsersOM222ODesktopadslibadslib.ino: In function 'void loop()':

adslib:11:3: error: 'ads' was not declared in this scope

   ads.printHello();

   ^

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

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Sorry I didn't know that existed ... there are so many different SEs hahaha. I'll move it to there.

First error is "#define ADS1219". Use the convention "#define ADS1219_H" instead. Please come back for more C++ help :).

That changed absolutely nothing :D

I even tried downloading the exact code some poeple showed to create libraries but I still had no luck! literally the exact same code doesn't wanna work on my machine! Any ideas on what I might be doing wrong? edit: here is the link which I followed: https://www.alanzucconi.com/2016/05/11/libraries-for-arduino/

You don't have to check for an old arduino version. That is no longer used. It is almost 2019. Just include the Arduino.h (only in the file ADS1219.h). What is a #include without specifying which file to include? In the sketch a ads ADS1219; is enough. Github is full of arduino libraries, you can find many examples there, for example: https://github.com/Locoduino/SlowMotionServo/tree/master/src and https://github.com/winlinvip/SimpleDHT (just two random chosen libraries, there must be hundreds of them).

@Jot that is exactly what I have done which is why I even have the line to check for arduino versions ... I don't know what version 1 is, but I directly copied that part of the header from other libraries. As I said, I'm directly copying other people's code and seeing where it breaks for now, till I learn to write everything from scratch :D

I created the exact same question here ... and I can't delete this one ... can somebody else do it? I don't wanna be spamming questions

I think I stuffed up the merging of the two questions. This is now the active one.

@OM222O did you have a look at those two random examples? The difference between those and your code is what is wrong. We told you everything to make it work. Fix the define, fix the includes, add the "()" for the constructor, remove the "= new" for the declaration. That's all, then it will work.

Your problem stems from this line:
#define ADS1219

You define the macro ADS1219 as empty. From that point on all references to ADS1219 get replaced with nothing. For example:
class ADS1219{
public:
 ADS1219();
 void begin();
 void printHello();
};

becomes:
class {
public:
 ();
 void begin();
 void printHello();
};

And
void ADS1219::begin(){
 Serial.begin(9600);
}

becomes:
void ::begin(){
 Serial.begin(9600);
}

By using the same name in your header guard as your class name you screw everything else up.
I always use strict rules for header guard macros to ensure that they never conflict with anything else.  You should change yours to read something else.  I would use:
#ifndef _ADS1219_H
#define _ADS1219_H

// ... content

#endif

You are also lacking the parenthesis in the constructor implementation:
ADS1219::ADS1219{
 Serial.println("New object created!");
}

should read:
ADS1219::ADS1219(){
 Serial.println("New object created!");
}

And you don't give your ads variable a type and you don't want to use new:
ads = new ADS1219;

should read:
ADS1219 ads;

Also in the cpp file he should not include again the Arduino.h file, but rather include only the library file (ADS1219.h). Moreover, in my libraries I stopped including WProgram.h. Do you think it is still required?

I haven't included wprogram.h for ages. It doesn't hurt to include a file multiple times as headers should include header guards.

thanks this has fixed my issue for now :D I will try to finis the rest on my own but I still might need some help.I'll publish it as soon as I finished

I have made a lot of progress and almost everything works fine ... except I initially used strings in switch case for setting up the voltage reference and conversion modes ... it did not like it at all. I instead aimed to use enums for the same purpose but I'm getting this error now:
Arduino: 1.8.8 (Windows 10), Board: "Arduino Nano, ATmega328P (Old Bootloader)"

In file included from sketch\LibraryExample1.ino.cpp:1:0:

C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:81:18: error: expected identifier before numeric constant

 #define INTERNAL 3

                  ^

C:\Users\OM222O\Documents\Arduino\libraries\ADS1219/ADS1219.h:49:3: note: in expansion of macro 'INTERNAL'

   INTERNAL = VREF_INTERNAL,

   ^

C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:81:18: error: expected '}' before numeric constant

 #define INTERNAL 3

                  ^

C:\Users\OM222O\Documents\Arduino\libraries\ADS1219/ADS1219.h:49:3: note: in expansion of macro 'INTERNAL'

   INTERNAL = VREF_INTERNAL,

   ^

C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:81:18: error: expected unqualified-id before numeric constant

 #define INTERNAL 3

                  ^

C:\Users\OM222O\Documents\Arduino\libraries\ADS1219/ADS1219.h:49:3: note: in expansion of macro 'INTERNAL'

   INTERNAL = VREF_INTERNAL,

   ^

In file included from C:\Users\OM222O\Desktop\LibraryExample1\LibraryExample1.ino:2:0:

C:\Users\OM222O\Documents\Arduino\libraries\ADS1219/ADS1219.h:51:1: error: expected declaration before '}' token

 }adsRef_t;

 ^

exit status 1
Error compiling for board Arduino Nano.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

my ADS1219.h file is:
#ifndef ADS1219_H
#define ADS1219_H

#if (ARDUINO >=100)
  #include "Arduino.h"
#else
  #include "WProgram.h"
#endif

#include <Wire.h>

#define CONFIG_REGISTER_ADDRESS 0x20
#define STATUS_REGISTER_ADDRESS 0x24

#define MUX_MASK                0x1F
#define MUX_DIFF_0_1            0x00
#define MUX_DIFF_2_3            0x20
#define MUX_DIFF_1_2            0x40
#define MUX_SINGLE_0            0x60
#define MUX_SINGLE_1            0x80
#define MUX_SINGLE_2            0xA0
#define MUX_SINGLE_3            0xC0
#define MUX_SHORTED             0xE0

#define GAIN_MASK               0xEF
#define GAIN_ONE                0x00
#define GAIN_FOUR               0x10

#define DATA_RATE_MASK          0xF3
#define DATA_RATE_20            0x00
#define DATA_RATE_90            0x04
#define DATA_RATE_330           0x08
#define DATA_RATE_1000          0x0c

#define MODE_MASK               0xFD
#define MODE_SINGLE_SHOT        0x00
#define MODE_CONTINUOUS         0x02

#define VREF_MASK               0xFE
#define VREF_INTERNAL           0x00
#define VREF_EXTERNAL           0x01

typedef enum{
  ONE   = GAIN_ONE,
  FOUR  = GAIN_FOUR
}adsGain_t;

typedef enum{
  INTERNAL  = VREF_INTERNAL,
  EXTERNAL  = VREF_EXTERNAL
}adsRef_t;

typedef enum{
  SINGLE_SHOT   = MODE_SINGLE_SHOT,
  CONTINUOUS    = MODE_CONTINUOUS
}adsMode_t;

class ADS1219  {
  protected:
    uint8_t address;
  public:
    // Constructor
    ADS1219(int drdy, uint8_t addr = 0x40);

    // Methods
    void begin();
    void resetConfig();
    long readSingleEnded(int channel);
    long readDifferential_0_1();
    long readDifferential_2_3();
    long readDifferential_1_2();
    long readShorted();
    void setGain(adsGain_t gain);
    void setDataRate(int rate);
    void setConversionMode(adsMode_t mode);
    void setVoltageReference(adsRef_t vref);

  private:
    void writeRegister(uint8_t data);
    uint8_t readRegister(uint8_t reg);
    long readConversionResult();
    uint8_t config;
    int data_ready;
};
#endif

and my cpp file is:
#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

#include <Wire.h>
#include "ADS1219.h"

static uint8_t i2cRead(void) {
  #if ARDUINO >= 100
  return Wire.read();
  #else
  return Wire.receive();
  #endif
}

static void i2cWrite(uint8_t x) {
  #if ARDUINO >= 100
  Wire.write(x);
  #else
  Wire.send(x);
  #endif
}

ADS1219::ADS1219(int drdy, uint8_t addr) {
  data_ready = drdy;
  address = addr;
  config = 0x00;
}

void ADS1219::begin() {
  Wire.begin();
}

uint8_t ADS1219::readRegister(uint8_t reg){
  Wire.beginTransmission(address);
  i2cWrite(reg);
  Wire.endTransmission();
  Wire.requestFrom((uint8_t)address,(uint8_t)1);
  return i2cRead();
}

void ADS1219::writeRegister(uint8_t data){
  Wire.beginTransmission(address);
  i2cWrite(CONFIG_REGISTER_ADDRESS);
  i2cWrite(data);
  Wire.endTransmission();
}

long ADS1219::readConversionResult(){
  Wire.beginTransmission(address);
  i2cWrite(0x10);
  Wire.endTransmission();
  Wire.requestFrom((uint8_t)address,(uint8_t)3);
  byte dataMSB = i2cRead();
  byte data = i2cRead();
  byte dataLSB = i2cRead();
  long data32 = dataMSB;
  data32 <<= 8;
  data32 |= data;
  data32 <<= 8;
  data32 |= dataLSB;
  return (data32 << 8) >> 8;
}

void ADS1219::resetConfig(){
    writeRegister(0x00);
}

long ADS1219::readSingleEnded(int channel){
    if (channel > 3) return 0;
    config &= MUX_MASK;
    switch (channel){
    case (0):
      config |= MUX_SINGLE_0;
      break;
    case (1):
      config |= MUX_SINGLE_1;
      break;
    case (2):
      config |= MUX_SINGLE_2;
      break;
    case (3):
      config |= MUX_SINGLE_3;
      break;
    default:
      break;
  }
  writeRegister(config);
  while(digitalRead(data_ready)==1);
  return readConversionResult();
}

long ADS1219::readDifferential_0_1(){
  config &= MUX_MASK;
  config |= MUX_DIFF_0_1;
  writeRegister(config);
  while(digitalRead(data_ready)==1);
  return readConversionResult();
}

long ADS1219::readDifferential_2_3(){
  config &= MUX_MASK;
  config |= MUX_DIFF_2_3;
  writeRegister(config);
  while(digitalRead(data_ready)==1);
  return readConversionResult();
}

long ADS1219::readDifferential_1_2(){
  config &= MUX_MASK;
  config |= MUX_DIFF_1_2;
  writeRegister(config);
  while(digitalRead(data_ready)==1);
  return readConversionResult();
}

long ADS1219::readShorted(){
  config &= MUX_MASK;
  config |= MUX_SHORTED;
  writeRegister(config);
  while(digitalRead(data_ready)==1);
  return readConversionResult();
}

void ADS1219::setGain(adsGain_t gain){
    config &= GAIN_MASK;
    config |= gain;
  writeRegister(config);
}

void ADS1219::setDataRate(int rate){
    config &= DATA_RATE_MASK;
    switch (rate){
    case (20):
      config |= DATA_RATE_20;
      break;
    case (90):
      config |= DATA_RATE_90;
      break;
    case (330):
      config |= DATA_RATE_330;
      break;
    case (1000):
      config |= DATA_RATE_1000;
      break;
    default:
      break;
  }
  writeRegister(config);
}

void ADS1219::setConversionMode(adsMode_t mode){
    config &= MODE_MASK;
    config |= mode;
  writeRegister(config);
}

void ADS1219::setVoltageReference(adsRef_t vref){
    config &= VREF_MASK;
    config |= vref;
  writeRegister(config);
}

it seems to be passing Gain (or maybe hasn't compiled that yet) but failing on the reference selection ... I don't know what I should change in order to fix the issue.
Edit: I'm really hoping it's not another naming convention thing ... if it is, I'm sorry but C++ seems to waaaaayyyy too picky about names in general

Hint: Use a private enum for all the control codes etc. Using #define is old-school and actually the root-cause of many of the issues. C++ allow namespaces, private, const, etc, which is much more semantic rich. Here is an example to help you along; https://github.com/mikaelpatel/Cosa/blob/master/libraries/ADXL345/ADXL345.hh

Hint: To avoid some of the constants, masks, etc, it is possible to use bit-fields in struct's. Here is an example: https://github.com/mikaelpatel/Cosa/blob/master/libraries/DS2482/DS2482.hh

thanks a lot! I'll have a look. I'm most of the way finished with the program :D

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


text:
Arduino timer interrupts for PID
I'm working on a robotics project where an arduino nano is acting as the motion controller. I'm trying to use a trapezoidal motion profile generator and PID loop to follow that profile, but I found out the motion was quite jerky and I assumed it's because both the motion profile and the PID run at the same speed (10ms loop using timer interrupt library)
#include <TimerOne.h>
void setup() {
  Timer1.initialize(10000);
  Timer1.attachInterrupt(Compute);
}

now I want to use two seperate loops, one running at the same 10ms interval for the profile generation and one running at 1ms for the PID (I'm not sure if the motors can actually act that quickly, but I can adjust the timings a bit), this way the PID has about 10 loops to get to the desired position accurately, reducing the jerky motion.
I'm not sure how I can set up two different interrupts using that library or by setting the flags like TCCR0A to generate the desired interrupt timers.
Here's the actual "Compute" function in case it's relevant (there are some bugs regarding the direction and it's using two different methods for generating the profile, also I'm changing it so don't think it matters, but just in case it does, I posted it)
void Compute(){
  int dir;
  if (setPoint > target){
    dir = 1;
  } else if (setPoint < target){
    dir = -1;
  }
  if (mode == 1) {
    target += v*dir;
    if (abs(setPoint - target) <= turningPoint){
      v -= acceleration;
    } else {
      if (v < maxV){
        v += acceleration;
      }
    }
    if (abs(target) >= abs(setPoint)){
      target = setPoint;
      mode = 0;
      v = 0;
      Serial.println("Finished!");
    }
    #ifdef DEBUG
      printDebug();
    #endif
  } else if (mode ==2){
    target += v*dir;
    if (phase == 1 and v < reachableV){
      v += acceleration;
      if (v >= reachableV){
        phase = 3;
        v = reachableV;
      }
    } else if (phase == 3){
      v -= acceleration;
      if (v <= 0){
        target = setPoint;
        mode = 0;
        v = 0;
        phase = 0;
        Serial.println("Finished!");
      }
    }
    #ifdef DEBUG
      printDebug();
    #endif
  }
  error = target- pos;
/////////////////////////////////////////////////
  PID_P = kp * error;
  if (PID_P > outMax) PID_P = outMax;
  if (PID_P < outMin) PID_P = outMin;
/////////////////////////////////////////////////
  if (abs(error) < 50){
    PID_I += ki * error * sampleTime;
  } else {
    PID_I *= 0.8;
  }
/////////////////////////////////////////////////
  PID_D = kd * (pos - lastPos) / sampleTime;
  if (PID_D > outMax) PID_D = outMax;
  if (PID_D < outMin) PID_D = outMin;
/////////////////////////////////////////////////
  output = PID_P - PID_D + PID_I;
  if (output > outMax) output = outMax;
  if (output < outMin) output = outMin;
/////////////////////////////////////////////////
  lastPos = pos;
  if (output < 0){
    digitalWrite(DIR,1);
  } else {
    digitalWrite(DIR,0);
  }
  analogWrite(PWM,abs(output));
/////////////////////////////////////////////////
}

p.s: I'm most likly going to use the PID library instead of trying to write my own like I currently have the code.

When you speak about different loops, does that mean, that you previously didn't use interrupts for this?

no I mean two loops with different periods, one running at 10ms and one at 1ms. I'm using a single 10ms interrupt timer right now.

the ISR should be as brief as possible and should not contain any serial I/O code ... if you wish to print a message, then use a flag ... set the flag in the ISR ... print message and clear the flag in loop()

Just use a single 1ms timer interrupt and count them. Every 10 interrupts do both things.
void interruptHandler() {
   counter++;

   // do things that happen every 1ms

   if(counter == 10) {
      // do things that happen every 10ms
      counter = 0;
   }
}

that'd be a nice solution but I'm assuming there are better ways to do this? the counters have 3 options for interrupt: A, B and overflow. I'm assuming this was done to set a PWM signal with duty cycle and frequency control, but I'm not sure how to set the proper flags to use them.

Why would you assume that?  What is wrong with this solution?  Newbies always want something "elegant" and by that they mean hard to understand or deep into the hardware.  But that's not very often the case.  If you do this with separate interrupts then the 1ms and the 10ms will both have to fire at the same time.  Thus one interrupt will be late and you'll have the extra overhead time interrupting your other code.  Sometimes the simple answer is really the best answer.  What would there be to gain by having one interrupt exit and another enter late?  You want to waste time?

In order to set two interrupts on that timer and have one be at 10ms, then you have to let the timer run all the way to 10ms.  So for every 1ms interrupt you have to update the OCRA register to a new time so it fires at 1ms then 2ms then 3ms then 4ms.  If you want the interrupts to be regular then you'll have to calculate how much to add each time.  What's better about that?

You could use a second timer, but then you lose PWM on two more pins.  And I assume you're wanting to use Timer1 for the 16 bit resolution.  You only get one of those.  So you'd have to give up resolution on the second interrupt.  How does that help?


text:
How to find the peak value of analog signal?
I have a question .. Please help me I don't know how Arduino can read the peak value of the sensor signal. The value I want is in the ADC value .. What I want is ... for 5 seconds there will be 1 average value from the highest peak value of the sensor, and the ADC value. I will use pin A0, but I don't know how to code the program that I want. Please help me What is the code?

See if I understand this correctly: For a given time period you want to find the peak.
void setup()
{
  unsigned long int cur_time = 0 ;
  unsigned long int time_elapsed = 0;
  int peaks[20]; // say you want to find 20 peaks , 1 peak for data arriving between 5 secs
  int time_period = 5000;
  int data = 0;
  int mx=0;
}

void loop()
{
   for(int i = 0 ; i<20;i++)
   {
      cur_time = millis();
      while(cur_time - time_elapsed <=time_period)
      {
             if(mx==0)
              { mx = analogRead(A0); }
              else:
               {  data = analogread(A0);
                  mx = max(data , mx);
               }
              cur_time = millis();
        }
         time_elapsed = cur_time;
         peaks[i] = mx;
         mx = 0;
        }
  }

Hope this helps!!


text:
ESP8266/Android app: slow response when using soft access point and keeps dropping connection
I have an ESP8266 which I'm using the Arduino IDE to compile a program which
uses soft access points to talk to an Android App compiled using MIT App Inventor. The app seems to work the first couple times but then my cell phone looses connection and I have to go to Settings->Wifi connections and rescan and wait for it to connect. Sometimes it says: "Denied access to network" and sometimes (most always) after I connect I will get a message that says I'm not connected to the internet, which I don't want, and then choose 'No' to stay connected to the current network. My cell phone is right next to the ESP8266 and the signal strength is 'Excellent'. I'm only powering the board via the USB cable connected to it. Do I need to run 3v3 to the pin marked '3V3'?
Here's the code:
// server running on ESP8266 to get commands from Android App
// Load Wi-Fi library
#include <ESP8266WiFi.h>

// Replace with your network credentials
const char *ssid = "PanzerD"; // The name of the Wi-Fi network that will be created
const char *password = "testasdf";   // The password required to connect to it, leave blank for an open network
// Set web server port number to 80
WiFiServer server(80);
IPAddress local_IP1(192,168,0,15);
IPAddress gateway1(192,168,0,1);
IPAddress subnet(255,255,255,0);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state

// Assign output variables to GPIO pins
int tool_box_lights = 0;
int pass_side_lights = 0;
int drv_side_lights = 0;
int rear_lights = 0;
int winch = 0;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

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

  Serial.print("Setting soft-AP configuration ... ");
  Serial.println(WiFi.softAPConfig(local_IP1, gateway1, subnet) ? "Ready" : "Failed!");
  Serial.println(WiFi.softAP(ssid,password,1,4) ? "Ready" : "Failed!");

  Serial.print("Soft-AP IP address = ");
  Serial.println(WiFi.softAPIP());

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
/*
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
*/
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
//  Serial.println("IP address: ");
//  Serial.println(WiFi.localIP());
  server.begin();
}

void loop(){
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
//    Serial.print("Client: ");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
      currentTime = millis();
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
//        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            //Serial.println(header);
            // turns the GPIOs on and off
            if (header.indexOf("/tb/on") >= 0)
            {
              Serial.println("toolbox on");
              client.println("toolbox on");
              tool_box_lights = 1;
            } else if (header.indexOf("/tb/off") >= 0)
            {
              Serial.println("toolbox off");
              client.println("toolbox off");
              tool_box_lights = 0;
            } else if (header.indexOf("/ps/on") >= 0)
            {
              Serial.println("pass side on");
              client.println("pass side on");
              pass_side_lights = 1;
            } else if (header.indexOf("/ps/off") >= 0)
            {
              Serial.println("pass side off");
              client.println("pass side off");
              pass_side_lights = 0;
            } else if (header.indexOf("/ds/on") >= 0)
            {
              Serial.println("drv side on");
              client.println("drv side on");
              drv_side_lights = 1;
            } else if (header.indexOf("/ds/off") >= 0)
            {
              Serial.println("drv side off");
              client.println("drv side off");
              drv_side_lights = 0;
            } else if (header.indexOf("/rr/on") >= 0)
            {
              Serial.println("rear lights on");
              client.println("rear lights on");
              rear_lights = 1;
            } else if (header.indexOf("/rr/off") >= 0)
            {
              Serial.println("rear lights off");
              client.println("rear lights off");
              rear_lights = 0;
            } else if (header.indexOf("/wc/in") >= 0)
            {
              Serial.println("winch in");
              client.println("winch in");
              winch = 1;
            } else if (header.indexOf("/wc/out") >= 0)
            {
              Serial.println("winch out");
              client.println("winch out");
              winch = 2;
            } else if (header.indexOf("/wc/off") >= 0)
            {
              Serial.println("winch off");
              client.println("winch off");
              winch = 0;
            }
            // Display the HTML web page
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
//    Serial.println("Client disconnected.");
//    Serial.println("");
  }
}

Here's the blocks for the MIT App Inventor:

Each one of the blocks responds to a button press and depending on what the global variable is (upper left block is for toolbox lights) it will send the URL "/tb/on" in the case for turning the toolbox lights on.
[Edit:] It works fine when I use the modem as an access point but I need soft access points because I don't want to have to carry a router around in my truck.

Apparently I'm not formatting the html right and it's causing the connection to drop.


text:
using RTOS SDK - crashes when adding another task
(I hope this is the right place to ask questions about the ESP8266_RTOS_SDK)
I have a program that I've taken from the samples directory (protocols/tcp_client) in the RTOS SDK and added code from the uart sample just so I can use the keyboard to tell the client when to start. The tcp_client task simply does a socket send to & recv from the server (a simple sockets server running on a linux desktop). It runs great until I tried to add another sample task:
 static void test_task(void *pvParameters)
    {
        vTaskDelay(MYDELAY2);
        ESP_LOGI(TAG, "asdf 123");
    }

And then, in the app_main(), I create the task:
xTaskCreate(test_task, "test", 2048, NULL, 10, NULL);

I try to run it and it either locks up and then crashes or just crashes as soon as it connects to the server. It usually crashes right after it prints out the message in the test_task.
 #include <string.h>
    #include <sys/param.h>
    #include "freertos/FreeRTOS.h"
    #include "freertos/task.h"
    #include "esp_system.h"
    #include "esp_log.h"
    #include "esp_netif.h"
    #include "esp_event.h"
    #include "protocol_examples_common.h"
    #include "nvs.h"
    #include "nvs_flash.h"
    #include "lwip/err.h"
    #include "lwip/sockets.h"
    #include "lwip/sys.h"
    #include <lwip/netdb.h>
    #include "freertos/queue.h"
    #include "driver/uart.h"

    #define HOST_IP_ADDR CONFIG_EXAMPLE_IPV4_ADDR
    #define MYDELAY1 (75 / portTICK_PERIOD_MS)
    #define MYDELAY2 (125 / portTICK_PERIOD_MS)
    #define MYDELAY3 (250 / portTICK_PERIOD_MS)
    #define MYDELAY4 (500 / portTICK_PERIOD_MS)
    #define MYDELAY5 (1000 / portTICK_PERIOD_MS)
    #define MYDELAY6 (2000 / portTICK_PERIOD_MS)
    #define MYDELAY7 (5000 / portTICK_PERIOD_MS)
    #define PORT CONFIG_EXAMPLE_PORT

    static const char *TAG = "example";
    #define EX_UART_NUM UART_NUM_0
    #define BUF_SIZE (1024)
    #define RD_BUF_SIZE (BUF_SIZE)
    static QueueHandle_t uart0_queue;
    unsigned char state;
    int sock;

    static void test_task(void *pvParameters)
    {
        vTaskDelay(MYDELAY2);
        ESP_LOGI(TAG, "asdf 123");
    }

    static void tcp_client_task(void *pvParameters)
    {
        char rx_buffer[128];
        char send_buff[100];
        char addr_str[128];
        int addr_family;
        int ip_protocol;
        int i = 0;
        char xbyte = 0x21;
        int len, err;

        struct sockaddr_in destAddr;
    //  destAddr.sin_addr.s_addr = inet_addr(HOST_IP_ADDR);
    // can set ip address either explicitly or using 'make menuconfig' and go to 'example      configuration'
        destAddr.sin_addr.s_addr = inet_addr("192.168.88.103");
        inet_ntoa_r(((struct sockaddr_in *)&destAddr)->sin_addr.s_addr, addr_str, sizeof(addr_str) -     1);
        ESP_LOGI(TAG, "address : %s", addr_str);
        destAddr.sin_family = AF_INET;
        destAddr.sin_port = htons(PORT);
        addr_family = AF_INET;
        ip_protocol = IPPROTO_IP;
        inet_ntoa_r(destAddr.sin_addr, addr_str, sizeof(addr_str) - 1);

        sock =  socket(addr_family, SOCK_STREAM, ip_protocol);
        if (sock < 0)
        {
            ESP_LOGE(TAG, "Unable to create socket: errno %d", errno);
            state = 51;
        }
        ESP_LOGI(TAG, "Socket created %d",sock);

        memset(send_buff,0,sizeof(send_buff));
        for(i = 0;i < 99;i++)
        {
            send_buff[i] = xbyte;
            if(++xbyte > 0x7e)
                xbyte = 0x21;
        }
        send_buff[99] = 0;

        ESP_LOGI(TAG,"press '1' to connect, then press '2' to start client, '3' to shutdown");

        while (1)
        {
            switch(state)
            {
                case 0:
                vTaskDelay(MYDELAY3);
                break;
            case 49:
                err = connect(sock, (struct sockaddr *)&destAddr, sizeof(destAddr));
                if (err != 0)
                {
                    ESP_LOGE(TAG, "Socket unable to connect: errno %d", errno);
                    close(sock);
                    vTaskDelay(MYDELAY1);
                    state = 0;
                }
                ESP_LOGI(TAG, "Successfully connected %d",err);
                state = 0;
                break;
            case 50:
                //ESP_LOGI(TAG, "starting...");

                err = send(sock, send_buff, 80, 0);
                if (err < 0)
                {
                    ESP_LOGE(TAG, "Error occured during sending: errno %d", errno);
                    state = 0;
                    break;
                }
                //ESP_LOGI(TAG,"send returned: %d",err);

                vTaskDelay(MYDELAY1);

                len = recv(sock, rx_buffer, 80, 0);
                // Error occured during receiving
                if (len < 0)
                {
                    ESP_LOGE(TAG, "recv failed: errno %d", errno);
                    state = 0;
                    break;
                }
                else
                {
                    rx_buffer[len] = 0; // Null-terminate whatever we received and treat like a string
                    //ESP_LOGI(TAG, "Received %d bytes from %s:", len, addr_str);
                    ESP_LOGI(TAG, "%s", rx_buffer);
                }

                vTaskDelay(MYDELAY1);

                if (sock == -1)
                {
                    ESP_LOGE(TAG, "Shutting down socket, press '1' to restart...");
                    shutdown(sock, 0);
                    close(sock);
                    state = 0;
                }
                break;
            case 51:
                ESP_ERROR_CHECK(example_disconnect());
                break;
            case 52:
                shutdown(sock,0);
                close(sock);
                ESP_LOGI(TAG,"shutdown - deleting task");
                vTaskDelete(NULL);
                break;
            default:
                ESP_LOGI(TAG,"press '1' to connect, then press '2' to start client %d",state);
                vTaskDelay(MYDELAY3);
                state = 0;
                break;
        }
    }
}
//#if 0
static void uart_event_task(void *pvParameters)
{
    uart_event_t event;
    int i;
    uint8_t *dtmp = (uint8_t *) malloc(RD_BUF_SIZE);

    for (;;) {
        // Waiting for UART event.
        if (xQueueReceive(uart0_queue, (void *)&event, (portTickType)portMAX_DELAY)) {
            bzero(dtmp, RD_BUF_SIZE);
            //ESP_LOGI(TAG, "uart[%d] event:", EX_UART_NUM);

            switch (event.type) {
                // Event of UART receving data
                // We'd better handler data event fast, there would be much more data events than
                // other types of events. If we take too much time on data event, the queue might be full.
                case UART_DATA:
                    ESP_LOGI(TAG, "[UART DATA]: %d", event.size);
                    uart_read_bytes(EX_UART_NUM, dtmp, event.size, portMAX_DELAY);
                    state = dtmp[0];
                    ESP_LOGI(TAG,"state: %d",state);
//                    uart_write_bytes(EX_UART_NUM, (const char *) dtmp, event.size);
                    break;

                // Event of HW FIFO overflow detected
                case UART_FIFO_OVF:
                    ESP_LOGI(TAG, "hw fifo overflow");
                    // If fifo overflow happened, you should consider adding flow control for your application.
                    // The ISR has already reset the rx FIFO,
                    // As an example, we directly flush the rx buffer here in order to read more data.
                    uart_flush_input(EX_UART_NUM);
                    xQueueReset(uart0_queue);
                    break;

                // Event of UART ring buffer full
                case UART_BUFFER_FULL:
                    ESP_LOGI(TAG, "ring buffer full");
                    // If buffer full happened, you should consider encreasing your buffer size
                    // As an example, we directly flush the rx buffer here in order to read more data.
                    uart_flush_input(EX_UART_NUM);
                    xQueueReset(uart0_queue);
                    break;

                case UART_PARITY_ERR:
                    ESP_LOGI(TAG, "uart parity error");
                    break;

                // Event of UART frame error
                case UART_FRAME_ERR:
                    ESP_LOGI(TAG, "uart frame error");
                    break;

                // Others
                default:
                    ESP_LOGI(TAG, "uart event type: %d", event.type);
                    break;
            }
        }
    }
    free(dtmp);
    dtmp = NULL;
    vTaskDelete(NULL);
}
//#endif

void app_main()
{
    ESP_ERROR_CHECK(nvs_flash_init());
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    ESP_ERROR_CHECK(example_connect());
        uart_config_t uart_config = {
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE
    };
    uart_param_config(EX_UART_NUM, &uart_config);

    // Install UART driver, and get the queue.

    uart_driver_install(EX_UART_NUM, BUF_SIZE * 2, BUF_SIZE * 2, 100, &uart0_queue, 0);

    xTaskCreate(test_task, "test", 2048, NULL, 10, NULL);

    xTaskCreate(uart_event_task, "uart_event_task", 2048, NULL, 12, NULL);

    xTaskCreate(tcp_client_task, "tcp_client", 2048, NULL, 5, NULL);
}

When I added the task for the uart it works, but when I add the task to print the test message and do the time delay, it crashes.

I didn't have the task as an infinite loop. It should be:
static void test_task(void *pvParameters)
{
    while(1)
    {
        vTaskDelay(MYDELAY6);
        ESP_LOGI(TAG, "test 123");
     }
}


text:
Program crashes when calling external library code via function pointer
I've written a user library for the Pi Pico that uses the TaskScheduler library to abstract timing away from the user. The user provides a function in their sketch which the library calls periodically via function pointer passed in the constructor.
When I stick to standard Arduino or functions from my library, everything works fine. If I include a function from the ADC library I'm using, core1 hangs while the comms on core0 continue to respond. If I run the same ADC operation from a non-callback function on the same core it works as expected. What is happening?
The relevant code snippets follow:
Library:
class Card {
public:
  typedef void (*ExtCbPtr)();  //pointer type to call sketch code from library
  ExtCbPtr _readCB;            //function pointer, points at user routine in sketch
  ExtCbPtr _writeCB;

  Card(ExtCbPtr readFunc, ExtCbPtr writeFunc); //constructor
private:
  Task readInputs;
  Task writeOutputs;
  Scheduler ts1;
};

Card::Card(ExtCbPtr readFunc, ExtCbPtr writeFunc) {
  this->_readCB = readFunc;    //use to call user's sketch code
  this->_writeCB = writeFunc;
}

void Card::begin() {
  //init scheduler tasks
  ts1.init();
  ts1.addTask(readInputs);
  ts1.addTask(writeOutputs);

  readInputs.setInterval(100);
  readInputs.setIterations(10);
  readInputs.setCallback(_readCB);
  writeOutputs.setInterval(100);
  writeOutputs.setIterations(10);
  writeOutputs.setCallback(_writeCB);
}

void Card::core1Loop() {
  ts1.execute();
}

Sketch:
static void writeOut();
static void readIn();
Card card(readIn, writeOut);
Adafruit_ADS1115 ads;  //ADC

void setup(){

rp2040.idleOtherCore();

//setup ADC
  if (!ads.begin()) {
    Serial.println("Failed to initialize ADS.");
  }
  ads.setDataRate(0x00E0);  //860 samples per second, every conversion takes ~1.2mS
  ads.setGain(GAIN_ONE);    //0.125mV/LSB

  card.begin();  //initialise
  rp2040.resumeOtherCore();
  Serial.println("Ready 0");
}

void setup1(){
  delay(1);
  Serial.println("Ready 1");
}

void loop1();
  card.core1Loop();
}

void readIn() {
  Serial.println("Read start");
  uint16_t adc =  ads.readADC_SingleEnded(0);  //problematic line
  Serial.println("Read end");
}

void writeOut(){
   //Doesn't matter, task not reached if read fails
}

Are interrupts involved? Try taking out the serial prints from the callback function.

Did you try a simpler sketch to verify the compatibility of the Adafruit_ADS1115  readADC_SingleEnded(0) method with Scheduler?

I spent three hours on this yesterday. Come in today, turn the system on, and everything works. PEBKAC?


text:
Issues with reading numbers from serial port
I've built 2 motor drivers for a robotics project and need to set positions that I want the motors to move to, and read that using the arduino. The arduino then uses a rotary encoder to implement a closed loop PID controller and move the motor the set point. My code wasn't working so I started troubleshooting and found out that my setpoint was getting reset to 0 automatically!
The only thin that changes the setpoint was the serial read so I made a smaller sketch for troubleshooting which is this:
volatile long setpoint;

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

void loop() {
  if (Serial.available()){
    setpoint = Serial.parseInt();
    Serial.print("Set to: ");
    Serial.println(setpoint);
  }
}

The result was quite odd, it sets the value correctly but resets back to 0 without me sending any new commands!
I tried updating the IDE to 1.8.12, tried old and new arduinos (with old and new bootloader) but all had the same result. Here is a demo video showing the weird reset to 0 problem:
https://streamable.com/kfgv61
I tried changing the buadrate higher or lower but that also didn't fix anything. Any ideas on what I'm doing wrong?

The problem here is that Serial.parseInt() stops when it sees the
newline, but it does not consume that newline, which is left in the
input buffer. Thus, at the next loop iteration, Serial.available()
returns true because of this newline and, unless you send another value
fast enough, Serial.parseInt() times out and returns zero.
The easy fix is to consume that newline yourself:
void loop() {
  if (Serial.available()){
    setpoint = Serial.parseInt();
    if (Serial.peek() == '\n') Serial.read();  // consume LF
    Serial.print("Set to: ");
    Serial.println(setpoint);
  }
}

I personally would not use Serial.parseInt() at all, and would buffer
the data myself until I see the '\n'. This way there are
no surprises with timeouts being read as zero.


text:
Access is denied. Error compiling for board Arduino/Genuino Uno
Having this  error-
Arduino: 1.8.8 Hourly Build 2018/11/30 12:33 (Windows 10), Board: "Arduino/Genuino Uno"
open sketch\LCD.ino.cpp: Access is denied.
Error compiling for board Arduino/Genuino Uno.
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

High likely one of the intermediate/binary files is in use. For example:

When you have it already opened in a debug session
Having it opened in multiple instances of your IDE
Having it opened in another application
Having closed an application that locked the intermediate/binary file(s).

What you can do:

Close the debug session
Close all applications related to the project
Restart your computer


text:
Can Arduino Uno R3 board remove chip on the board
First off, got my Elegoo Uno board as Christmas gift, so this is all new to me.
Here is my problem, I built an motor project and the chip has been programmed. Can I remove the chip from the Uno board?
Or can I placing a new chip onto the Uno board?
Best regards.

Unless you messed with the fuses you can reprogram the chip again with a new program.

The question is not clear, please edit.  What do you mean by "remove"?  I can imagine, for example, that your Uno board is one of the older versions where the atmega328 is DIP packaged.  If this is the case, then yes, you can remove the chip after programming and place on another board.

I you want to place a new chip, you have to burn the Arduino bootloader to it first. Some stores sell ATMega328Ps with bootloader already on it.

why do you want to remove the chip?

It depends, if the chip has not been soldered, but placed in an IC (DIP) socket, than you can remove the programmed chip, and use it in another circuit and place another (same) IC in the IC socket of the Uno to be reprogrammed.
You also could desolder it, but I would not advice that; also most of the Uno's having a soldered IC use SMD instead of DIP.
Also, to replace the IC, you need to install a bootloader on the IC to be placed in the new Arduino (thanks for the addition Roberto Lo Giacco).
Below is a version with DIP that easily can be replaced, hence the big IC and the socket:

Below is a version with SMD that cannot easily be replaced, hence the small IC without a socket:

This is to me the right answer, but I would also add a note regarding the required bootloader for the new Atmega328P.

@RobertoLoGiacco Thanks, I added your comment (giving you the credits).

Yes, you can pull the DIP chip off the board, and use it elsewhere. It will require a 16 MHz crystal and two 22pF caps (or a 16MHz resonator), at least three 0.1uF (aka 100nF) caps (connect one each from VCC, AVCC, AREF to gnd - do not connect Aref to VCC), a 10K resistor from Reset to Vcc.
If you have a  hot air rework station and decide to pull off the SMD part, that chip has two VCC pins, so another 0.1uF cap is needed.


text:
PT100 and MAX31865 readings showing wrong
I am using PT100 (3 Wire) to measure the temperature with Arduino Uno and MAX31865.
I have connected everything perfectly.
Configuration in the code i am using is :
max1.begin(MAX31865_3WIRE);

And the output is:
output
RTD value: 0
Ratio = 0.00000000
Resistance = 0.00000000
Temperature = -242.02

I am testing it in a room temperature.
My question is , is there any settings or calibration that i need to do, or any other way to test the PT100 sensor, because the temperature is showing correct readings ?

I had the same problem and was solved due to the comment of fshero (Jun 3 at 11:35) about a capacitor wich drops the voltage on PIN 20 of the MAX31865.
I have logged in just to highlight the solution. Thanks fshero!!

I've the same problem with my shields;
Where is the componant to remove on the shield to solve the problem?
a picture of the modification is welcome thanks a lot
fabien

I nearly have the same problem. I use five of the MAX31865-Boards with 2-Wire Termocouples on an Arduino Nano. Two of the five boards are working perfectly. The other 3 boards show exactly the same wrong behaviour you described. My temperature readings are exactly like yours (-242.02).
But I think I found the reason for the not working ones: The two working boards I bought on Amazon. The other three not working boards I bought on AliExpress. Maybe I (and maybe you too) got really bad fakes from China and they are simply dead :(
(BTW: If I remove one working board from the SPI bus and read out the temperature with the arduino, I get also the value of -242.02. This value seems to be an error value in the Adafruit MAX31865 library)
EDIT: Fixed it with a workaround!Like shown in the picture below, simply remove the wrong component (SMD Capacitor) and create a solder bridge . See comments for more informations!
Here is a picture of my modification of one chinese board as requested by the comments:

(It's not the best solution, but it works. For final using you should get the right filter ferrite and solder it on the board!)

I figured out the source of the error in my case: After some "debug measuring" with a multimeter I recognized, that the voltage of the VDD Pin of the Sensor is too low (1.6V but 3.3V are required)! It seems the chinese version has a capacitor at the place, where a originally a filter ferrite should be (see part FB1
at adafruit_products_schem.png). This causes the voltage drop. I removed the capacitor and replaced it with a solder bridge. Et voilá. It's working perfectly! :D

If wanted, I can provide some pictures of my modification

Can you provide a picture of the modification please..it will help me a lot.

Sure :) Look at my updated post. Hope this helps.

You have the eye of a vulture! Great find! Had the exact same issue, couldn't make the boards work until I removed that darn capacitor. These Chinese components are cheap, but come with some surprise headaches.


text:
MAX9611/2 - receiving junk data
I'm connecting to a MAX9611 on a custom PCB (using a SAMD Cortex M0 running an Adafruit Feather bootloader) using I2C. I have code that reads the voltage, current and temperature from the internal registers, but I'm receiving junk data from the voltage and current registers. Temperature works reliably.
Sometimes voltage and current are 0. Sometimes voltage is 10x what it should be (that's the raw ADC value - this isn't a conversion bug). The current reading depends on whether the temperature request is commented out or not.
I've been reading through the documentation for a day now and can't see what I'm doing wrong. The kicker is that the code to request the register data is essentially identical (just pointing at different registers) between the working temperature request and the non-working voltage and current requests. I have posted it below, along with the relevant schematic section - does anyone have any ideas what I'm doing wrong?
Thanks!
#include <Wire.h>

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

void loop()
{
  Serial.print("mV:   ");  Serial.println(get_MAX9611_voltage());
  Serial.print("mA:   ");  Serial.println(get_MAX9611_current());
  Serial.print("Temp: ");  Serial.println(get_MAX9611_temp());
  Serial.println();
  delay(1000);
}

uint16_t get_MAX9611_voltage (void)
{
  Wire.beginTransmission(0x70);
  Wire.write(0x0A);                             //Select control register 1
  Wire.write(0x03);                             //Set mux to read from RS+
  Wire.endTransmission();

  Wire.beginTransmission(0x70);
  Wire.write(0x02);                             //Select RS+ data register MSB
  Wire.endTransmission();

  Wire.requestFrom(0x70,2);
  uint8_t msb = Wire.read();                    //Read RS+ MSB
  uint8_t lsb = Wire.read();                    //Read RS+ LSB

  uint16_t MAX9611_voltage = word(msb,lsb);
  MAX9611_voltage = MAX9611_voltage >> 4;       //shift right by 4 due to 12 bit value
  MAX9611_voltage = MAX9611_voltage*14;       //57.3V full scale, 14mV per ADC step

  return MAX9611_voltage;
}

uint16_t get_MAX9611_current (void)
{
  Wire.beginTransmission(0x70);
  Wire.write(0x0A);                             //Select control register 1
  Wire.write(0x02);                             //Set mux to read from current sense amplifier with gain 8x, full scale = 55mV
  Wire.endTransmission();

  Wire.beginTransmission(0x70);
  Wire.write(0x00);                             //Select CSA data register MSB
  Wire.endTransmission();

  Wire.requestFrom(0x70,2);
  uint8_t msb = Wire.read();                    //Read CSA MSB
  uint8_t lsb = Wire.read();                    //Read CSA LSB

  uint16_t MAX9611_current = word(msb,lsb);

  MAX9611_current = MAX9611_current >> 4;       //shift right by 4 due to 12 bit value
  MAX9611_current = (MAX9611_current*0.01342)*5;  //ADC value in millivolts, I=V/R where R is 0.2

  return MAX9611_current;
}

int16_t get_MAX9611_temp (void)
{
  Wire.beginTransmission(0x70);
  Wire.write(0x0A);                             //Select control register 1
  Wire.write(0x06);                             //Set mux to read from temp sensor
  Wire.endTransmission();

  Wire.beginTransmission(0x70);
  Wire.write(0x08);                             //Select temp data register MSB
  Wire.endTransmission();

  Wire.requestFrom(0x70,2);
  uint8_t msb = Wire.read();                    //Read temp MSB
  uint8_t lsb = Wire.read();                    //Read temp LSB

  int16_t MAX9611_temp = word(msb,lsb);
  MAX9611_temp = (((MAX9611_temp >> 7) * 480)/1000);                     //shift right by 7 due to 9 bit value, LSB is 480mC

  return MAX9611_temp;
}

That didn't take long to find the bug... Continuous read mode requires 2ms pause between each ADC read. I'm reading far faster than that, especially considering my micro is far faster than the 8 bit 328s that many other examples use. I added 2ms delay between reads and the problem seems to have disappeared, although I will have to check the current measurements when I have access to better equipment.

Happens to me too occasionally, that after writing a post searching for a bug for a long time, I find it myself shortly afterwards. Good that you posted the answer to help others with similar problems.


text:
Arduino RS485 communication protocol - minimising overheads and best practice
I'm building a single master multiple slave RS485 network for remote sensors on test equipment. I have the hardware built and working, and I can do a Serial.print on the master and have the slaves display the values received on their attached OLED screens. The goal is for the master to cycle through the slave addresses one by one and request data, then wait for the slave to respond (or timeout and register as a fail on the master's GUI).
The issue I have is that to work out if a packet is intended for a slave device I have to parse the entire packet, wait for start and end packets, and check the address. This means every device has to capture and check every packet on the network for its own address byte. If I compare on the fly I can exit the serial loop as soon as I know which device the packet is intended for, but the next received packet will just re-open the serial loop part way through transmission.
Other than disabling the RS485 transceiver between packets, is there an elegant way to solve this issue without massive overheads?
My hardware uses Arduino Nanos (master is currently an Uno but will be a piece of National Instruments hardware) and MAX13487 transceivers.
Thanks!

Have you looked into BACnet / MS/TP (Master-Slave/Token Passing) or TDMA (Time Division Multiple Access) protocols? I don't know enough about your project to recommend one or the other.

@StarCat Those look like they'd help avoid collisions, but I'm not so worried about that. I'm not sure they avoid the slaves having to listen for a request packet destined for them.

Are you using modbus?

@haresfur no, should I be?

RS485 is the hardware layer and MODBUS is a software layer for communicating over RS485 that is commonly used for sensors so it may have done some of the heavy lifting for you. I don't know enough to say if it will help or not.


text:
I need to Get my changed SSID and Password in my Serial monitor
I have this(Wifi Manager - Autoconnect IP) program run in my arduino IDE. And I get the output in serial monitor as this

Can Anyone help me in displaying my SSID and PASS in this serial monitor output?
My code is this
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>         //https://github.com/tzapu/WiFiManager

void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);

    //WiFiManager
    //Local intialization. Once its business is done, there is no need to keep it around
    WiFiManager wifiManager;
    //reset saved settings
    //wifiManager.resetSettings();

    //set custom ip for portal
    //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

    //fetches ssid and pass from eeprom and tries to connect
    //if it does not connect it starts an access point with the specified name
    //here  "AutoConnectAP"
    //and goes into a blocking loop awaiting configuration
    wifiManager.autoConnect("AutoConnectAP");
    //or use this for auto generated name ESP + ChipID
    //wifiManager.autoConnect();

    //if you get here you have connected to the WiFi
    Serial.println("connected...yeey :)");
}

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

}

I am using WIFImanager library example - Autoconnect

https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-class.html#ssid

Thank you for the link juraj.. btw where should I add that line of code. In the main program or in the header file??

You can use functions SSID() and psk() which are available on the WiFi object as documented here.
Put these lines in setup() after wifiManager.autoConnect:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
Serial.print("psk: ");
Serial.println(WiFi.psk());


text:
How to detect the direction of rotation with a sensor encoder timing disk (photoelectric speed sensor)?
I am making a DIY gaming steering wheel and am stuck.
For measuring the rotation of the wheel, I'm using a sensor encoder timing disk, which is usually found in printers. - https://robu.in/product/photoelectric-speed-sensor-encoder-coded-disc-code-wheel.
A lot of tutorials on youtube use this.
But I just cannot seem to understand how to use this sensor.
Please help me in figuring this out: using this sensor, how to -

Measure how much the wheel rotated?
Know which direction did the wheel rotates in (clockwise, anti-clockwise).

PS: I tried using a rotatory encoder, but it is unable to sense rotation when rotated by a 1000 RPM motor. Would love to understand why.
Thanks!

From the product description it isn't clear, if the sensor has 1 or 2 phototransistors. If it has only 1, you cannot sense the direction. If it has two, it is simple A/B encoding like any rotary encoder. Can you provide a more specific and detailed datasheet?

It seems to be a A/B coding : if A gets high before B, it's one way (count for exemple), and if B gets high before A, it's other way (decount).
So, connect power and ground. Then connect the two wires to input pins :
    int P_A=2; int P_B=3; //Inputs
    long int position = 0; //Position of wheel
    long int lastPosition = 0; //last position of wheel : for speed computing

Notice that one pin must be an hardware interrupt pin (Uno 2 an 3 are interrupt pins. Then attach interrupt in the stup :
    attachInterrupt(2, wheel, RISING);  //wheel is arbitray

Then create the interruption code :
    void wheel(){
        int sB = digitalRead(P_B);
        if (sA == sB)   { //Clockwise
        position++;
        }
        else   { //Counterclockwise
        position--;
        }

Then, in your loop, you can print position when it changes to read current position :
    if(lastPosition != position){
        Serial.println(position);
    }

i hope it will help...
Notice that if you use both interruptions, you get a better resolution, but speed limit is lower.

I'm having trouble understanding this. Could you please provide a code snippet?


text:
Arduino problem
I'am making a temperature monitor using an IC2 Interface and a dht11 sensor connected to an arduino uno, it works great when it´s plugged to the computer but whenever i plug it to a 9v battery the humidity goes to "0" and the temperature to "2", it only works when i resend the code through the ide to the arduino.
What could be the problem?
Code :
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
DHT dht;

void setup()
{
  lcd.begin(16,2);
  lcd.clear();
  dht.setup(7); // Pino 7

}

void loop(){

  float humidade = dht.getHumidity();
  float temperatura = dht.getTemperature();

  lcd.setCursor(0,0);
  lcd.print("Humidade: ");
  lcd.print(humidade);
  lcd.print("%");

  lcd.setCursor(0,1);
  lcd.print("Temp: ");
  lcd.print(temperatura);
  lcd.print("C");

  delay(1000);

}

why are you posting the code? ... you said that it works correctly

Just so you can see it´s output

think about what you did to make it fail

Fixed it by clicking the red button on the arduino uno.

The 9v sort of "cube shaped" batteries have a notoriously limited current output, resulting in falling voltage as the current demand rises. The Arduino's voltage regulator is not very effecient either, plus the battery gives only 2v of "headroom" over the minimum Vin voltage of 7v. Your system is probably starving. Try a different source.

Im new to arduino i got it fixed by clicking the red button in the arduino board, it started giving me the right numbers connected to the 9v battery.


text:
Weird effect of AVR C on USB-serial communication
I recently decided to learn direct port manipulation instead of builtin arduino routines.
First I tried this piece of code
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("on");
delay(500);
digitalWrite(LED_BUILTIN, LOW);
Serial.println("off");
delay(500);
}

This program on running instantly established connection with the serial monitor on my arduino IDE.
But when I try this code
int main(void)
{
Serial.begin(9600);
DDRB = B11111111;
while(1)
{
PORTB = PORTB | 0x20;
Serial.println("off");
_delay_ms(500);
PORTB = PORTB & 0xDF;
Serial.println("on");
_delay_ms(500);
}
}

But this program is taking some time, about 5-10 seconds to establish serial connection. Also delay() is not working too. When I use delay() instead of _delay_ms(), the entire arduino board freezes like a computer and stops blinking the LED instead LED is fully ON.
I tried is on several programs, while "setup-loop" program connects instantly, AVR C programs does not.
why does it happen?

Because normally main() initializes all the appropriate hardware and timers. You're circumventing that with your own main() so nothing Ardunioy works.

I should be most grateful if you could elaborate that in an answer.

please indent your code correctly .... beginners that might be browsing the quetions should be exposed to correctly formatted code no matter how simple the code listing is

By defining your own main() you are circumventing the Arduino startup procedures.
Normally with Arduino code main() first runs an init() function before setup() and (repeatedly) loop().  This init() function will configure, amongst other things, the timer for millis() and delay().
This is the normal main() for a basic AVR-based board:
int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

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

    return 0;
}

It first initializes common functions, then board-specific ones (normally nothing), and if applicable, the USB interface (for ATMega32U4 based boards, like the Leonardo).
Only then does it go on to run your sketch.
If you want to use both your own main() and Arduino functions like delay() then you will have to call those initialization routines before running the rest of your code.

Could you explain the significance of "serialEventRun"?

If you haven't defined a serialEvent() function then it has no significance at all. If you have defined one then it runs it.

What is the purpose of initVariant()?

That is the bit where I say then board-specific ones (normally nothing)

I just rewrote my code to include just init() and nothing else, the serial communication, both read and write, is now working. So my question, is     USBDevice.attach()
necessary?

Only if you're on an ATMega32U4 or similar chip where the USB is a real USB connection, not a UART connection through a USB bridge chip.

Let us continue this discussion in chat.


text:
Connecting an Arduino to a servo with an external power supply
I have purchased an MG995 servo (4.8-7.2V operating voltage, 170MA no load operating current draw) and will power this using a 5V, 2A mains plug pack. Do I need a breadboard to connect this with my Arduino (which will itself be powered through its usb port)? Or is it possible to connect the servo with the Arduino directly?
If it's possible to connect it directly, which pins should I be using on the Arduino? Will it look something like this:

except the red wire (and black wire?) connects to the external power supply?
Any answers (or links to relevant tutorials which have all three of these components) would be welcome. Thanks!

Don't  pull the power for the servo through the Arduino.  They need to be powered in parallel or from separate supplies.  What you have drawn can burn up your Arduino.

Be sure to connect the grounds.

are you asking how a breadboard works?

Potentially - I haven't purchased a breadboard so if it's possible to connect the servo (powered externally by the plug pack) and the Arduino (powered by a USB cable) together without one that would be better. if possible ;D

From what I know, and what is said here, you connect the negative terminal of the power source to arduino ground, as well as the ground of the servo. Because both the power source, and the signal have to travel as 2 independent circuits.

Your question is not very concise, but I'll try to hit the main points.
I'm going with the assumption that your "Arduino" is the Sparkfun Redboard. The Redboard has a current limit of <800mA (heat management on the Redboard probably lowers this number even more), as per the LM1117 voltage regulator listed in the provided RedBoard schematic, and a minimum input voltage of 7V. You won't be able to power your Arduino with the 5V2A powerbrick. If you are powering the RedBoard through the standard USB, then it will typically be limited to 500mA.
Are you sure your servo has a no-load draw of 170mA? That's really high for a servo. If it does, then I'm assuming it's a large servo that likely has a high stall current draw, so 800mA from the Redboard's on-board regulator won't cut it, nor a USB port.
To power your servo externally, wire the servo and Redboard according to the schematic below. The power supply is indicative of your 5V 2A "wall wart". It's important to note that you need to connect the ground of the the power supply to the ground of the Arduino. For controlling the servo, check out Adafruit's servo tutorial. You will also need to provide power to your Arduino via USB or a DC barrel jack with a power brick that outputs >= 7v.

Would you please explain why it is necessary to connect the power supply ground to the arduino ground? Thank you.

If you don't have the ground connected to the Arduino, there is no return path for current meaning your signal wire is useless. Also, in order to measure voltage you need a reference point. If you have no ground or reference, it has no idea what the voltage you are supplying it with is, or high that voltage point is with respect to ground is. So you tie both grounds so they both have the same reference point and to provide a return path of current for your control wire (granted it's an insanely tiny amount, nevertheless still must be there)

I always thought that "ground" is "ground", so Arduino has its grounds connected to its own power supply, that whats confuses-me. Thanks

You did not indicate how you plan to connect the 5V, 2A mains plug pack to the Arduino board. If you want to use the barrel jack on the left, please note the listed input voltage. 5 volts is too low if you plan on powering the Uno board with the external power source. There is a voltage comparator circuit that will switch over to the barrel jack power if the voltage is high enough.
But since you are not really asking about powering the Uno, just the servo, then it gets interesting. The Sparkfun schematic shows a diode in line with the barrel connector and the Vin connection point on the board. This could provide a power path for the servo. The problem is that the servo voltage range 4.8 volts on the low end. With a 5 volt output of your external power supply, a voltage drop from the diode would give the servo almost enough voltage to meet the 4.8 volt minimum but not quite.
You are better off to not connect the servo power through the Uno board. If you had a somewhat higher voltage supply, at least 6 volts, then it would be ok. But if it is only 5 volts then it really is at a very marginal level.

Hey, thanks so much for answering.I'm all pretty new at this so if I clarify what I meant I'm not sure if that will actually help (let me know!).So I want to power the Arduino board using a USB cable (from a laptop to the Arduino's usb jack). The servo I am using draws too high a current to power it using the 5V pin on the Arduino,so I have been advised to buy a plug pack (the 5V, 2A one),strip the end of the cable and connect it's wires to the servo (in order to power the servo separately from an external source)
Basically my question is how do I connect the servo to the Arduino? Which pins?

You need to make sure what is the positive wire and what is the negative wire. You then connect the negative wire of the power supply to the Black wire of the servo above. The positive of the power supply connects to the Red wire. The Yellow and Black wire also connect to the Uno board as you show above.


text:
ADC noise when sharing ground from external supplies
i have resistor based sensor, when i test it using arduino connect to PC using serial monitor  without sharing ground to other circuit it has a nice value between 300-650 in adc range and the error/ accuracy reading just have about 5 value (ex: 607-612) if there is no condition change in the sensor.
But the problem comes when i sharing the ground to the other circuit. The accuracy is messed up bigger than 60 adc value (570-660) with the same condition without sharing ground.
My circuit is powered by PSU 24V and 24V driver to produce input signal for electric pressure regulator. The arduino ground is sharing because to control the input of the 24V driver. Here my circuit in the attachment.
So there is two ground from PC (i need it to use serial monitor) and the PSU 24V
How to eliminate the noise? Is there any way to control the 24v driver and read the sensor at the same time without sharing ground? Maybe using two controller with master/slave? Or there is any advice?

You could use an opto-coupler between the arduino and driver. Then you don't need to have a common ground. I'd also try putting a 1-10kOhm resistor between the arduino output and driver input.

What you have shown in the schematic is insufficient in determining your problem and a possible fix. What needs to be seen is exactly where are the wires are run to and from. The exact routing of the wires. And a schematic does not show that.

Can you tell me what Arduino board you are using? Uno, Nano, etc. And what sensor.

I had the same problem with communication between a Rasberry Pi and an Arduino Mega.  Ultimately I solved the problem by powering the Pi from the Mega.  You may need to separate the power and communication lines to the PC.

Thanks @Gerben i solved my problem by using an optocoupler. Before My arduino UNO PWM output go through PWM driver, I separate this line using Optocoupler so the ground from power supply doesn't contact to my controller that preventing from ground loop.

You've created what's known as a "Ground Loop".  You have 2 grounds in your circuit, your 24v PS has a ground and the PC supplying 5V to your Arduino has a ground.  They are not likely to be equivalent and will cause many unwanted side effects.
You can reduce some noise using RC or RLC circuits on your power supply pins.  It's probably best to use only a single power supply (and ground).

"You can reduce some noise using RC or RLC circuits on your power supply pins." How will this eliminate the ground loop?


text:
NodeMCU: Wiegand not working for one device, while working for another
I'm using a NodeMCU, and a working code for reading Wiegand data, with this library.
I managed to successfully read the Wiegand signal from this device.
However, I also have this new AR-721H device, and I can't get the Wiegand to work. This is the manual for the device.
There is absolutely nothing coming to the mcu. Everything is wired identically as the working device.
According to the manual, everything should be working, but I am at a loss.
Can someone please tell me what I might be doing wrong?
The store clerk told me something about needing a controller that converts RS485 to RS232, but I have no idea what that means. I already made it work with another device...

It's quite cryptic from the little information in that (somewhat chaotic) "manual", but I interpret it that the Wiegand interface is an input port, not an output port.  It is intended to connect that port to an external card reader or keypad as a remote interface (typically the other side of the door to this unit).
For communication with your Arduino you should use the RS-485 interface. For that you need an MAX485 breakout board.

I suspect that the store clerk was talking about using RxTx for the data transmission, available in this device. He said all the programmers bought a controller to convert the signal, and I think he doesn't know what he's talking about, since the device I bought uses Wiegand, as an input at that as you said. I didn't understand your last sentence about MAX485 tho...

RS485 is a specific electrical signalling format for UART (serial) data. You need to convert that to UART using a MAX485 - then you can feed it in to the TX/RX pins (or other pins using SoftwareSerial) and communicate using Serial. You'd need to know the baud rate and protocol though to make sense of the data.

Thank you for the elaboration. In other words, the clerk is clueless... As the device I bought doesn't even have the option to use UART.

@Ivan Yes it does (or should have) - P3 is the RS-485 port.

@Ivan I can tell you that it should be running at 9600 baud - but what the data content will be I haven't managed to discern.

@Ivan Pay Dirt! https://kupdf.net/download/721-727h-protocol-en_5bfba826e2b6f5d51b0dabd5_pdf

Ok, so we've established that I am the stupid one. No problem. So the NodeMCU has RxTx pins (RS232), but that won't work with the RS485 directly (which I failed to see, thanks for that) i.e. I'd need a hardware converter as he said. Correct? Can I do this with software?

You need a MAX485 breakout board.  AR-721H <-> MAX485 <-> ESP8266. https://en.wikipedia.org/wiki/RS-485

I see... Thanks for the elaboration. I am really stupid with this stuff, and I am trying to learn. Can you please tell me what the MAX485 board does? Does it just do the conversion? I can't figure it out from Googling.

You're not stupid - you just don't have this area of knowledge yet. In one mode the MAX485 chip takes normal UART data in one side and spits out the RS485 equivalent from the other. In the other mode it receives RS485 data in one side and spits out UART data out the other. You switch modes with the DE and RI pins (which you can connect to the same GPIO pin of the ESP8266).  It's basically a transparent bridge between UART and RS485 that runs in the direction you specify. In TX mode you can Serial.write(...) data. In RX mode you can Serial.read() data.

@Ivan Actually since you're working at 3.3V you need the MAX3485 since it's the 3.3V version.

@Ivan I'm trying to update my answer with a diagram for you, but the schematic editor is being a complete arse.

I could also use a level converter with the MAX485, instead of the MAX3485, correct?

@Ivan Sure, but that gets messy then.

Yeah, a lot of wiring. I am so frustrated that I can't find a simple RFID reader with a keypad... It's either devices without keypads working with Wiegand, or the ones with Wiegand having all sorts of weird workarounds... Why is the access control area so complicated?

@Ivan https://www.supremainc.com/en/hardware/compact-outdoor-rfid-reader-xpass-d2.asp

Can you please tell me why you are specifically recommending these?

It's one I just happen to be aware of. I should have one coming some time for a job I am working on at the moment. I'll know more about working with them when the customer finally sends me one.


text:
Atmega328pb type casting errors
I've created a custom pcb with a Atmega328pb cpu.
It's said to be binary compatible with Atmega32p, thus i flash it with my already functioning sketches that i've developed using an arduino.
The thing is that i have a double that i try to cast to int and when i do, it crashes the processor.
The code works perfectly fine on 328p so i'm wondering whether it could be a compiler issue, hardware issue, fuse settings issue.
double globalDouble = 0.0;

void arne() {
  int stuff = globalDouble;
  // program execution halted…
}

The board manager does not include 328pb bit but https://www.pololu.com/ has board config for it, so has http://github.com/watterott/ATmega328PB-Testing, but they make no difference. Still halts.
Any clues on how to move forward? I could ask the factory to replace it with a 328p but i'de rather have my already made products work.
Thank you!

How do you know it halts because of it? Have you tried to compare assembly for both MCU's? Does it even use the same version of compiler? Maybe it's just a compiler bug.

try with AVR boards package 1.6.21


text:
Logging PAR with quantum sensor and Arduino
I want to link a PAR quantum sensor (either Licor or Skye Instruments) to Arduino to log PAR, in order to measure light in a forest.
I have an Arduino Uno + data logging shield (with RTC, SD card and ADS1115) and have connected the PAR sensor via A0 to measure differential voltage (A0 –– S+ | S- –– GND | A1 –– GND). Code as follows:
  ads.setGain(GAIN_TWOTHIRDS);
  adc0 = ads.readADC_Differential_0_1();
  Voltage = (adc0 * 6.144)/pow(2, 15);
  Voltage = Voltage*1000; // conversion to millivolts

When I wire the Arduino to itself to measure a differential voltage (A0 –– 3V and A1 –– GND), it measures beautifully.
Furthermore, when I use a voltmeter to test the Voltage across the + - wires from the sensor, I get sensible readings.
Put the two together – nonsense. I get noisy V readings that don't make sense. When I cover the sensor my V is actually going up, not down as it should! I have tried changing the GAIN, but unfortunately this makes no difference to the problem.
I have been looking at PARduino for help/inspiration, but they include an amplifier in their setup, which is expensive and I'm not sure is necessary / would solve my problem.
Very new to Arduino. Any and all advice would be very much appreciated.

Could you connect the sensor to the Arduino and, at the same time, to the voltmeter? Do you still get sensible readings from the voltmeter if you do so?

Please provide a link to the datasheet of the used sensor. I'm not sure, if you can simply omit the amplifier

Thanks for your comments Edgar and chris. The problem must have been arising from a faulty board or some such.
In the end, I was able to wire up the sensor as described above, using a more fleshed-out version of the code. No amplifier necessary, you can just adjust the GAIN.
I then ran my Arduino sensor alongside a Skye Instruments SpectroSense 2+ to 'calibrate' it. Plotting the Arduino voltages against the SpectroSense PAR values gave quite a nice fit!
Apologies for the long delay in replying – was on fieldwork.


text:
Problem with sending sound sensor data to app using ESP32 over BLE_UART
I was working on Adafruit Electret Microphone Amplifier - MAX4466 with Adjustable Gain
and ESP32.
I want to send data to an app using BLE UART
I have printed data to the serial monitor or serial Plotter using the following example  code
/*
    Video: https://www.youtube.com/watch?v=oCMOYS71NIU
    Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp
    Ported to Arduino ESP32 by Evandro Copercini

   Create a BLE server that, once we receive a connection, will send periodic notifications.
   The service advertises itself as: 6E400001-B5A3-F393-E0A9-E50E24DCCA9E
   Has a characteristic of: 6E400002-B5A3-F393-E0A9-E50E24DCCA9E - used for receiving data with "WRITE"
   Has a characteristic of: 6E400003-B5A3-F393-E0A9-E50E24DCCA9E - used to send data with  "NOTIFY"

   The design of creating the BLE server is:
   1. Create a BLE Server
   2. Create a BLE Service
   3. Create a BLE Characteristic on the Service
   4. Create a BLE Descriptor on the characteristic
   5. Start the service.
   6. Start advertising.

   In this example rxValue is the data received (only accessible inside that function).
   And txValue is the data to be sent, in this example just a byte incremented every second.
*/
#include <BLEDevice.h>
#include <BLEServer.h>
#include <BLEUtils.h>
#include <BLE2902.h>
float AnalogValue;
BLEServer *pServer = NULL;
BLECharacteristic * pTxCharacteristic;
BLECharacteristic * pTEMPCharacteristic;
bool deviceConnected = false;
bool oldDeviceConnected = false;
uint16_t  txValue;
uint16_t  TEMPValue;

static String Received_Char;

// See the following for generating UUIDs:
// https://www.uuidgenerator.net/

#define SERVICE_UUID           "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID
#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
#define CHARACTERISTIC_UUID_TEMP "6E400004-B5A3-F393-E0A9-E50E24DCCA9E"

class MyServerCallbacks: public BLEServerCallbacks {
    void onConnect(BLEServer* pServer) {
      deviceConnected = true;
    };

    void onDisconnect(BLEServer* pServer) {
      deviceConnected = false;
    }
};

class MyCallbacks: public BLECharacteristicCallbacks {
    void onWrite(BLECharacteristic *pCharacteristic) {
      std::string rxValue = pCharacteristic->getValue();

      if (rxValue.length() > 0) {
        Serial.println("*********");
        Serial.print("Received Value: ");
        for (int i = 0; i < rxValue.length(); i++)
        {
          Serial.print(rxValue[i]);
          Received_Char=rxValue[i];
        }
        Serial.println();
        Serial.println("*********");

      }
      Serial.println(Received_Char);
    }
};

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

  // Create the BLE Device
  BLEDevice::init("Lungs Monitoring");

  // Create the BLE Server
  pServer = BLEDevice::createServer();
  pServer->setCallbacks(new MyServerCallbacks());

  // Create the BLE Service
  BLEService *pService = pServer->createService(SERVICE_UUID);

  // Create a BLE Characteristic
  pTxCharacteristic = pService->createCharacteristic(
                        CHARACTERISTIC_UUID_TX,
                        BLECharacteristic::PROPERTY_NOTIFY
                      );

  pTxCharacteristic->addDescriptor(new BLE2902());

    pTEMPCharacteristic = pService->createCharacteristic(
                        CHARACTERISTIC_UUID_TEMP,
                        BLECharacteristic::PROPERTY_NOTIFY
                      );

  pTEMPCharacteristic->addDescriptor(new BLE2902());

  BLECharacteristic * pRxCharacteristic = pService->createCharacteristic(
      CHARACTERISTIC_UUID_RX,
      BLECharacteristic::PROPERTY_WRITE
                                          );

  pRxCharacteristic->setCallbacks(new MyCallbacks());

  // Start the service
  pService->start();

  // Start advertising
  pServer->getAdvertising()->start();
  Serial.println("Waiting a client connection to notify...");
}

void loop() {

  if (deviceConnected) {
    if(Received_Char=="S"){
    txValue = analogRead(A0);//=AnalogValue.toInt();
    pTxCharacteristic->setValue(txValue);
    pTxCharacteristic->notify();
    //txValue++;
    Serial.println(txValue);
    delay(10); // bluetooth stack will go into congestion, if too many packets are sent
  }
  else if(Received_Char=="T");
  }
  // disconnecting
  if (!deviceConnected && oldDeviceConnected) {
    delay(500); // give the bluetooth stack the chance to get things ready
    pServer->startAdvertising(); // restart advertising
    Serial.println("start advertising");
    oldDeviceConnected = deviceConnected;
  }
  // connecting
  if (deviceConnected && !oldDeviceConnected) {
    // do stuff here on connecting
    oldDeviceConnected = deviceConnected;
  }
}

But the data is transferring at a very high speed and the app is not able to get it properly.
Can anyone help me with how to take samples of the audio sensor and store them in a byte array and send it to the app?
Thank you in advance.


text:
Motor shield and Arduino Led not turning on when connected to laptop and Arduino is heating up
I have a problem like that....As I connect my Arduino to the laptop with the usb cable and the motor shield connected, my led won't turn on neither does the led on the Arduino. And the small chip like thingy beside the usb cable also heats up really bad...please help!

disconnect the motor shield

Is a motor connected?

Do you mean this component gets hot?

There's not much information to go on here. If nothing is lighting up at all there's a problem. Disconnect everything and see if the Arduino works at all.

0
You might have burned one of the onboard voltage regulators. In my case, it was AMS1117 which was burned and my Arduino was behaving similarly. You will notice that the Arduino will work with an external power supply connected to the Vin pin of Arduino and it will not become hot.

 In short, the small chip which is getting hot is a voltage regulator may be AMS1117 and you have to replace it manually or buy a new Arduino