text:
RFID-RC522 Can't read from MIFARE Ultralight
I tried many ways to get and print UID and other data from a MIFARE Ultralight, but it always ends with an error. I am using the RFID-RC522 reader with an Arduino UNO and thr MFRC522 Library.
I can normally get and print the PICC type of the chip, but that's the only thing that works.
This is how I have connected my RC522 reader:

(source: ytimg.com)
This is my code:
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN 9
#define SS_PIN 10

MFRC522 rfid(SS_PIN, RST_PIN);

unsigned long noSignal = 0;

bool lastState = true;
bool read = true;

void setup()
{
    pinMode(2, OUTPUT); //Red led
    pinMode(3, OUTPUT); //Green led

    Serial.begin(9600);
    SPI.begin();
    while (!Serial);

    rfid.PCD_Init();
    Serial.println("RFID ctecka byla uspesne spustena."); //Prints "RFID Reader succesfully started"
    Serial.println();

    changeLed(true);
}

void changeLed(bool red)
{
    digitalWrite(2, red);
    digitalWrite(3, !red);
}

void loop()
{
    if (millis() - noSignal >= 300)
    {
        changeLed(true);
        read = true;
    }

    bool state = !rfid.PICC_IsNewCardPresent() && !rfid.PICC_ReadCardSerial();

    if (state != lastState)
        if (state)
            noSignal = millis();
        else if (read)
        {
            read = false;

            changeLed(false);
            noSignal = millis();

            Serial.println("---------Cip detekovan----------"); //Prints "Chip detected"
            Serial.println();

            MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);

            Serial.print("Znacka cipu: ");//Prints chip type
            Serial.println(rfid.PICC_GetTypeName(piccType));

            rfid.PICC_DumpToSerial(&rfid.uid); //Here is the error

            Serial.println();
            Serial.println("---------Cteni skoncilo----------");//prints "Read ended"
            Serial.println();

            rfid.PICC_HaltA();
            rfid.PCD_StopCrypto1();
        }

    lastState = state;
}

Serial monitor snapshot:

Maybe an important thing is that when I call PCD_DumpVersionToSerial() I get:
Firmware Version: 0x12 = (unknown)

Somewere I read that my Arduino isn't compatibile with MIFARE Ultralight and I need MIFARE Classic cards. Is that true? Can I solve this problem by using another library or is it a hardware problem?
EDIT:
I asked my friend, who has an Arduino too from the same shop as me, if he can read MIFARE Ultralight cards. He said that it's working for him. So my problem will be probably on the hardware side. We both have unofficial Arduinos from AliExpress.

In the first lines of code there are two lines that say:
#define RST_PIN 9
#define SS_PIN 10

They define the RESET pin to be on the D9 pin and the SDA on the D10 pin.
So you have an connection error try connecting like shown and you should be good to go.

Sorry, I made mistake. I have connected pins like in your picture. I will update my question.

@DavidMoškoř have you tried the original example?

Yes, same result

Is it possible that my cards are using encryption DES3 that my arduino cannot decrypt?

@DavidMoškoř it is possible that your card use a different frequency.


text:
2 buttons, 1 servo, turn when pressed only
I have a code problem. I need to turn a servo clockwise or counter clockwise using 2 microswitches.
The problem is that my code is fine on startup, but when i press the button the servo continues to spin.
How do i make this so it only spins while the buttons are pressed and turn off when they are not pressed?
#include <Servo.h>

Servo myservo; // create servo object to control a servo

// CONSTANTS

// PINS
const int crServo = 12; // sets pin 12 as servo
const int buttonPinCW = 2; // sets pin 2 as button; CW => clockwise => FOCUS FAR
const int buttonPinCC = 3; // sets pin 3 as button; CC => counterclockwise => FOCUS NEAR

// SERVO PROPERTIES
const int crSpeedDefault = 0; // is the stay still position, motor should not turn
const int crSpeedCW = 110; // turns the motor full speed clockwise
const int crSpeedCC = 70; // turns the motor full speed counter-clockwise

// SET BUTTON STATES
int buttonStateCW = 0; //sets button 1 as off
int buttonStateCC = 0; // sets button 2 as off

void setup()
{
  myservo.attach(crServo); // attaches the servo on pin 12 to the servo object
  pinMode (crServo, OUTPUT);
  pinMode (buttonPinCW, INPUT); // sets button as input
  pinMode (buttonPinCC, INPUT); // sets button as input
  myservo.write(crSpeedDefault); // default servo to crSpeedDefault
}

void loop()
{
  crServo = digitalRead(crSpeedDefault);
  buttonStateCW = digitalRead(buttonPinCW);
  buttonStateCC = digitalRead(buttonPinCC);
  // clockwise rotation
  if (buttonStateCW == HIGH) {
    myservo.write(crSpeedCW);
    // counterclockwise rotation
  }
  if (buttonStateCC == HIGH) {
    myservo.write(crSpeedCC);
  }
}

Do you have an external pull-down on your buttons?

Hi Maximilian, Yes, i have a wheel which spins manually by a user. The idea is that when the steering wheel spins 180 degrees a microswitch is pushed. This turns the servo one direction, the opposite is to turn the servo in the opposite direction.

I meant a pull-down resistor. Your firmware logic is that if the button pin reads "HIGH" it is pressed. Thus you must have a button via pull-down to GND and other side to +5V connected right? Also: Why is the line crServo = digitalRead(crSpeedDefault); there? With const int crServo = 12 the variable cannot be changed. It doesn't make sense to re-write the servo pin to 0 or 1 using the result of digitalRead, which reads from pin 0 which is the Serial TX of the Arduino.

If you want the logic "if none of the two buttons are pressed, stop the servo immediately", then you'd express this in your loop as a if expression where you check if both buttons read LOW:
void loop()
{
  buttonStateCW = digitalRead(buttonPinCW);
  buttonStateCC = digitalRead(buttonPinCC);
  // clockwise rotation
  if (buttonStateCW == HIGH) {
    myservo.write(crSpeedCW);
    // counterclockwise rotation
  }
  if (buttonStateCC == HIGH) {
    myservo.write(crSpeedCC);
  }

  //Are both buttons not pressed?
  if(buttonStateCC == LOW && buttonStateCW == LOW) {
    //Stop the servo.
    myservo.write(0);
  }
}

This assumes your buttons are with pull-down resistors to GND on one side and with +5V on the other side, as detailed in the Arduino tutorial. In short this means that an unpressed button reads as 0 and a pressed on reads as 1 (HIGH). This is unusual because we usually use the internal pullup resistors via the INPUT_PULLUP pinMode parameter with a switched logic (1 = unpressed, 0 = pressed).
I've also removed the line crServo = digitalRead(crSpeedDefault); because that doesn't make sense in my opinion, as I've detailed in my comment.

thank you, Maximilian i think this must be in my switch wiring, the code edit you sent makes them spin continuously in either direction when the button is pressed. I think i need to have a look at quite how i wire these up to the Uno as something is a-miss here i think.

Please edit your question to show your circuit then.

sorry for the delay, ok the buttons go to GND and to the input pins 2 & 3 (there are 2 buttons 1 to 2 and 1 to 3)

then the servo comes off 12 and is also connected to GND and +5v

@Richard When you edit your question you will notice a "Schematic" tool button with which you can accurately present your circuit.

@Richard there was a copy-paste error in my answer in the if-statement which may have caused the fail. Retry please.

This solution is similar to @Maximilian Gerhardt's solution. So his comments on the pull-up/down resistors apply.
I assume that you only want to turn either CW or CC and not oscillate between the two.
Then you should cater for 4 button conditions:
None pressed, CW only press, CC only press, both pressed.
We only need to worry about the "only pressed" conditions and a default state when coding.
Here is my solution:
void loop()
{
  buttonStateCW = digitalRead(buttonPinCW);
  buttonStateCC = digitalRead(buttonPinCC);

  // CW button pressed only
  if (buttonStateCW == HIGH && buttonStateCC == LOW) {
    myservo.write(crSpeedCW); // clockwise rotation
  }
  // CC button pressed only
  else if (buttonStateCW == LOW && buttonStateCC == HIGH) {
    myservo.write(crSpeedCC); // counterclockwise rotation
  }
  // Default condition
  else {
    myservo.write(crSpeedDefault);
  }
}

source: Stack Exchange

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

sort: votes


text:
How do string pointers work in Arduino?
To the best of my understanding, when I declare
String s = "This is a string.";

what happens is that space is allocated on the stack for a pointer which points to some String object which internally contains a char array. My confusion stems from the fact that this pointer seems(I could be wrong) to behave differently than any other type of pointer. For example, if I write
int a = 1;
int* x = &a;
int* y = x;

what happens is that the pointer saved in y now points to the same location in memory as the pointer saved at x. So if I write
String s1 = "This is a string.";
String s2 = "Hello World!";
s1 = s2;

does the pointer saved at s1 now point to the same memory location as s2? Or does s1 copy the char array from s2 into its own separate memory? Further, If I write
String s1 = "This is a string.";
s1 = "Hello World!";

does s1 now point to whatever arbitrary memory location was created for the string literal "Hello World!"? Will this memory location be freed later, or is some sort of smart garbage collector in place which knows that I am using that memory in the heap? Finally, should I never assign a string declared on the stack to a global variable, as this will be referencing a memory location which will be freed soon?
Thank you in advance for your help!

I suggest you study https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/WString.cpp#L214. The expression s1 = s2 will invoke the overloaded assignment operator, which will, depending on the used C++ version, execute a move() or a copy. Expressions of the form s1  = "Some String value"; will result in a copy (see operator = (const char *cstr)). Also see https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/

String is not a simple type like an int or a char. It is a class with many member functions and, more importantly, operators.  When you create the object it allocates room for that object either on the stack (for a local variable) or in the global data area if it's a global variable. However that object doesn't contain the memory used to store the actual string data - it only has a pointer. The memory for the string data is allocated on the heap using malloc() and realloc().
Assigning string data to the String object is done through the = operator defined in the class, of which there are a number of overloaded varieties:
String & String::operator = (const String &rhs)
{
    if (this == &rhs) return *this;

    if (rhs.buffer) copy(rhs.buffer, rhs.len);
    else invalidate();

    return *this;
}

#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
String & String::operator = (String &&rval)
{
    if (this != &rval) move(rval);
    return *this;
}

String & String::operator = (StringSumHelper &&rval)
{
    if (this != &rval) move(rval);
    return *this;
}
#endif

String & String::operator = (const char *cstr)
{
    if (cstr) copy(cstr, strlen(cstr));
    else invalidate();

    return *this;
}

String & String::operator = (const __FlashStringHelper *pstr)
{
    if (pstr) copy(pstr, strlen_P((PGM_P)pstr));
    else invalidate();

    return *this;
}

They all, ultimately, call the copy() or move() functions which copy the data from the source into the memory allocated on the heap (increasing the allocation if needed).
Using:
String s1 = "Foo";
String s2 = s1;

s1 has memory allocated on the heap, then Foo\0 copied into it.  s2 then also has memory allocated on the heap, and the data from s1 is copied into it. So you have two separate objects with separate memory allocated for their content.  So then doing:
s2 += "bar";

you end up with:
s1: "Foo\0"
s2: "Foobar\0"

Since it's an object that's allocated on the stack (or in global space) and not a pointer to the object you can get a pointer to it like with an int:
String s1 = "Foo";
String *s2 = &s1;
(*s2) += "bar";

Which gives you just one object and one memory space, but two names for it, and the result is:
s1: "Foobar\0"
s2: "Foobar\0"

This is why it's important to use either pointers or references when passing String objects as parameters to functions, and the constant allocation and reallocation on the heap why String objects are frowned upon in microcontrollers with very limited RAM.

important to use either pointers or references when passing String objects as parameters to functions.
Updating this great explanation with couple examples of how to/not pass strings to func would be very helpful!

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


text:
Error to make a request using Arduino Uno and ESP8266
I'm using Arduino Uno and ESP8266 in a project.
I'm using AT Commands to connect to wi-fi and make a request. I'm using the monitor serial to test the code before compile it in arduino.
It is connecting to wi-fi and I can make a request to a server in my network but when i try to make a request to my web-service in cloud it doesn't work well.
The return is an HTML with an 404 page instead of what I am expecting:

Hello Versa

Here is my code:
AT+CIPSTART="TCP","ternary.com.br",80
AT+CIPSEND=18
GET /webservice/

Can someone help me telling me what I am doing wrong?

After see the answer of Maximilian Gerhardt, I solved it writing the following sequence in the monitor serialize:
AT+CIPSTART="TCP","ternary.com.br",80
AT+CIPSEND=70
GET /webservice/ HTTP/1.1
Host: ternary.com.br
Connection: Close
[Just press enter and send a new line]

what does the response code 404 mean?

An html page with saying "page not found"

A HTTP requests is comprised of more than just GET /webservice/. Take a look at what curl (console-line HTTP client) does.
C:\>curl -v "http://ternary.com.br/webservice/"
*   Trying 187.84.237.200...
* Connected to ternary.com.br (187.84.237.200) port 80 (#0)
> GET /webservice/ HTTP/1.1
> Host: ternary.com.br
> User-Agent: curl/7.46.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Fri, 11 May 2018 15:04:16 GMT
< Server: Apache
< X-Powered-By: PHP/5.6.30
< Vary: Accept-Encoding
< Cache-Control: max-age=0, no-cache, no-store, must-revalidate
< Expires: Wed, 11 Jan 1984 05:00:00 GMT
< X-UA-Compatible: IE=Edge,chrome=1
< Pragma: no-cache
< Transfer-Encoding: chunked
< Content-Type: text/html; charset=UTF-8
<

Hello Versa
* Connection #0 to host ternary.com.br left intact

You will have to at least transfer the minimal correct HTTP Headers of the form
GET /webservice/ HTTP/1.1
Host: ternary.com.br
Connection: Close

To get an answer. Also mind the ending \r\n\r\n. Refer to this website for more headers.
When I only send GET /webservice/ I also get 404 page.
C:\>cat test
GET /webservice/

C:\>cat test | ncat ternary.com.br 80
[...]
        <title data-i18n="[html]404_page.title">404 ÔÇô P├ígina n├úo encontrada</title>

Thank you so much! I solved it using these headers with HTTP/1.1


text:
How to read main code inside main code in Arduino?
How can I read the hex code of the main programme stored inside flash memory inside my running Arduino programme?
So far I am able to read the Flash at any given address by using PROGMEM
unsigned int displayInt;
int k;    // counter variable

void setup() {
  Serial.begin(9600);
  while (!Serial);  // wait for serial port to connect. Needed for native USB

  for(k = 0; k < 5; k++) {
    displayInt = pgm_read_word_near(k);
    Serial.println(displayInt);
  }
}

void loop() {
}

The output is
37900
13716
53
3072
37900

But this not hex code.
I am implementing the OTA (over the air) feature. I will get the new version of a code from GPRS. It will be huge code so I will write it to flash by using the custom bootloader mentioned in this thread. I am able to write to the flash memory. Now I would like to read the data from flash. To begin with I would like to read the main programme inside my main programme.

Interesting. If you want hex you have to tell it to print in hex. If I change your display line to:
Serial.println(displayInt, HEX);

Then I get:
940C
3594
35
C00
940C

Compare this to what the decompiled file looks like:
   0:   0c 94 35 00     jmp 0x6a    ; 0x6a <__ctors_end>
   4:   0c 94 5d 00     jmp 0xba    ; 0xba <__bad_interrupt>
   8:   0c 94 5d 00     jmp 0xba    ; 0xba <__bad_interrupt>

If you take the endianness into account (you are reading words, not bytes) then it is the same.

If you change it to read bytes it looks better:
void setup() {
  Serial.begin(115200);
  while (!Serial);  // wait for serial port to connect. Needed for native USB

  for(int k = 0; k < 12; k++) {
    byte c = pgm_read_byte(k);
    char buf [3];
    sprintf (buf, "%02X", c);
    Serial.println(buf);
  }
}

void loop() {
}

I increased the baud rate to 115200. I'm always puzzled when people use 9600 baud. Do you hanker for the olden days, when 9600 baud modems were the fastest you could get?
That gives this result:
0C
94
35
00
0C
94
5D
00
0C
94
5D
00

As you can see, it is exactly correct.

Thanks. I am a frontend web developer trying to learn all of it(firmware development) at once. I don't know C very well. Thanks


text:
Arduino ESP8266 - wifi evt: 3 and wifi evt: 7 meaning?
I'm getting these in my serial port, but what does wifi evt 3 and 7 mean?
I am trying to complete this tutorial. https://youtu.be/4Z0gBG8dkqw
The PHP file is on my hosting, and the ESP reads out the temperature and humidity from the sensor so that's fine.
The serial code:
Connecting
wifi evt: 3
Connected
Temperature:
24.10
Humidity:
39.70
[hostByName] request IP for: lucasdebelder.be
[hostByName] Host: lucasdebelder.be IP: 185.182.57.81
connected
HTTP/1.1 200 OK
Date: Fri, 11 May 2018 13:14:17 GMT
Server: Apache/2
Upgrade: h2,h2c
Connection: Upgrade, close
Vary: User-Agent
Content-Length: 0
Content-Type: text/html; charset=UTF-8

�
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7
wifi evt: 7

The code that I am running in Arduino.

#include <ESP8266WiFi.h>
#include "DHT.h"

const char* ssid     = "bbox2";      // SSID of local network
const char* password = "azerty";   // Password on network

WiFiClient client;
char servername[]="lucasdebelder.be";  // remote server we will connect to
String result;

float temperature;
float humidity;

#define DHTPIN 14

#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  dht.begin();
  delay(2000);
  Serial.begin(115200);
  Serial.println("Connecting");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
  }
  Serial.println("Connected");
  delay(1000);
  readSensor();
  String temperatureString = String(temperature,1);
  String humidityString = String(humidity,1);
  sendDataToServer(temperatureString,humidityString);
}

void loop() {

}

void sendDataToServer(String temperature, String humidity)
{
  if (client.connect(servername, 80)) {  //starts client connection, checks for connection
    Serial.println("connected");
    client.println("GET /send_email.php?temperature="+temperature+"&humidity="+humidity+" HTTP/1.1"); //Send data
    client.println("Host: lucasdebelder.be");
    client.println("Connection: close");  //close 1.1 persistent connection
    client.println(); //end of get request
  }
  else {
    Serial.println("connection failed"); //error message if no client connect
    Serial.println();
  }

 while(client.connected() && !client.available()) delay(1); //waits for data
  while (client.connected() || client.available()) { //connected or data available
    char c = client.read(); //gets byte from ethernet buffer
      result = result+c;
    }

  client.stop(); //stop client
  Serial.println(result);

}

void readSensor()
{

  humidity = dht.readHumidity();
  temperature = dht.readTemperature();
  Serial.println("Temperature:");
  Serial.println(temperature);
  Serial.println("Humidity:");
  Serial.println(humidity);

}

The codes are explained in this forum thread. The wifi event types are  described here (and also duplicated here, which are ultimately coming from the Espressif Non-RTOS SDK, chapter 6.2.4):
typedef enum WiFiEvent
{
    WIFI_EVENT_STAMODE_CONNECTED = 0,
    WIFI_EVENT_STAMODE_DISCONNECTED,
    WIFI_EVENT_STAMODE_AUTHMODE_CHANGE,
    WIFI_EVENT_STAMODE_GOT_IP,
    WIFI_EVENT_STAMODE_DHCP_TIMEOUT,
    WIFI_EVENT_SOFTAPMODE_STACONNECTED,
    WIFI_EVENT_SOFTAPMODE_STADISCONNECTED,
    WIFI_EVENT_SOFTAPMODE_PROBEREQRECVED,
    WIFI_EVENT_MAX,
    WIFI_EVENT_ANY = WIFI_EVENT_MAX,
    WIFI_EVENT_MODE_CHANGE
} WiFiEvent_t;

The enum's values are increasing downwards, meaning that 7 is WIFI_EVENT_SOFTAPMODE_PROBEREQRECVED. Receiving a probe request means that some other device has scanned the surrounding WiFi networks and your ESP answered. This indicates that your ESP is in the Software Access Point (AP) + Station (SoftAP + STA) mode. But you only want to be a station in your own WiFi network, not an access point yourself.
The output is triggered by this function.
This comment on an issue suggests that you add WiFi.mode(WIFI_STA); to your setup, like
void setup() {
  WiFi.mode(WIFI_STA);
  dht.begin();
  delay(2000);
  Serial.begin(115200);
  Serial.println("Connecting");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
  }
  Serial.println("Connected");
  delay(1000);
  readSensor();
  String temperatureString = String(temperature,1);
  String humidityString = String(humidity,1);
  sendDataToServer(temperatureString,humidityString);
}

Subsequently, a WiFi event 3 indicates WIFI_EVENT_STAMODE_GOT_IP. Which also makes sense because you're telling the module to connect to the WiFi, it acquires an IP over DHCP and is then fully connected. This message is harmless since it doesn't indicate an error.
You should investigate on why these debug messages are thrown in the first place. The messages are only printed if two macros are set: DEBUG_ESP_WIFI and DEBUG_ESP_PORT (see here). So something must do #define DEBUG_ESP_WIFI and #define DEBUG_ESP_PORT Serial somewhere.
This is either done in some compiler settings which you are not aware of or because you modified a header file to include this change. Either way, you can try to use the #undef pre-processor macro to remove these definitions again before including the library. Change your first line to the following:
//Try to kill the DEBUG defines
#undef DEBUG_ESP_WIFI
#undef DEBUG_ESP_PORT
#undef DEBUG_WIFI
#include <ESP8266WiFi.h>

Thanks a lot for the answer. On the second line I still get a wifi evt :3  ->Connecting
wifi evt: 3
Connected. Same as in the post I made (check the third line)

@Panic I've addressed this in an edit of my answer.

from core package 2.4.1 the debug defines can be turned on in Tools menu

@MaximilianGerhardt, SDK is the primary source of the enum

You see the "wifi" debug messages because you set in Tools menu Debug Level "WiFi". SetDebug Level "None"


text:
Arduino Mega Pins for SoftwareSerial (vs. AltSoftSerial)
I am currently looking at using an Arduino Mega to build a MIDI Receive box that will then pump the data over USB, but am having design issues/uncertainties with the Arduino's receiving end.
I am looking to having (hopefully) 16 MIDI (as 5-pin DINs) inputs on this build, with no outputs other than the USB. The Mega has the 4 Rx pins, which still leaves me with 12 to create in software. From what I've read it appears that SoftwareSerial will not support simultaneous reads from different inputs, while AlftSofSerial does. However, it also appears (at least from what I've gathered) that AltSoftSerial is not supported on as many pins as I would need to make this work.
With my setup up, not all 16 MIDI devices would be sending data into the Arduino at once, but only 2 - 4; these would be operating at the same time though (i.e. a Keyboard note along with a volume fader), so I don't believe SoftwareSerial would work well for what I need.
Is it possible to work out what I need with SoftwareSerial/AltSoftSerial and the physical UARTs? If there's any necessary info that seems to be missing or I seem to be misunderstanding something, please let me know. Thanks!

It seems altsoftserial only supports one instance. Do you only need RX for MIDI? What baudrate?

For such a specialized application, you probably cannot rely on a library and have to program the hardware directly.

@Gerben I do only need it for MIDI. I was using 9600 in my hardware "tests" with only one device and it seemed to be working fine.

@CL I'll have to look up how to do this. Any helpful links to point me in the right direction?

AVR304 might be a start. But you need enough knowledge and experience to write your own AltSoftSerial library and to improve on that.

From what I've read it appears that SoftwareSerial will not support simultaneous reads from different inputs

Correct. You can only listen() on one instance at a time.
AltSoftSerial can only support 1 instance, but allows simultaneous transmit and receive, and doesn't block the whole system while either transmitting or receiving.
So the best you can hope for is 4 hardware UART and one AltSoftSerial for 5 ports.
I would suggest looking into the possibility of using multiple Arduino Mega boards with 4 ports on each (4 boards would give 16 ports in total) and have them communicate with each other through some other protocol (SPI or I2C for instance).

I had initially considered a setup similar to this, but had shrugged it off in an attempt to cut down costs, but looks like that may be the route to travel. Do you happen to know if there is another device with more UARTs? I was looking at the newest version of the Teensy, but it still only has 6.


text:
Arduino IDE loses programmer after installing Visual Micro
I had this added to programmers.txt
mysmartusb.name=mySmartUSB light
mysmartusb.communication=serial
mysmartusb.protocol=stk500v2
mysmartusb.program.protocol=stk500v2
mysmartusb.program.tool=avrdude
mysmartusb.program.extra_params=-P{serial.port}

And was getting so annoyed with the loading time of Arduino IDE 1.8.5 so I tried Visual Micro but that didn't go well either. Now, Arduino IDE can no longer see my programmer. Tried rebooting, did a search for all programmer.txt files on the C: and deleted/updated as I thought appropriate. Has anyone else ever had that issue and if so, how did they solve it?

Uninstalled and installed 1.9.0 as I heard that fixes the launch time (it does). I'm aware it's beta but it fixed my issue. I assume reinstalling 1.8.5 would've also gotten me my programmer back.


text:
Powering USB cable that powers Arduino with regulated 5V
I am having an issue with external loads causing the computer I have my Arduino connected to to momentarily drop out, which causes the Arduino to lose USB power momentarily and the port drops out and won't reconnect unless I physically remove and reconnect the USB cable. Since I need the USB connected in order to send and receive serial data to/from the Arduino, I was wondering if I could physically open the USB cable, cut the 5V line, and supply it via and external regulated 5V supply. I wouldn't cut the ground wire, but would tie it to the external 5V supply. I have read conflicting information on this (something about handshaking) but was wondering if that applied to Arduino's specifically.

You probably could, but why not just get a powered USB hub?

A powered hub would be a more proper solution USB-wise.  However it may be that whatever is causing "dropouts" would break the USB session as well.  You might need to switch to using an actual serial connection (if still logic-level) and use a different serial port on the computer.  Another thing to look at would be galvanic isolators for USB or serial.  It really all depends on the cause and nature of the "dropouts".  If these are being cause by other USB peripherals try putting them on their own powered hub, ideally connected to a different port or internal hub on the PC.

The dropouts are being caused by external loads being powered on and off. The loads have pretty high starting current, which is causing power for the whole computer to fluctuate. I've tried using a UPS but the problem still persists. I'll try getting a powered hub and see if that helps.

USB devices are only slaves. They cannot do anything without the host. When the power of your computer drops, it seems to close the usb sessions. So this is most likely not a problem with the Arduinos USB, but with your computer. It has to reestablish the connections after a voltage drop. Using a powered USB hub will only ensure, that the Arduinos power isn't cut of, but it will not ensure, that the computer reestablishes the connection, that you need for data transer.

I solved this problem by using a laptop instead. It is immune to these power fluctuations

I solved this problem by using a laptop instead. It is immune to these power fluctuations

If you are drawing more than 500mA from your PC then that is why it is happening.
I suggest, rather than butchering a cable, you get yourself a "wallwart" (Mobile phone charger) and use that to power the board.  You really should work out how much current you are pulling before deciding on what PSU to use.
A problem with wall warts is earthing, you need to make sure that your PC and wall wart are connected to the same earth connection, so that they share a common ground.
If the current being drawn us only for a very short time then it might be possible to provide additional power using a capacitor in the power line.  But plugging a charger in is much easier.


text:
ESP8266 with Arduino Uno and HTTP POST
Im currently new on this and sucessfully made a sound-activated alarm with Arduino Uno and a microphone sensor. (If sound is detected, then it will alarm). Now, I am adding a ESP 8266 module into it so it can perform a HTTP GET or POST to IFTT Maker link.
My problem with it is how can I program the esp with arduino uno? Do I do something like this

https://github.com/bportaluri/WiFiEsp/blob/master/examples/WebClient/WebClient.ino

(and add the threshold for the microphone sensor, buzzers and LEDs)??
Thanks for helping

That would work if your ESP8266 had the AT+ firmware flashed onto it by default. What exact module do you have? If you have a NodeMCU board you might as well work on the ESP8266 directly for everything

Im using the small one with 8 pins (esp-01). Thanks

Yes, the library

https://github.com/bportaluri/WiFiEsp

Is suited for your task because it implements talking to a ESP8266 over a software serial. On this serial connection, AT+ commands will be sent. This also means that you must have the AT firmware flashed onto your ESP-01.
If that is not the case you can download the binary image here and flash it with a serial adapter, as instructed with the tools on that page. You can check whether your ESP8266 has the firmware flashed by attach a UART adpater to the TX output. It should print a "ready" on bootup.
For your wire-up, you will just have to add VCC (+3.3V), GND, TX and RX connections to the ESP-01 board, preferable with a big capacitor between VCC and GND, as the ESP8266 draws a lot of power when sending data over WiFi.

Is it ok if i use something like this to connect so can use 5V instead? link

@HenrikhA. The ESP8266 is a 3.3V device, if you supply it with 5V it dies. It should also not receive a 5V signal. You will need a level shifter from the Arduino TX line to the ESP's RX line with a voltage divider. See http://www.martyncurrey.com/arduino-to-esp8266-serial-commincation/

@HenrikhA. Ah, I didn't see the link at the end. Yes, the adapter has a voltage regulator and bi-directional level shifters already on there. This module should be fine and you could give +5V (or V_USB) as VCC on there.

I think I know what to do now. Thanks @Maximilian


text:
External power vs usb power
I built a sample of my project on a breadboard using little 700mh leds and other components that easily ran off my computers usb. Now I’m building my project to full size.  This includes 12 7w leds, soundboard and amps. It’s still going to be controlled by a arduino mega, obviously, the power consumption is substantially higher than the usb or even the arduino can provide. I’m using a high amp power supply that can drive everything including the arduino.
The question is... how will I be able to alter my sketch later???  Is it feasible to use a panel mount usb cord modified to only allow tx and rx, (cut the red and black)?  Or will I have to isolate the mega each time I need to send a change to it?

700mh? Realize its not really important to the question...

You can modify a USB cable by cutting the power (red) wire. You'll still need the ground wire with RX and TX.

Using an altered USB cable and a separate power supply will work but isn't really necessary. I usually put a connector on my high-current devices like LEDs and whatnot so I can remove them from the equation while I upload code, and for debugging I leave the external power supply attached and use a regular USB cable to the PC (see What happens if I power the Arduino with both the USB and external power voltage simultaneously?).


text:
Configuring Accelerometer on BNO055 sensor
I'm using the BNO055 9DOF Adafruit sensor to measure the acceleration/orientation. How can I change the configuration of the accelerometer from 4G (default) to 16G?
What I already know:
The datasheet : https://cdn-shop.adafruit.com/datasheets/BST_BNO055_DS000_12.pdf
From point 3.5.2 from page 27, I need to change xxxxxx01b to xxxxxx11b in the configuration file (that is the library). I use https://github.com/adafruit/Adafruit_BNO055 but I could not find any information on what to change and where in the .h file.
Any ideas?
Thank you

This was partly discussed as an issue on the library's github

https://github.com/adafruit/Adafruit_BNO055/issues/48

Here's how I understand it:
The library doesn't configure the registers you want. I don't see a reference to writing to the ACC_CONFIG register (address 8). Not even defined in the header.
The sensor has two register-pages (0 and 1) [refer page 50]. I.e. if you select page 0 then the register at address X means something, at page 1 it means something else.
We want to write to ACC_Config at address 0x08 on Page 1.
Page 77 tells us that, regarding writing to the register: "Write: can only be changed in sensor mode, see section 3.5.2"
In code, you could hack something in there:

https://github.com/adafruit/Adafruit_BNO055/blob/master/Adafruit_BNO055.cpp#L115

After changing to the sensore mode, you could then write to the register as
//values taken from section 3.5.2 page 27
#define BNO055_ACC_CONFIG_2G (0) //0B00
#define BNO055_ACC_CONFIG_4G (1) //0B01
#define BNO055_ACC_CONFIG_8G (2)  //0B10
#define BNO055_ACC_CONFIG_16G (3)  //0B11

//bandwidth definitions
#define BNO055_ACC_BW_7_81_Hz (0)
#define BNO055_ACC_BW_15_63_Hz (1)
#define BNO055_ACC_BW_31_25_Hz (2)
#define BNO055_ACC_BW_62_5_Hz (3)
#define BNO055_ACC_BW_125_Hz (4)
#define BNO055_ACC_BW_250_Hz (5)
#define BNO055_ACC_BW_500_Hz (6)
#define BNO055_ACC_BW_1000_Hz (7)

//powermode definitions
#define BNO055_ACC_PWRMODE_NORMAL (0)
#define BNO055_ACC_PWRMODE_SUSPEND (1)
#define BNO055_ACC_PWRMODE_LP1 (2)
#define BNO055_ACC_PWRMODE_STANDBY (3)
#define BNO055_ACC_PWRMODE_LP2 (4)
#define BNO055_ACC_PWRMODE_DEEP_SUSPEND (5)

#define BNO055_ACC_CONFIG_ADDR 0x08

//Select page ID 1 to write to the right register
write8(BNO055_PAGE_ID_ADDR, 1);
//build the config value with bitshifts
//see page 77
//use all standard values except 16G parameter
uint8_t acc_config = (uint8_t)((BNO055_ACC_PWRMODE_NORMAL << 5)
                   | (BNO055_ACC_BW_62_5_Hz << 2)
                   | BNO055_ACC_CONFIG_16G);
//write new accelerometer config
write8(BNO055_ACC_CONFIG_ADDR, acc_config);

//change back to page ID 0 (or whatever was before there)
//Otherwise we read sensor data from the wrong page with entirely different meaning
write8(BNO055_PAGE_ID_ADDR, 0);

Since I don't have that sensor here I have no way to test it. So this is just the basic idea. You can also read registers with read8, with which you can verify that before you write anything to the register, it has some standard (or expected) value. E.g., ACC_CONFIG should read as 0B00001101 = 0x0d. And after you write a value there you should be able to read the same value back, otherwise the chip didn't let you execute the write and you have to investigate why.
Yes, you mostly have to do the hard work by yourself. Changing from 4G to 16G might also have the implication that some other calculations on the raw data has to be done different, however I am not sure of that.


text:
trouble getting out of a for loop in a function and go back to a FSM with a button
I have a finite state machine that goes to a function called patternOne, I can't seam to get out of this function though once I am in it and get back to the finite state machine. When I press a button my serial port shows it's been pressed but still stays in the function patternOne, I don't know how to get out of it and why this is happening. My code is below:
#include <SPI.h>
SPISettings settingsA(2000000, MSBFIRST, SPI_MODE1);
#include <SFE_MicroOLED.h>  // Include the SFE_MicroOLED library
#include <Wire.h>  // Include Wire if you're using I2C
volatile unsigned long prevTime = 0;

int time_interval_for_chip = 5;
int blinking_interval = 500;
unsigned long current_time = 0;
#define PIN_RESET A6  // Connect RST to pin 9

#define DC_JUMPER 0

MicroOLED oled(PIN_RESET, DC_JUMPER);// I2C declaration

const int buttonpin = A8;
volatile int buttonState = 0;   // variable for reading the pushbutton status
volatile int buttonState2 = 0;
int buttonstate3 = 1;
const int buttonpin2 = A7;

enum State {flip, intro, option1, pattern1, intro_flip, option1_flipped, pattern1_flipped, pattern2, pattern3};
//enum is the data type that consists of user defined varaibles ie like the words pattern, intro, ext
State state = flip; //telling the intial state to start at intro

unsigned int column_pattern1[] = {0b0000000100000100, 0b0000001000001000,0b0100000010000010};
//unsigned int column_off_pattern1[]={0b0000000000000100, 0b00000000000001000,0b0100000000000010};
const int css1 = 10;
const int css2 = A0;
void setup() {
  oled.begin();    // Initialize the OLED
  oled.clear(ALL); // Clear the display's internal memory
  //  oled.display();  // Display what's in the buffer (splashscreen)
  //  delay(1000);     // Delay 1000 ms
  oled.clear(PAGE); // Clear the buffer.
  //

  pinMode(css1, OUTPUT);
  pinMode(css2, OUTPUT);
  Serial.begin(9600);
  SPI.begin();
  SPI.beginTransaction(settingsA);

  pinMode(buttonpin, INPUT_PULLDOWN);
  pinMode(buttonpin2, INPUT_PULLDOWN);
  // watermark generates this interrupt
  attachInterrupt(buttonpin, button_pressed, FALLING); // interrrupt 1 is data ready
  //attachInterrupt(buttonpin2, button_pressed2, FALLING); // interrrupt 1 is data ready

}

void loop() {

  // blinking output 4 and 8 while using a finite state machine to change from intro to a patter
  //turning off the desplay when a pattern is chosen

  switch (state) {
    case flip:
    oled.setFontType(1);
  oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
  //oled.setFontType(2);
  //  oled.setCursor(0, 0);
  oled.print(" Flip  Screen?");
  oled.setFontType(0);
  oled.setCursor(0, 30);
  oled.print("yes");
  oled.setCursor(40, 30);
  oled.print("no");
  oled.circle(10, 43, 3.5);
  oled.circle(50, 43, 3.5);
  oled.display();
  buttonState = 0;

  if (digitalRead(buttonpin2) == HIGH) {
        oled.circleFill(50, 43, 3.5);
        oled.display();
        oled.clear(PAGE); // Clear the buffer.
        delay(500);
        //buttonstate3=0;
     state=intro;
  }
   if (digitalRead(buttonpin) != buttonState) {
    oled.circleFill(10, 43, 3.5);
     oled.display();
        oled.clear(PAGE); // Clear the buffer.
        delay(500);
        state=intro_flip;
   }
  break;

    case intro:

      oled.setFontType(1);
      oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
      //oled.setFontType(2);
      //  oled.setCursor(0, 0);
      oled.print("choose pattern");
      oled.circle(10, 40, 7);
      oled.display();
      buttonState = 0;

      if (digitalRead(buttonpin) != buttonState) {

        buttonState = 0; //reset button state
        oled.circleFill(10, 40, 7);
        oled.display();
        delay(500);
        state = option1;

      }
      break;

    case option1:
      oled.clear(PAGE); // Clear the buffer.

      //delay(300);
      oled.setFontType(0);
      oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
      //oled.setFontType(2);
      //  oled.setCursor(0, 0);
      oled.print("Pattern 1");
      oled.setCursor(0, 10);
      oled.print("next");
      oled.setCursor(40, 10);
      oled.print("yes");
      oled.circle(10, 40, 7);
      oled.circle(50, 40, 7);
      oled.display();

      if (digitalRead(buttonpin2) == HIGH) {
        Serial.println("right button pressed");

        oled.circleFill(50, 40, 7);
        oled.display();
        delay(500);
        state = pattern1;

      }
      break;
        case pattern1:
      oled.clear(PAGE);
      oled.display();

      patternONE();
      buttonState=0;
      if (digitalRead(buttonpin) != buttonState) {
        Serial.println("left button pressed");
        //         //delay to register that the button was pressed
        delay(500);
        //
        state = intro;
      }
      break;

////////////////////////////////////////////////////////
///////////FLIPPED FINITE STATE MACHINE/////////////////
////////////////////////////////////////////////////////

case intro_flip:
  oled.flipVertical(true);
    oled.flipHorizontal(true);
     oled.setFontType(1);
      oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
      //oled.setFontType(2);
      //  oled.setCursor(0, 0);
      oled.print("choose pattern");
      oled.circle(50, 40, 7);
      oled.display();
      buttonState = 0;

      if (digitalRead(buttonpin) != buttonState) {

        buttonState = 0; //reset button state
        oled.circleFill(50, 40, 7);
        oled.display();
        delay(500);
        state = option1_flipped;

      }
      break;

      case option1_flipped:
oled.flipVertical(true);
    oled.flipHorizontal(true);
      oled.clear(PAGE); // Clear the buffer.

      //delay(300);
      oled.setFontType(0);
      oled.setCursor(0, 0);  // Set the text cursor to the upper-left of the screen.
      //oled.setFontType(2);
      //  oled.setCursor(0, 0);
      oled.print("Pattern 1");
       oled.setCursor(0, 10);
      oled.print("yes");
      oled.setCursor(40, 10);
      oled.print("next");
      oled.circle(10, 40, 7);
      oled.circle(50, 40, 7);
      oled.display();

      if (digitalRead(buttonpin2) == HIGH) {
        Serial.println("right button pressed");

        oled.circleFill(10, 40, 7);
        oled.display();
        delay(500);
        state = pattern1_flipped;

      }
      break;

       case pattern1_flipped:
      oled.clear(PAGE);
      oled.display();

      patternONE();
//      buttonState=0;
      if (digitalRead(buttonpin) != buttonState) {
        Serial.println("left button pressed");
        //         //delay to register that the button was pressed
        delay(500);
        //
        state = intro_flip;
      }
      break;

  }
}////////////////////////////////////////////////////////
///////////Pattern/////////////////
////////////////////////////////////////////////////////
void patternONE() {
buttonState = 0;
   unsigned int chip1 = 0;
  unsigned int chip2 = 0;
  byte inbyte = 0;
  byte inbyte2 = 0;

  for (int i = 0; i < 3; ++i) {

    digitalWrite(css2, LOW);
    chip2 = SPI.transfer16(column_pattern1[i]);
    Serial.print("chip2 column off=");
    Serial.println(chip2, BIN);
    digitalWrite(css2, HIGH);

    digitalWrite(css1, LOW);
    chip1 = SPI.transfer16(0b0001010000000000);
    Serial.print("chip1 row 8 on high driver= ");//not the chip is a look behind so the print statments are the previous output
    Serial.println(chip1, BIN);
    digitalWrite(css1, HIGH);

    delay(1);
    digitalWrite(css1, LOW);
    chip1 = SPI.transfer16(0b0100000100000000);
    Serial.print("chip1 row 4 and 6 on low driver= ");
    Serial.println(chip1, BIN);
    digitalWrite(css1, HIGH);

    delay(2000);

    digitalWrite(css1, LOW);
    chip1 = SPI.transfer16(0b0001010001010000);
    Serial.print("chip1 row 8 on low driver= ");
    Serial.println(chip1, BIN);
    digitalWrite(css1, HIGH);

    delay(1);

    digitalWrite(css1, LOW);
    chip1 = SPI.transfer16(0b0100000100000100);
    Serial.print("chip1 row 4 and 6 on high driver= ");
    Serial.println(chip1, BIN);
    digitalWrite(css1, HIGH);

    digitalWrite(css2, LOW);
    chip2 = SPI.transfer16(column_pattern1[i]);
    Serial.print("chip2 column on high driver= ");
    Serial.println(chip2, BIN);
    digitalWrite(css2, HIGH);

    //turn off the previous column
//    digitalWrite(css2, LOW);
//    chip2 = SPI.transfer16(column_off_pattern1[i]);
//    Serial.print("chip2 column on high driver= ");
//    Serial.println(chip2, BIN);
//    digitalWrite(css2, HIGH);
//
    delay(2000);

  }

}

// watermark generates this interrupt
void button_pressed()
{
  cli();
  //confirmitng that the button was pressed and that its not just like a bounce"
  if (millis() - prevTime > 50) {
    Serial.println("left button pressed");
    buttonState = 1;
  Serial.println("buttonState =");
  Serial.println(buttonState);
  }

  sei();
  prevTime = millis();

}

You could start with some old fashioned brute force Serial.println debugging.  Print the current state before the switch & print every change of state then add more printlns as needed to track down the error.

How do you know you never leave PatternONE() and are not just calling it over and over again?

hum thats a good question, if i'm calling it over and over again how do I leave it then?

See earlier comment -- debug with Serial.println()

thanks for the help Craig! it worked when I did the brute fore,

From your question, it sounds like you are expecting PatternONE() to return on a button press but I don't see any code in the function that refers to a button or acts on one. The function defines a local variable buttonState and initializes it to 0, but never refers to it again.
I suspect you meant that as a declaration of the global buttonState, but you have two problems: 1) the function never uses buttonState to initiate a return; and 2) the local definition buttonState hides the global one while it is in scope; i.e., while the function is executing.

Unless some code is missing, patternOne() does not declare a local variable.  It assigns a value of 0 to the global variable.

Oops - correct. It does reset the global, but never refers to it again.

it turned out I was suppose to comment out the buttonState=0; right after the patternONE(); in the case pattern1 and then it worked fine.


text:
Fast PWM working with int main(void) but not with void setup()
board: Arduino Mega (ATMEGA2560)
I want to generate pulses using timer1 configured as Fast PWM, this is my code which works fine:
#include <avr/io.h>

int main(void)
//void setup()
{

  DDRB |= (1 << DDB5) | (1 << DDB6); // PWM outputs

  ICR1 = 0x7FFF;  // TOP
  OCR1A = 0x3FFF; // 50% of ICR1
  OCR1B = 0x3FFF; // 50% of ICR1

  TCCR1A |= (1 << COM1A1) | (1 << COM1B1);
  TCCR1A |= (1 << WGM11);
  TCCR1B |= (1 << WGM12) | (1 << WGM13);
  TCCR1B |= (1 << CS10);

}

void loop() {

}

I don't understand why it doesn't work if I use void setup() instead of int main(void). I'm working with arduino IDE 1.8.2 and always used void setup(), in this case I used int main(void) because it is used in some turorials I found like this one: https://www.youtube.com/watch?v=O_Yqf_cugwE
EDIT: When I say that it doesn't work, what happens is that instead of having PWM signals I just have a constant 5V output in both OC1A and OC1B pins

Try using = instead of |=.

Using = instead of |= I have now a 0V output instead of 5V. I tried to initialize TCCR1A = 0; and TCCR1B = 0; first.

If you don't define your own main(), your program will be linked with
the main() provided by the Arduino core library, which roughly looks
like this (I am simplifying a little bit):
int main(void)
{
    init();      // Arduino core initialization
    setup();     // user's initialization
    for (;;)
        loop();  // user's main loop
}

The core's init() function configures Timer 1 for 8-bit phase
correct PWM at 490 Hz, which means that, by the time your setup()
runs, the timer's control registers are not in their default state
anymore, and some of their bits are already set to 1. If you then
update these registers using the |= operator, you end up with a mix of
the core's configuration and your own.
This can be fixed either by zeroing these registers first or, more
simply, by setting their values with the = operator, which has the
effect or setting every bit of those registers to the value you want.
The following works whether you use or not the Arduino core library:
#ifdef NOCORE
int main(void)
#else
void setup()
#endif
{
    DDRB   = _BV(PB5) | _BV(PB6);
    TCCR1A = _BV(COM1A1)
           | _BV(COM1B1)
           | _BV(WGM11);
    TCCR1B = _BV(WGM12)
           | _BV(WGM13)
           | _BV(CS10);
    ICR1   = 0x7fff;  // TOP
    OCR1A  = 0x3fff;  // 50% of ICR1
    OCR1B  = 0x3fff;  // 50% of ICR1
}

#ifndef NOCORE
void loop(){}
#endif

Note that:

The control registers are set (=) rather than just modified with
|=
The mode is set before the output compare registers. This is because
setting the output compare registers does not work well when the timer
is in an 8-bit mode.

Thank you for pointing out that the order in which the timer is set up could affect in some way, i had no idea.  With your code it still does not work for me, did you have a chance to test it?

@Mr.C: I tested it (and it works) on an Uno. I had to change DDRB to _BV(PB1) | _BV(PB2) in order to fit the Uno's pinout. Note that on the previous version of my answer I mistakenly left the DDRB setting appropriate for the Uno.

After changing DDRB to _BV(PB1) | _BV(PB2) to the corresponding pins in MEga DDRB to _BV(PB5) | _BV(PB6) it works perfectly, i didnt notice that. Thank you so much @Edgar Bonet, after your explanation about the core's init function it is more clear for me now why it was not working with void setup().


text:
Change values of timer using I2C
I'd like to alter the "LED_T_ON" values using an I2C enabled device (i.e. RPi)
Code for Arduino Mega slave:
//slave

#include <Wire.h>

#define SLAVE_ADDRESS 0x08

const int PWR_LED = 43;
int LED_TinH_ON = 18;
int LED_T_ON = 5000;
int LED_T_OFF = 5000;

String inString = "";    // string to hold input
byte LastMasterCommand = 0;
int Mval;

char user_input;

class Relay {
  int relayPin;
  long OnTime;     // milliseconds of on-time
  long OffTime;    // milliseconds of off-time

  // These maintain the current state
  int relayState;                 // pumpState used to set the PUMP
  unsigned long previousMillis;   // will store last time PUMP was updated

  // Constructor - creates a Timer and initializes the member variables and state
  public:
  Relay(int pin, long on, long off)
  {
    relayPin = pin;
    pinMode(relayPin, OUTPUT);

    OnTime = on;
    OffTime = off;

    relayState = LOW;
    previousMillis = 0;  //ORIGINALLY 0
  }

  void Update()
  {
    // check to see if it's time to change the state of the TIMER
    unsigned long currentMillis = millis();

    if((relayState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
      relayState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(relayPin, relayState);  // Update the actual LED
    }
    else if ((relayState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      relayState = HIGH;  // turn it on
      previousMillis = currentMillis;   // Remember the time
      digitalWrite(relayPin, relayState);   // Update the actual RELAY
    }
  }
};

Relay relay3(PWR_LED, LED_T_OFF, LED_T_ON);

void setup() {
 // initialize serial communication with computer:
  Serial.begin(9600);

  Wire.begin(SLAVE_ADDRESS);

  Wire.onReceive(receiveData);
  Wire.onRequest(slavesRespond);

  pinMode(PWR_LED, OUTPUT);
}

void loop() {
  delay(1000);

  Serial.print("LED_T_ON=");
  Serial.println(LED_T_ON);
  Serial.print("LED_T_OFF=");
  Serial.println(LED_T_OFF);
  Serial.println();

  relay3.Update();

  switch (Mval) {
    case 1 ... 25:
      LED_TinH_ON = Mval;
      Serial.print("LED time on: ");
      Serial.print(LED_TinH_ON);
      Serial.println("h");
      LED_T_ON = LED_TinH_ON*1000;//*60*60;
      LED_T_OFF = (24-LED_TinH_ON)*1000;//*60*60;
    break;
  }
}

void receiveData(int byteCount) {
  LastMasterCommand = Wire.read();
  while (Wire.available()) {
    int msg = Wire.read();

    if (isDigit(msg)) {
      inString += (char)msg;
    }
  }
  Mval = inString.toInt();
  //Serial.println(LastMasterCommand);
  inString = "";
  //Serial.println(Mval);
}

void slavesRespond() {
}

When I change the value on the RPi the Arduino receives and displays the correct value but the timed relays don't actually use the updated values.
Am I missing something?

I see nothing there relating to I2C. What there can be "displaying the correct value" when there is neither anything receiving a value nor anything displaying anything anywhere?

Same. Also LED_T_ON is not changed anywhere (nor is OnTime).

My bad, edited to display the right code

assuming maybe you have other code that is doing the I2C bit, if that code is changing the value of LED_T_ON that will have no effect on that relay object as that value is passed in during the construction. You would need to update relay3.OnTime    ( your order/naming is also switched, relay3(PWR_LED, LED_T_OFF, LED_T_ON); calls Relay(int pin, long on, long off)

Your updating LED_T_ON and LED_T_OFF but those values were already passed into the constructor and changing them will not change the object. you need to update  relay3.OnTime and relay3.OffTime


text:
I2C Read Operation in TCA9539
I am using this TI device TCA9539 (http://www.ti.com/lit/ds/symlink/tca9539.pdf) with the pins A1 and A0 tied to ground resulting the write address to 0x74.

I don't have any issues writing to this device address and perform the necessary functions, however when I try to read registers using Arduino read functions, getting NACK there. Is 0x75 correct read address?
For second question:
Based on the device spec for read operation:

Reading from a slave is very similar to writing, but requires some additional steps. In order to read from a slave,
  the master must first instruct the slave which register it wishes to read from. This is done by the master starting
  off the transmission in a similar fashion as the write, by sending the address with the R/W bit equal to 0
  (signifying a write), followed by the register address it wishes to read from. When the slave acknowledges this
  register address, the master sends a START condition again, followed by the slave address with the R/W bit set
  to 1 (signifying a read). This time, the slave acknowledges the read request, and the master releases the SDA
  bus but continues supplying the clock to the slave. During this part of the transaction, the master becomes the
  master-receiver, and the slave becomes the slave-transmitter.
  The master continues to send out the clock pulses, but releases the SDA line so that the slave can transmit data.
  At the end of every byte of data, the master sends an ACK to the slave, letting the slave know that it is ready for
  more data. When the master has received the number of bytes it is expecting, it sends a NACK, signaling to the
  slave to halt communications and release the bus. The master follows this up with a STOP condition."

This is the code I am trying to use,
Wire.begin();
Wire.beginTransmission(0x74); // start i2c transmission as write addr
Wire.write(0x01)              // the register i need to read from
Wire.beginTransmission(0x75); // start i2c transmission as read addr given

I believe the device I2C read and arduino library functions for read is not making sense to me. Has anyone used this device for read?

somewhat related: When does the Arduino Wire library actually transmit on I2C ?

You have misunderstood, how the Wire library works. It is doing all the things with the direction bit for you.
Write Operation:

Wire.beginTransmission() takes a 7-bit address as a parameter. The direction bit is automatically and internally set to write operation.
Wire.write() writes a value to the library-internal buffer, but is not doing anything on the actual I2C bus
Finally you call Wire.endTransmission() to finally do the write operation on the actual I2C bus. Prior to this function call the library doesn't do anything on the bus. So you have to call it, so that the data can reach the slave device

Read Operation:

For reading from a slave device there is an extra function: Wire.requestFrom(). It takes the (7-bit) address and the number of requested bytes as parameters and it returns the number of bytes, that were actually read from the slave device (is important if the slave is sending less data, than requested). After a call to this function, the read bytes are now lying in the library-internal buffer.
To get the received bytes from the library-internal buffer, you have to use Wire.read(). Again it does not do anything on the I2C bus. It just reads from the internal buffer.

So for your code you need to send a command byte to the slave, that says, what registers of the slave (determinded by the lowest three bytes, as the datasheet says) you want to access next. After that you can either send more bytes (in order to write the chosen registers) or you can start a request, so that the slave will send you the current state of the selected register.
Look at this images from pages 23 and 24 of the datasheet:

These are showing exactly, what you have to send. Note that the address byte is automatically send by the Wire library, so you don't have to do it. I will put it in code for you:
Write operation:
Wire.begin();
Wire.beginTransmission(slave_address);
Wire.write(register_address);
Wire.write(new_register_data);
Wire.endTransmission();

The register address is documented in the datasheet. In this case it is the register with address 0x01 (Though this makes no sense, since this is a read-only register).
Read operation
Wire.begin();
Wire.beginTransmission(slave_address);
Wire.write(register_address);
Wire.endTransmission();
if(Wire.requestFrom(slave_address,1) > 0 ){
    byte data = Wire.read();
}

Here we first do a write operation to tell the slave, what register we want to access. Then we request the data in this register with Wire.requestFrom(). To transfer from the internal buffer to our program is done with the Wire.read() function (but only, if there was actually something received).

For the address of the slave device: This depends on how you have set the pins A0 and A1. You can find a table with the corresponding addresses at page 21 of the datasheet. Note that these are NOT including the data direction bit. When you are using the Wire library, you don't have to bother about it.

If this solved your problem, please mark the answer as correct, so that others can see it directly. Thank you

Done, answers accepted!

The arduino i2c libraries expect a 7 bit slave address, not 8 bit address + r/w bit, and will manage the read write bit internally based on if you do a write or read.
So begin transmission 0x74
Write 0x01
End transmission
Begin transmission 0x74
Read n
End transmission

You have to end the first transmission before starting the read. The actual I2C action is done when endTransmission() is called.


text:
Binary addressing and coding to control a 96 input mux matrix
I’m trying to wrap my head around using binary addresses in a mux. Failing miserably.
For the circuit I have six 16 channel analog multiplexers CD74HC4067 as slaves to an eight channel multiplexor CD54HC4051 master.
They are bringing in 96 sensor readings (IR receiver diodes through Op Amps) into an array
that, in turn,  is used to constantly update lotsa LEDs through a series of shift registers (TLC5940) using the Arduino TLC5940 Library.
I’ve included the possible wiring scheme that the code is trying to control.
It probably needs work too.
Question: I’ve seen, and SEMI-understand matrixes that address 32 inputs
(4 x 8 bits) but not quite understanding how I can address the six mux chips
with 96 inputs. Or if I can even do it this way. Example from this forum: How to code for cascading multiplexers?
Is it possible with this matrix of 96 inputs, and how? Am I barking up the wrong tree?
Code so far:
    #include <Tlc5940.h> //Arduino TLC5940 Library controls the individual LEDs - "Pixels"

int ledCount = 96; //change  LED "PIXEL" count in matrix...also number of IR sensor inputs

int thresh = 10; //value for usable distance reading from IR

// main structures to hold LED Pixel array on/off state, IR reciever readings
byte dsply_state[ledCount];    //pixel on-off grid, need for tlc5940
uint_16  recv_state[ledCount];           // IR Readings - FROM mux set-up

// Master IR -mux sensor pins for Arduino Pro MINI
#define  M_S0 2
#define  M_S1 4
#define  M_S2 5
// Slave IR mux sensor pins
#define  S_S0 6
#define  S_S1 7
#define  S_S2 8
#define  S_S3 12

//  ANALOG PIN :
#define  InputFromMux A0

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

    //tlc5940 Arduino library
    Tlc.init(0);

    // CONFIGURE ADDRESS PINS
    pinMode(M_S0, OUTPUT);
    pinMode(M_S1, OUTPUT);
    pinMode(M_S2, OUTPUT);

    pinMode(S_S0, OUTPUT);
    pinMode(S_S1, OUTPUT);
    pinMode(S_S2, OUTPUT);
    pinMode(S_S3, OUTPUT);
    pinMode(InputFromMux, INPUT);

}

void loop() {
    // LOOP THROUGH ALL THE ADDRESSES OF THE MASTER and SLAVES.

  for (int i = 0; i < ledCount; i++) {

    digitalWrite(M_S2, i & 0b1000000);
    digitalWrite(M_S1, i & 0b0100000);
    digitalWrite(M_S0, i & 0b0010000);
    digitalWrite(S_S3, i & 0b0001000);
    digitalWrite(S_S2, i & 0b0000100);
    digitalWrite(S_S1, i & 0b0000010);
    digitalWrite(S_S0, i & 0b0000001);

    delay(2);

    //edited as per @Gerben. thanks so much

    //get an individual sensor reading from IR receiver/opAmp mux, store it in a variable
     int IRstate = analogRead(InputFromMux);

    //populate receiving array with a reading
     recv_state[i] = IRstate;

    //populate display array for tlc5940 to push out
     dsply_state[i] = recv_state[i];

} //end for(i...) loop

      //run through display state array to check if the stored reading is greater than a threshold number
      //if yes, then turn on the "pixel". If not, set it to zero
      //

       for (int x = 0; x < ledCount; x++)
          if (dsply_state[x] >= thresh ) {

               Tlc.set(dsply_state[x], 4000);

             //or if reading from mux is zero
          } else if (dsply_state[x] < thresh) {

              Tlc.set(dsply_state[x], 0);
              }

            //tlc5940 Arduino library - update() clocks the chips
            // move update(); outside the for(x...) loop for speed?
        Tlc.update();
        delay(10);

      } //end For(x..) Loop

}//endMainLoop

The 48 in the for loop should be 96. It should be digitalWrite(M_S2, i & 0b1000000) not 0b110000. You do an anologRead, but never do anything with the read value (IRstate).

Thank you @Gerben. This is exactly the part that confuses me. How to correctly write the masks(?) that make the chips cycle through each input. If I digitalWrite M-S2 as i & 0b1000000, won't that be the same as M_S1? Or does it change enough as you've added six zero's instead of five - M_S1, i & 0b100000? As per IRstate, I thought I was pushing each reading into recv_state array in the for loop. Or should the variable be inside the loop? Or is there a better way to get each reading into an array?

You correctly spotted the extra 0. Your mask needs to be 7 bits long. 3 bits to represent a 0-7 for the first mux, 4 bits to represent 0-15 for the second stage muxes. Maybe for readability, you could add a 0 on the left of all mask.

The line of your code is IRstate = recv_state[x];. Maybe you meant recv_state[x] = IRstate; instead. The value of right part is what you assign to the left part. I think what you need is to remove the for( x ...) loop and add recv_state[i] = IRstate; and dsply_state[x] = recv_state[x];

Thanks @gerben, I'll edit the masks. Re:IRstate.....So that works without a for loop? int IRstate = analogRead(InputFromMux); recv_state[i] = IRstate; disply_state[x] = recv_state[i]; That three lines takes the individual readings, pushes all 96 readings into recv-state array and then maps recv-state[] onto a new display_state[] array? Is it the main loop then, doing the pushing?

You already have a for-loop. No need for the other.

Thank you @gerben. I see I missed the first for(i...) loop, so I understand how I was repeating. However, I'm not understanding how dsply_state[x] is iterating? dsply_state[x] = recv_state[i]; Isn't it just overwriting x rather than mapping 96 individual values into the dsply_state array? Should I just make it dsply_state[i] = recv_state[i];? Would that be the right way to map dsply_state array to recv_state array?

Yeah, sorry. I forgot to replace the x with a i. That would make the values in the dsply_state array the same as the recv_state array. PS. I'm only counting 5 } while there are 6 {s.

This helped so much. I've tried to edit the code as you suggested. It makes so much more sense now. Thank you @gerben

You will have a problem if you don't change the schematic. You have A0 unused on the 4051 chip, which means that your bit patterns are going to be out. You should really use A0 to A5 leaving A6 and A7 free. Otherwise the code will have to change to allow for that. Probably two loops would be easier in that case if you already have the board and can't change it.

You could also use the digitalWriteFast library which will somewhat speed up all those digitalWrites in the loop.

I take back that comment about digitalWriteFast. That requires both arguments (pin number and value) to be constants. The value isn't a constant.

OK. First, how the multiplexer works. I have a page about multiplexers in which there is this example of the 74HC4051:

Depending on the "binary" input to A/B/C (shown as S0/S1/S2 on your schematic) there is a low resistance path between one of the 8 inputs and the single output. The CD74HC4067 works in a similar way, except it switches 16 inputs.
So, if you set up the binary number 2 (010) in A/B/C then the third input is selected (number 02 because it is zero-relative).
In your schematic you have 6 x CD74HC4067 which therefore can have 16 x 6 inputs (96 inputs in total). The outputs of those 6 are fed into the 54HC4051 (2 aren't used) so therefore the 54HC4051 can select which of the 6 16-input chips it is interested in right now, by setting up a number between 0 and 5 on the 8-input multiplexer.
The four binary inputs to the 6 x CD74HC4067 are all tied together as you can see on the schematic.
Thus your method would be:

Loop from 0 to 5 on the master multiplexer (the 54HC4051). This selects which of the 6 16-input multiplexers you are interested in right now.
For each of those, loop through 0 to 15 on S0/S1/S2/S3 so that the currently-selected CD74HC4067 routes its input through to its output.
Read the resulting value

Those two loops will give you 96 inputs, which is what you are trying to read.
This technique takes 7 output pins to output the binary numbers (3 bits plus 4 bits). It also needs one input pin to read the result.

Judging by the schematic it uses SPI (serial data) to control the 6 x TLC5940 shift registers which lets it turn LEDs on and off with only two control pins (SCK and MOSI named SCLK and SOUT on your schematic).
The chips are daisy-chained together so all of those TLC5940s are controlled by those two pins.
This fairly minimalist design has therefore left some spare pins on the Arduino Pro.

Mostly having a hard time visualizing the code, especially how to write correctly the 7 binary digital write commands. Is it possible for you to correct what I've written above, so I might be able to see the pattern?

I know you changed the question by the time I saw this, but the code below illustrates what I mean by the two loops:
const int MUX_CHIPS = 6;
const int LEDS_PER_CHIP = 16;
const int TOTAL_IR_INPUTS = MUX_CHIPS * LEDS_PER_CHIP;
// Master IR -mux sensor pins for Arduino Pro MINI
const byte  M_S0 = 2;
const byte  M_S1 = 4;
const byte  M_S2 = 5;
// Slave IR mux sensor pins
const byte  S_S0 = 6;
const byte  S_S1 = 7;
const byte  S_S2 = 8;
const byte  S_S3 = 12;
//  ANALOG PIN :
const byte INPUT_FROM_MUX = A0;

int  recv_state[TOTAL_IR_INPUTS];           // IR Readings - FROM mux set-up

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

    // CONFIGURE ADDRESS PINS
    pinMode(M_S0, OUTPUT);
    pinMode(M_S1, OUTPUT);
    pinMode(M_S2, OUTPUT);

    pinMode(S_S0, OUTPUT);
    pinMode(S_S1, OUTPUT);
    pinMode(S_S2, OUTPUT);
    pinMode(S_S3, OUTPUT);
    pinMode(INPUT_FROM_MUX, INPUT);

    // set ADC prescaler of 32
    ADCSRA &= ~(bit (ADPS0) | bit (ADPS1) | bit (ADPS2)); // clear prescaler bits
    ADCSRA |= bit (ADPS0) | bit (ADPS2);                 //  32
} // end of setup

void loop() {

  unsigned long start = micros ();

  // read from IR diodes

  int whichLED = 0;
  for (byte master = 0; master < MUX_CHIPS; master++)
    {
    // select appropriate slave on the master MUX
    digitalWrite(M_S2, (master & 0b100) ? HIGH : LOW);
    digitalWrite(M_S1, (master & 0b010) ? HIGH : LOW);
    digitalWrite(M_S0, (master & 0b001) ? HIGH : LOW);

    // take each slave reading
    for (byte slave = 0; slave < LEDS_PER_CHIP; slave++)
      {
      digitalWrite(S_S3, (slave & 0b1000) ? HIGH : LOW);
      digitalWrite(S_S2, (slave & 0b0100) ? HIGH : LOW);
      digitalWrite(S_S1, (slave & 0b0010) ? HIGH : LOW);
      digitalWrite(S_S0, (slave & 0b0001) ? HIGH : LOW);

      // store this reading
      recv_state [whichLED++] = analogRead (INPUT_FROM_MUX);

      } // end of for each slave
    } // end of for each master

  // display results here ...

} // of loop

The exact code above took 5148 µs (around 5 ms) to execute the loop once on my Uno. If we remove the speedup of the ADC (analogRead) it takes 13252 µs (13 ms).
To allow for your exact wiring you need to ignore the low-order bit on the master MUX because you are not using input A0_13 in which case you need to add 2 to the master value in the outer loop:
    // select appropriate slave on the master MUX
    byte master_plus_2 = master + 2;  // allow for not using input A0
    digitalWrite(M_S2, (master_plus_2 & 0b100) ? HIGH : LOW);
    digitalWrite(M_S1, (master_plus_2 & 0b010) ? HIGH : LOW);
    digitalWrite(M_S0, (master_plus_2 & 0b001) ? HIGH : LOW);

Thank you @nickGammon. Appreciate the mux explanation. Very helpful. Mostly having a hard time visualizing the code, especially how to write correctly the 7 binary digital write commands. Is it possible for you to correct what I've written above, so I might be able to see the pattern? And yes, keeping this art installation very simple for now, at least until I can understand better

Look like you already have worked it out. You may want to change the ADC clock rate (see here). A prescaler of 32 will make the analogReads take only 26 µs rather than 104 µs which will improve responsiveness when you are reading 96 of them.

I updated my answer anyway to include the code I suggested (an inner loop and an outer loop). That will make it easier to change if you leave A0 disconnected on the master MUX.

This is sooo far out of my league :-) Regardless, thank you very much for the lessons @nickGammon. The explanations + code are so helpful. I will try both codes, the simpler and this double loop/pre-scaler after I solder up the circuit. I can still change the 4051 to use A0 - A5 as suggested and try to get that pre-scaler in there for speed. Especially considering that the 96 values, in turn, need to be pushed out through the TLC5940's as well


text:
Arduino pro micro might be bricked
I bought an Arduino pro micro (looks like this) from a Chinese seller over E-Bay, for its HID interface.
I installed the Arduino software on my Linux machine (Kali Linux), and started writing a USB Rubber Ducky script, and converted it to Arduino using Dckuino.js, which usually works just fine.
I may have used either:

The wrong programmer, or
The wrong board type

because when I uploaded the sketch, it said it failed, but HID script still worked when I plugged it into my Mac.
The Mac came up with a Keyboard Assistant, because it couldn't recognize the keyboard being use. So I plugged it back into my Linux machine, and it wouldn't recognize.

lsusb and dmesg -w didn't show any updates when re-plugging the Arduino.
Changing USB chords didn't work.
Switching over to windows, Device Manager didn't do the normal "refresh" when you plug in a new device, and there was nothing under COM Ports.
The HID input didn't work on the Mac anymore, when plugging it in again.
The inbuilt LED lights up when connected.

Is this a brick?
I can't seem to find any reset button or header on the board, so I cant connect the ground and reset.
There is an RST header, but I don't know what that is.
Any help would be greatly appreciated!

RST = ReSeT.  Have you tried re-flashing the bootloader through ICSP?

Be sure to check out the answers on a very similar question: Have I bricked my Arduino Uno Problems with uploading to board

Connecting the RST header to ground (GND) with a wire should be the same as pressing the reset button on other arduinos.

Do I need to solder on the wire, or can I just kind of hold it there?

Don't play with RST. Get another arduino. Load programmer sketch. And try to load bootloader over icsp. Select programmer "arduino as isp"


text:
Code output is not as expected
#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'E'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};
int count = 0; char num[4];
char key;
byte rowPins[ROWS] = {A0, A1, A2, A3}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 5, 4, 3}; //connect to the column pinouts of the keypad

char adhaar[4][4] = {
  {'1', '0', '8', '3'},
  {'9', '1', '6', '0'},
  {'5', '7', '6', '1'},
  {'6', '7', '9', '3'}
};

char adhaar0[4] = {'1', '0', '8', '3'};
char adhaar1[4] = {'9', '1', '6', '0'};
char adhaar2[4] = {'5', '7', '6', '1'};
char adhaar3[4] = {'6', '7', '9', '3'};
boolean check, control, adhar, tag_status;
int i = 0, j, p, q;

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
void setup() {
  Serial.begin(9600);
  Serial.println(" enter your adhaar ");
}

void loop() {
  getkey();
  checkkey();
}

void getkey() {
  while (i < 4) {
    char key = keypad.getKey();
    if (key) {
      num[i] = key;
      Serial.print(num[i]);
      i++;
    }
  }
}

void checkkey() {
  if (i == 4) {
    control = true;
    for (p = 0; p < 4; p++) {
      for (q = 0; q < 4; q++) {
        if (adhaar[p][q] == num[q]) {
          check = true;
          Serial.println(num[q]);
        } else {
          check = false;
          Serial.println(" not eligile");
          break;
        }
      }
      if (check == true) {
        adhar = true;
        Serial.println(" cast your vote");
      }
    }
    i = 0;
  }
}

My problem is once the adhaar matches with the values initialised in the array I have, it's going to "cast your vote" as expected, but after that it's again executing "not eligible" 3 times.

What was the output? What did you expect it to be? Please edit your question.

My problem is once the adhaar matches with the values initialised in the array i have taken, it's going to "cast your vote" as expected, but after that its again executing "not eligible" 3 times

please someone help me to solve this problem...thank you

Do not answer in a comment, please edit your question!

Also please just post the output, rather then trying to explain it

add line with return; after Serial.println(" cast your vote");, to not to check against remaining codes

First, a general remark: most of your variables are never used. You
should get rid of them, as they only serve to make your code more
obscure.
Then, the reason for the observed behavior is that you are comparing the
entered code with 4 predefined codes. Whatever the user enters, there
will be at least 3 non-matches, hence 3 times the program prints “not
eligile”.
To get the behavior you expect, I would get rid all all those boolean
variables that make the logic hard to follow, and instead break down the
problem into smaller chunks, each implemented in its own small function.
This makes it easier to write code that is easy to understand.
First, how do you tell whether two 4-character codes are the same? Like
this:
// Do codes a and b match?
bool match(char a[4], char b[4]) {
    for (int i = 0; i < 4; i++) {
        if (a[i] != b[i])
            return false;
    }
    return true;
}

Then, given a code entered by the user, tell whether it matches
adhaar[0] or adhaar[1] or... or none of them:
// Return the adhaar index matching the given key,
// or -1 if there is no match.
int matching_idx(char key[4]) {
    for (int i = 0; i < 4; i++) {
        if (match(key, adhaar[i]))
            return i;
    }
    return -1;  // no match
}

Now your checkkey() function can be rewritten as follows:
void checkkey() {
    if (i != 4) return;  // should never happen
    if (matching_idx(num) == -1)
        Serial.println(" not eligile");
    else
        Serial.println(" cast your vote");
    i = 0;
}

when I try this, its a infinite loop.....and its not going to next loop

@RenukaARajur: It goes into an infinite loop because I forgot to clear the global i variable in checkkey(). Fixed in the edit. Note that this way of using the global i is very poor design in the first place: this should instead be a counter local to getkey(), as in for (int i = 0; i < 4; i++) ....


text:
16*2 LCD display doesn't display my result
I am working on a project to calculate line frequency meter by reciprocal counting with Arduino. I am trying to print the the result on a 16*2 LCD but it is not displaying anything. It just gets on and stuck there. I got the project details from this website Line Frequency Meter Based On Reciprocal Counting
I modified the stock program to interface the LCD but it's not working. Here is the code I am using:
//To read and display the Line frequency
//using Reciprocal counting method
//clk for 'Time Counter'  is generated with 'Tone' function
//'Time counter' is the physical counter T1
// 'EVENT Counter' is a software counter
#define Fin 6      // input pin for Line freq sig
#define clk 7      // input to ' Time ' counter
#include<LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
boolean FState;   // status of the 50 Hz Signal
int countS;       // Signal count
int countC=0;     //  Clock count
int LineFreq;     // Result

void setup() {
  tone(8, 5000); // generates ref freq of 5000 Hz at Pin 8
  pinMode(Fin, INPUT); // set the Fin pin as INPUT
  pinMode(clk, INPUT); // set the clk pin as INPUT
  lcd.begin(16, 2);
}

void loop() {
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Frequency of signal");
  // to avoid partial cycles, first detect the rising edge
  while(digitalRead(Fin)) {
    //wait for '0' state of the Signal
    delayMicroseconds(10);
  }
  //here '0' state
  while(!digitalRead(Fin)) {
    //wait for '1' state
    delayMicroseconds(10);
  }
  //this is the rising edge of the Fin
  //counting can start from here
  // clear the TIME Counter T1
  counterStart1();
  //count 50 of the Line freq signals
  while(countS<50) {
    while(digitalRead(Fin)) {
      //wait for '0' state
      delayMicroseconds(1);
    }
    //here '0' state
    while(!digitalRead(Fin)) {
      //wait for '1' state
      delayMicroseconds(1);
    }
    // here '1' state
    // here one cycle is just over
    //increment the event counter
    countS=countS+1;
  }
  //here 50 Signal cycles over
  // read the contents of T1 & compute frequency
  countC = getCount1();
  LineFreq = 25000000/countC;

  //send to display
  lcd.setCursor(0,1);
  lcd.print(LineFreq);
  lcd.print(" Hz");
  delay(500);
  delay(100);
  // clear counter
  countS=0;
  // repeat
}

//The following code is obtained from on-line articles in the public domain
void counterStart1() {
 // hardware counter setup,  for  the 16-bit Timer1 Timer/Counter
 TCCR1A=0; // reset timer/countern control register A
 TCCR1B=0; // reset timer/countern control register B
 TCNT1=0; // initialize the counter value to 0; this register holds the current count
  // set timer/counter1 hardware as a counter; it counts events on pin Tn (Arduino pin 5)
 TCCR1B = TCCR1B | 7; // Counter Clock source = pin Tn (Arduino pin 5) , start counting now
 // 7 in binary is 0111; OR-ing will set CS10,11,12 to 1's
return;
}

// the following code is obtained from on-line articles in the public domain
// Sub routine  to get the current count
unsigned int getCount1() {
 unsigned int count; // this variable returns the current count from the counting register
 TCCR1B = TCCR1B & ~7; // Gate Off  / Counter T1 stopped,
 // this operation clears the bits (CS10,11,12)
 count = TCNT1; // read the counting register
 TCCR1B = TCCR1B | 7; // re-start counting by resetting the bits (CS10,11,12)
 return count; // return the retrieved count to the calling function
}

I am getting a blank screen but the line at very first of the code "Frequency of signal" is printing accurately.
What is wrong with the code and what changes do I need?
Thanks in advance!

Which is it? Not displaying anything, or only displaying "Frequency of signal"?

I fixed your indentation, as it was nearly impossible to read.

If the latter, it seems like you signal on pin 6 isn't there, or is too weak. Ending up with your code waiting for 50 transitions that just aren't there?

It is only displaying frequency of the signal only, which is written at the top of code. After that nothing is working. I checked the pin 6 signal And it was working fine.

Your variables are int, which on an Arduino is a 2-byte signed type by default, and has a range of -32768 to 32767.
When you execute:
LineFreq = 25000000/countC;

is the result of the math a 2-byte int, or a 4-byte long? Regardless, you are possibly assigning a 4-byte value to an int.
You can declare LineFreq to be type long, and also append an L to the end of the constant value 25000000 to force long math, so that you have:
long LineFreq;
[...]
LineFreq = 25000000L/countC;


text:
Soft WDT with HX711 and PubSubClient libraries
I'm using NodeMCU 0.9
My sketch crashes if the following 2 include are present in the sketch:
#include <PubSubClient.h>
#include <HX711.h>

I obtain a Soft WDT reset
If I do not use HX711 I can send message using mqtt.
If I do not use PubSubClient I can read weight values from the load cell connected to the hx711 board without problem
The code crashes at the following line:
mqtt_client.connect("ESP8266Client", mqtt_user, mqtt_password)

Actually using this debugger suggested here the line that crashes is the following and it is inside the PubSubClient class:
WiFiClient::available()

It is a function already existing at ~/.arduino15/packages/esp8266/hardware/esp8266/2.4.1/libraries/ESP8266WiFi/src/WiFiClient.cpp line 21
Here I paste my code so you can reproduce it and tell me if you have the same problem:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "HX711.h"

#define wifi_ssid "mqtt"
#define wifi_password "testmqtt"

#define mqtt_server "THE.IP.OF.MQTT"
#define mqtt_user "USER"
#define mqtt_password "PSW"

#define humidity_topic "sensor/humidity"
#define temperature_topic "sensor/temperature"
#define weight_topic "sensor/weight"

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  Serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);

  WiFi.begin(wifi_ssid, wifi_password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    // If you do not want to use a username and password, change next line to
    // if (client.connect("ESP8266Client")) {
    if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

long lastMsg = 0;
float temp = 0.0;
float hum = 0.0;
float diff = 1.0;

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 1000) {
    lastMsg = now;

    float newTemp = 456;
    float newHum = 123;

    temp = newTemp+1;
    Serial.print("New temperature:");
    Serial.println(String(temp).c_str());
    client.publish(weight_topic, String(temp).c_str(), true);
  }
}

It works if you comment the initial include
PS: Nothing change if HX711 is include as <...> or "..."

Have you read this?

Assuming that's the library you're using - you haven't specified - there's - https://github.com/olkal/HX711_ADC - which can be installed using Arduino IDE (whereas the one I referred to can not)

Thank you @JaromandaX Now I'm trying to use HX711_ADC. I'll try to adapt my code to this new library and update if it gives me problem


text:
SPST switch - powered from pin output, or voltage regulator
I have a SPST switch and I just want to sense whether it's on or not. I will then turn on/off a relay depending on the state of this switch.
The two options I'm considering are: create a digital out on a pin going to one side of the switch, and read the digital in on another pin off the other side of the switch. Or put 5v from my voltage regulator to the switch, and read a digital in off the other side of the switch.
Would a resistor be necessary for the digital in pin with either of these options?

Why don't you just connect the relay to the switch - no Arduino required?

It is wasting of IO pins to use the digital output pin just to get +5V rail. But both options will work. Don't forget to use pull/up or pull/down resistor, or activate internal pull/up resistor on the sensing pin. When the switch will be open, the input pin is not connected anywhere and will act as antenna, so it might pick up some noise.

I am choosing this as the correct answer because it uses less current when the switch is open.

You could configure one of the digital pins as INPUT_PULLUP and connect one end of the switch to it. The other end of the switch goes to ground. LOW = switch ON, HIGH = switch OFF.
const byte pinNumber = 3;

void setup(){
  pinMode(pinNumber, INPUT_PULLUP);
}

void loop(){
}

Does the pullup resistor draw current continually while the switch is open?

Yes. Approximately 0.1 to 0.25 mA.


text:
DHT22 Hanging Up Entire Program
In the process of learning and working on a larger project, I started by adding an OLED display (128x64, SPI). I wrote a simple script to update every 5 seconds and then display the number of seconds on both the OLED and the Serial port. This worked just fine and I even let it run for more than a day. Then I added a DHT22. This is where the issues started coming in. The Arduino Mega (clone) is powering both devices. I have a 10K resistor across the VCC and signal pins of the DHT22. The code should now update both the OLED and the serial port with the number of seconds and the temperature and humidity. This works, for awhile, and then the whole program freezes for some odd reason. The time before freezing is also at random intervals.
During my research it was suggested to add a 10uF capacitor across the ground and VCC. So I added a 10uF 50v cap and the results are still the same. Originally I had Serial.println(String(..... in the code, but I replaced all that to not use String(). I tried adding Serial.flush() at the end of the display code, but equal results.
Additional research also suggested waiting 30 seconds before trying to read the DHT22. I added this 30 second wait at the end of the setup function, but same results. I've tried checking for NaN, not checking for NaN and nothing has seemed to correct this issue.
I've also tried the program without the OLED. Same results. I've tried the program without the Serial output, but same results.
What is going on here and does anyone have any suggestions as to how to correct this?
Currently this whole thing is rigged up on a breadboard if that helps.
Below is the current code I'm trying:
#include <Arduino.h>

#include <SPI.h>
#include <Wire.h>

#include "DHT.h"

#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

// Adafruit Libraries for the OLED display
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

// Setup the OLED variables
#define OLED_MOSI   9 // D1 on the OLED
#define OLED_CLK   10 // D0 on the OLED
#define OLED_DC    11 // DC on the OLED
#define OLED_CS    12 // CS on the OLED
#define OLED_RESET 13 // RES on the OLED
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

// Global variables
unsigned long currentMillis;
long previousMillis = 0;
#define interval 5000

float humidity;
float fahrenheit;

void setup(){
  // Start the serial port transmission
  Serial.begin(9600);

  // Start the OLED
  display.begin(SSD1306_SWITCHCAPVCC);

  dht.begin();

  // Clear the memory of the OLED
  display.clearDisplay();

  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(1,0);
  display.println("Madgayrah");
  display.display();

  while(millis()<2000);

  display.setCursor(0,16);
  display.println("Arduino");
  display.display();

  while(millis()<5000);
//  while(millis()<30000);

  Serial.println("");
  display.clearDisplay();
}

void loop() {
  currentMillis = millis();

  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    poll_and_display(currentMillis);
  }
}

void poll_and_display(long currentMillis){
    read_dht22();

    Serial.println(previousMillis/1000);

    if(!isnan(humidity) && !isnan(fahrenheit)){
      Serial.print(fahrenheit, 1);
      Serial.print("* ");
      Serial.print(humidity, 0);
      Serial.println("%");
    }

    display.clearDisplay();

    display.setCursor(0,0);
    display.println(currentMillis/1000);
    if(!isnan(humidity) && !isnan(fahrenheit)){
      display.setCursor(0,16);
      display.print(fahrenheit, 1);
      display.print("* ");
      display.print(humidity, 0);
      display.print("%");
    }
    display.display();

    Serial.println("");

    Serial.flush();
}

void read_dht22(){
    humidity = dht.readHumidity();
    fahrenheit = dht.readTemperature(true);

//    while (isnan(humidity) || isnan(fahrenheit)) {
//      unsigned long tempEnteredMillis = millis();
//      while (millis() - tempEnteredMillis < 2500);
//
//      humidity = dht.readHumidity();
//      fahrenheit = dht.readTemperature(true);
//
//      Serial.print("Result from NaN loop = ");
//      Serial.print(fahrenheit, 1);
//      Serial.print("* ");
//      Serial.print(humidity, 0);
//      Serial.println("%");
//    }
}

UPDATE:
After continuing to research on this I discovered that Arduino has a Watchdog Timer, or at least SHOULD have, and this SHOULD detect hang ups and restart the Arduino. So I tried a hardware version of the Watchdog Timer and a software version, but neither one seemed to work and/or correct the hang up/freeze issue. Below are the links I used for the software and hardware versions.
https://circuits4you.com/2018/01/24/tutorial-on-arduino-watchdog-timer-setup/
https://blog.frogslayer.com/creating-an-arduino-watchdog-timer/
I then ran across another post about a different solution that I have implemented and it seems to be working, but I want to give it some more time just to be sure. More updates to come.

Here is the solution. After searching last night I ran across this post https://forum.arduino.cc/index.php?topic=517608.new . Turns out, I was using the Adafruit DHT library and that seems to be what the issue was. I switched over to this https://github.com/markruys/arduino-DHT DHT library and it's been running for some 14 hours now with NO issues. Looking back through the Serial output I don't even see where it returned a NaN, not even once. I'm so excited to have this corrected and hopefully this will help out someone else stuck with this problem.


text:
Is there any way to group variables like group.variable as you can in Java/Delphi
I'm writing a sketch which does some calculations on measured variables, and it's based on a similar program written in Java like
c = A.Ux + B.Uz;
Where A&B have various parameters Ux,Uy,Uz etc
In Delphi this notation can be used either for parameters of classes or variables in a group. Looks like there's something similar in Java. It's a tidy way to organise and manipulate variables when there are lots of them and move them between methods without having huge numbers of arguments.
Is there any way to do this in the Arduino Wiring language? I don't seem to find anything online, but I'm probably phrasing the question wrong.
Thanks in advance, Brian

Wiring is the development platform, not the language. We write our sketches in C/C++. Do you mean struct or class members in C++? (https://www.tutorialspoint.com/cplusplus/cpp_classes_objects.htm)

What you are looking for is a struct:
struct foo {
    uint8_t Ux;
    uint8_t Uy;
    uint8_t Yz;
};

Then:
struct foo A;
struct foo B;

And:
A.Ux = 3;
B.Uz = 48;

int c = A.Ux + B.Uz;

When calling a function you should really use either pass-as-pointer or pass-as-reference to avoid unnecessary copying:
// By Reference
int normal(struct foo &arg) {
    return (arg.Ux + arg.Uy + arg.Uz) / 3;
}

int avg = normal(A);

Or:
// By pointer
int normal(struct foo *arg) {
    return (arg->Ux + arg->Uy + arg->Uz) / 3;
}

int avg = normal(&A);

You can read more about structs here.

Note that pass-as-const-reference is often the best alternative to pass-as-value.

@EdgarBonet Unless you want to modify but discard the values. Maybe do some calculations on them and return the result, but want to (for some reason) modify the actual values as part of the calculation process (maybe you're working iteratively on the values and want to accumulate changes, I dunno...).

Of course there are many specific situations! But that's not my point. My point is that, if you want to optimize a code that mindlessly passes a big struct by value, you know that the caller's copy of the struct should not be modified by the callee. Thus your best bet is to attempt to pass by const reference. If it compiles, you are all good. If it doesn't, that's because the callee is modifying its own copy, and you then know that at least some copying is necessary.

@EdgarBonet Indeed. But if it's getting that complex maybe it's time to consider upgrading to using classes... ;)

ah struct! perfect thanks! I was searching for 'record' as that's what it's called in Delphi....


text:
strtok() command with Serial communicaton
After I take a char* variable from serial communication, I use strtok to split variables with " ". But when I do that it acts like there is a " " after every character. I dont know why. How can I fix this ?
void setup() {
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
  char* a = "The quick brown fox jumped over the lazy dog.";
  char* c = a3;
  char* b;
  b = strtok(c, " ");
  while (b != NULL) {
    Serial.println(b);
    b = strtok(NULL, " ");
  }
}

void loop() {
}

outcome:
The
quick
brown
...

This parsing code works perfectly, until I take it from serial ports. Serial code here, like this:
#include <SoftwareSerial.h>
#define bRSerial 9600
#define bRmY 9600

char vD[45];
int i = 0;

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

void setup() {
  Serial.begin(bRSerial);
  while (!Serial) {
    ;
  }
  mySerial.begin(bRmY);
}

void loop() {
  if (mySerial.available()) {
    //Serial.write(mySerial.read());
    vD[i]=mySerial.read();
    i++;
    if (i = 46) {
      char* a = vD;
      char* b;

      b = strtok(a, " ");
      while (b != NULL) {
        Serial.println(b);
        b = strtok(NULL, " ");
      }
      i=0;
    }
  }
}

outcome:
T
h
e
q
u
i
c
k
b
r
o
w
...

Is there a way to fix this? i need to get it from serial and split on " ".

if ( i == 46 ) {

yep that was it.  :D simply 1 mistake that i couldnt see thanks.

is this how you plan to use it or only a test? it would be simpler to detect the delimiter when it is read

i dont know how to use it simplier.

if this is not only a strtok test, the you do not need strtok. read in char c, and if c == ' ', print vD and reset i to 0 else vD[i] = c

and I do not see where you set the terminating 0 of vD a.k.a. a

only a syntax typo. the condition should be if ( i == 46 ) {
if this is not only a strtok test, the you do not need strtok. read in char c, and if c == ' ', print vD and reset i to 0
and I do not see where you set the terminating 0 of vD a.k.a. a

As @Juraz mentioned, in the case you have a typo. Also I'd have suggestions as one who had spent a while coding reading process in terminal. When you need to read something from a serial port it is good to use the while() loop, instead of if(), so I recommend changing:
while (mySerial.available()) {
  //Serial.write(mySerial.read());
  vD[i]=mySerial.read();
  i++;
  if (i == 46) {
    char* a = vD;
    char* b;

    b = strtok(a, " ");
    while(b != NULL) {
      Serial.println(b);
      b = strtok(NULL, " ");
    }
    i=0;
  }
}

the if is in loop()