text:
shiftOut using SPI isn't working
I made a sample using two of them using Arduino UNO.
So I did that like this:

(There aren't any resistor on that image, but there are 220ohm resistor on every LEDs.)
And uploaded this code.
//1.6us+62.5ns
#include <SPI.h>

#define sbi(port, bit) (port) |= (1 << (bit))
#define cbi(port, bit) (port) &= ~(1 << (bit))

int latchPin = 12;
int clockPin = 13;
int dataPin = 11;

byte data[]={ 0b10101010,0b11001100 };

void _595_out() {
    cbi(PORTB, 4);
    SPI.transfer(data[0] );
    SPI.transfer( data[1] );
    sbi(PORTB, 4);
}

void setup() {
    pinMode(latchPin, OUTPUT);
    pinMode(clockPin, OUTPUT);
    pinMode(dataPin, OUTPUT);

    SPI.setClockDivider(SPI_CLOCK_DIV2);
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);
    SPI.begin();
}

void loop() {
    _595_out();
}

And this worked as I expected. But, when I changed sketch like this,
//1.6us+62.5ns
#include <SPI.h>

#define sbi(port, bit) (port) |= (1 << (bit))
#define cbi(port, bit) (port) &= ~(1 << (bit))
#define CHIPNO 2
int latchPin = 12;
int clockPin = 13;
int dataPin = 11;

byte data[]={ 0b10101010,0b11001100 };

void _595_out() {
    cbi(PORTB, 4);
    SPI.transfer(data[0]);
    SPI.transfer(data[1]);
    sbi(PORTB, 4);
}

void setup() {
    pinMode(latchPin, OUTPUT);
    pinMode(clockPin, OUTPUT);
    pinMode(dataPin, OUTPUT);

    SPI.setClockDivider(SPI_CLOCK_DIV2);
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);
    SPI.begin();
    Serial.begin(9600);
}

void loop() {
    for(unsigned int z = 0; z < 65535; z++) {
        data[0] = z & 255;
        data[1] = (z & 65280) >> 8;
        Serial.println("A");
        Serial.print(data[0]);
        Serial.print("/");
        Serial.println(data[1]);
        Serial.println("B");
        _595_out();
        Serial.println("C");
        delay(500);
    }
}

74HC595s aren't working. Any LEDs aren't on.
Printing Serial works well. Only 74HC595s aren't working.
And Removing all Serial-related thing doesn't solved this problem.
Where did I do wrong?

Did you do a Serial.begin()? Please post the entire sketch that doesn't work.

shiftOut using SPI isn't working - And this worked as I expected. - so SPI is in fact working?

@NickGammon I just changed the loop function like that and added Serial.begin(9600); ath the end of the setup function. Everything except these is same as the first code, so that's why I didn't upload the entire sketch... And shiftOut using SPI is working when I use first code, but isn't working when I change the code as I said.

@NickGammon What I trying to do is changing outputs of 74HC595 every 0.5sec at very fast speed and that's why I'm using SPI. On first code, it's sending same outputs every loop, and it worked so I just changed that code to send different value every loop. But now it doesn't work. That's what it happened :-P

Why are you wanting to drive AY-3-8910 chips with shift registers...? It sounds like you are thinking of having one AY-3-8910 per shift register pair, which is just plain silly. Do some research about how these kind of chips interface to a CPU bus, which is what they are designed to do.

http://playground.arduino.cc/Main/AY38910 ?

@Majenko Umm...as I know, AY-3-8910 uses 8bit bus for input/output(see this datasheet 36, 41, 43 page), and that's why I am thinking of having one AY-3-8910 per shift register pair. Can I get any information of that research? I'm just a noob to here and don't know about that :-(

The clue here is the word bus. All the AY-3-8910 chips can share the same bus. The only thing that needs to be unique is the equivalent of the address decoding (A8 and /A9 on the chip).

@MikaelPatel Yeah, but I am planning to control 10 of them, so I used 74HC595, just like this. And that above thing is for testing and isn't working :-(

@Majenko Wait for a sec, I couldn't understand yet and got "shock and awe". Can you give me a detail?

An AY-3-8910 chip is only active when A8 is HIGH and A9 is LOW. By only having one chip active at a time all the other signals can be shared. That's 8 data signals, plus BDIR and CLOCK that are common. That's 10 pins for the bus, and a number of pins for selecting chips. That could be one pin attached to A8 and another attached to A9, which gives you 4 AY-3-8910 chips on 12 pins. Add a 2-to-4 decoder in place of the direct A9 connection and you get 8 chips off 13 pins. Change that to a 3-to-8 decoder and you get 16 chips off 14 pins. The Arduino can do that without needing any shift registers.

@Majenko The reason why I paired one shift register per AY-3-8910 is to control multiple chip with different data at one loop. And I'm trying to control AY using two pins, BC1 and BDIR, which are also controlled by another 74HC595 lane(not a paired shift registor lane), so I can control 10 AY-3-8910 using only 6 pins of Arduino. So maybe I can't use that way right now.

Anyway, I really want to solve this shift out problem because I want to use this on another project.

Where does  AY-3-8910 comes from in the comments? There is no mention of it in the question.

@NickGammon Actually it was, but i thought that isn't necessary on my question so i removed that. Sorry for the confusion...

int latchPin = 12;

You use pin 12 as the latch pin. Once you activate SPI the hardware takes over control of the pins MOSI, MISO and SCK. Pin 12 is MISO and thus attempting to change it in your code will have no effect.
You should use some other pin as the latch pin (pin 10 is often used).

And shiftOut using SPI is working when I use first code

shiftOut is a software-based method of clocking out bits. It doesn't use hardware and thus it doesn't take control of pin 12.

Note: Answered originally on the Arduino Forum


text:
Liquid Crystal LCD Display Prints f in all rows and columns
The problem is that the Liquid Crystal LCD display only prints "f" on every row and every column.
When I tell it to print something, then the display prints "f" on every square(row, column) for a brief second, then each square shows three white bars stacked up parallel to each other (quite like an "=" sign except that there's one more bar on top").
I am also using a tmrpcm library, so I'm guessing that interrupts might have to do with this, but I have no idea how to solve the problem.
The link to the tmrpcm library is as follows: https://github.com/TMRh20/TMRpcm
Thank you so much. I need to get this done by tomorrow 8 A.M., so I'm pretty desperate.
#include <LiquidCrystal.h>
#include <SD.h>                      // need to include the SD library
//#define SD_ChipSelectPin 53  //example uses hardware SS pin 53 on Mega2560
#define SD_ChipSelectPin 10  //using digital pin 4 on arduino nano 328
#include <TMRpcm.h>           //  also need to include this library...

TMRpcm tmrpcm;   // create an object for use in this sketch
char mychar;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

volatile int pauseOnOff;

void setup(){

  tmrpcm.speakerPin = 9; //11 on Mega, 9 on Uno, Nano, etc

  if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can be initialized:
    Serial.println("SD fail");
    return;   // don't do anything more if not
  }
  else{
    Serial.println("success!");
  }

  tmrpcm.play("Closer.wav");

  lcd.begin(16, 2);

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

void loop(){

}

If the problem is “something to do with interrupts” you will need to show some code for the problem to be diagnosed.  Please edit your question to include a Minimal, Complete, and Verifiable example of code.   On the other hand, it may be a wiring problem.  In that case, edit your question to include a circuit diagram and parts list.

Thank you, but I can confirm that the wiring is not the problem by excluding the tmrpcm library and confirming that the display works correctly. Furthermore, I do not know how the tmrpcm library works...I've been studying for it for a few weeks but I still don't grasp how it works.

I don't know the source of the problem, but here are a few things that might help diagnose where the problem begins or what it is due to.
(a) To track execution progress, and detect which statement, if any, ruins LCD operation:  Create a routine to display current line number in code to LCD and Serial; make a macro ss to use for invoking that routine; invoke the macro before and after each line containing a tmrpcm action by calls like ss;.  See following example.
void shoLine(int line) {
  Serial.println(line);
  lcd.home ();     // Set cursor to 0,0
  lcd.print(line);
  lcd.print(' ');
  delay(200);  // /Delay long enough to see stuff appear
}
#define ss shoLine(__LINE__)

Note:  Move lcd.begin(16, 2); to be the first statement in setup() when using this method of debugging.
(b) If you find that the first few LCD calls are ok and then LCD output stops working, try turning off interrupts during LCD output.  That is, put a cli() or noInterrupts() call before an lcd.print(), and an sei() or interrupts() after it, and see if it then works.  If so, that might serve as a last-ditch workaround.  (I don't know whether LCD output routines use any interrupts; I doubt they do; but if they do, this method won't work.)
(c) If the LCD doesn't display correctly at all, even before the first tmrpcm action, it may be that the combination of tmrpcm with other code is using too much memory.  Carefully check the memory-usage reports when you compile your sketch.

source: Stack Exchange

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

sort: votes


text:
Relay for controlling a water pump motor
I want to switch on and off a motor with arduino, used for pumping water. I need to have a idea which relay could be used with arduino.
Here is a photo of a similar motor:

In this case an image does not tell a thousand words. In order to get a proper answer, we need to know the specifics of this pump. Voltage? Amperage? AC / DC? How does it work? Perhaps a datasheet?

You need a relay that can handle the amount of current the motor uses. So check the Amps ratings of the motor and of the relay.

@Gerben it must handle Starting current. I think some small opto-isolated relay module and big contactor would be the best.

A relay must also be spec'ed for the voltage it will be switching, to prevent arcing and burning its contacts when they make and break.

Fairly cheap and quite reliable relays which operate at 5V (5mA to switch closed/open) can be had at a decent price. Mine have an upper limit of 10A, either 250VAC or 30VDC.

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


text:
Convert a Double to an UnSigned Char
So, I'm working on RedBear Blend Micro V 1.0, and I must use the function:
ble_write(Serial.read());

To read some input from the serial monitor(Input being stuff I type in the Serial Monitor) and send it via bluetooth.
It works perfectly this way!
Now what I need to do is create a random double data type number, and insert it in the place of Serial.read()
Read This:
ble_write
Syntax:
    void ble_write(unsigned char data);
  ble_write sends a single byte data to the BLE Central.
So, can you please help me, to:
1)Generate a random double
2)Send it using the ble_write() function?
For a full list of function sin the ReadBear Library click on the link:
https://github.com/RedBearLab/nRF8001

If it's random then why not just send random unsigned chars?

@IgnacioVazquez-Abrams Thanks for the suggestion but the thing is, for now I want to send a definite NUMBER via the ReadBear BlendMicro, but later, instead of this number, i will be sending data from an ECG Sensor, the data from the ecg sensor is a Double..Dont worry Ive checked the ECG part

Edit: Chris Stratton rightfully points out that the question is
about a double, not a float:

a float is four bytes in every platform I know about, as per the
IEEE-754 standard
a double is eight bytes in almost all platforms, with the notable
exception of AVR: the AVR double is highly non-standard, four bytes
long, and essentially equivalent to float

Most, but not all Arduinos, are AVR-based.
In the following I assume you are talking about AVR doubles, i.e.
floats. If this is not the case, then just replace the array of 4 bytes
by an array of 8 bytes.

Original answer:
A float is four bytes, so it is somewhat equivalent to an array of
four unsigned chars, i.e. to unsigned char[4]. You can use this
equivalence with an union. For example, the following function will
send a float byte by byte:
void ble_write_float(float x)
{
    union {
        float f;
        unsigned char c[4];
    } data;

    data.f = x;
    ble_write(data.c[0]);
    ble_write(data.c[1]);
    ble_write(data.c[2]);
    ble_write(data.c[3]);
}

Notice that this will send the bytes in whatever is the natural order of
the sending processor. If it's an AVR (like most Arduinos), this will be
LSB (least significant byte) first. You have to make sure that this is
what the receiver expects.
Following Ignacio Vazquez-Abrams' suggestion, for sending a random float
you could just send four random bytes. However, it may be wiser to have
an idea of the random distribution you want for your float, and use
things like random() and map() to achieve that distribution. Using
four random bytes, you get a very wide distribution (all the possible
floats are equally likely) which includes weird things like denormals,
infinities and NaN (literally meaning “not a number”).

The question asks about a double while you answer with regard to a float so it would be helpful to mention that on the ATmega based Arduinos they are equivalent, however on some other varieties they are not.

@ChrisStratton: Thanks for pointing this out. I amended the answer.


text:
Detector Sensor Not Detecting
I have a problem with my Microwave Sensor V2.0 Contraption.
When I turn it on it doesn't detect anything.
The LED-light is also not flickering so I know it probably has something to do with that, but I don't know where to begin with tweaking it.
Here below is the Code:
#include <SPI.h>
#include <MsTimer2.h>           // Timer interrupt function library
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3D
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

int pbIn = 0;                    // Define interrupt 0 that is digital pin 2
int ledOut = 13;                 // Define the indicator LED pin digital pin 13
int number = 0;                  // Interrupt count
volatile int state = LOW;        // LED state, initially off (LOW)

void setup() {
    Serial.begin(9600);
    pinMode(ledOut, OUTPUT); // Set LED pin as output
    attachInterrupt(pbIn, stateChange, FALLING);
    // Set interrupt function: triggered on FALLING edge (pin 2 goes from HIGH to LOW)
    MsTimer2::set(3000, Handle); // Timer interrupt: call Handle() every 3000ms (3 seconds)
    MsTimer2::start(); // Start timer interrupt

    display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
    display.clearDisplay();
    display.display();
}

void loop() {
    // Display "status" and the current number on the OLED
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(0, 5);
    display.println("status: ");

    display.setTextSize(3);
    display.setTextColor(WHITE);
    display.setCursor(0, 30);
    display.println(number);

    display.display();
    display.clearDisplay();
    delay(10);
}

void stateChange() {
    // Interrupt service function: increment the counter when triggered
    number++;
}

void Handle() {
    // Timer service function: reset the counter and toggle the LED state
    number = 0;               // Reset counter
    state = !state;           // Toggle state (HIGH to LOW, or LOW to HIGH)
    digitalWrite(ledOut, state); // Set the LED to the toggled state
}

Here is a picture of the little contraption:
I don't have a sketch for tinytronics, because some components I can't find on the website.
Sorry if the pictures might be a little too big.
And for clarification The LED-light is this yellow light on the back of the Microwave Sensor V2.0
I thank you for taking your time looking at this.

Your variable number should be declared volatile too

I did that but it hasn't fixed it.

The wire of of the 5v should've been the d2pin and vice versa. The blueprint I got it off made a error. I fixed it

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


text:
Integer corruption
I use a sensor to measure the temperature. This is returned as float. I feed this float using typecasting (int) to a blink function. This works fine.
But the next is step is using this same unchanged integer in a struct and send it over 433MHz using RadioHead.
Here the integer is no longer an integer and it never gets sent.
When I hard code the sensor measurement value, it works. When I hard code the value in the struct it works. When I hard code the value anywhere it works.
My assumption is: when the blink works it must be an integer. When sending a hard coded integer works it must also send the measured value confirmed to be an integer. What am I missing here?
The chip is an ATtiny85
The sensor is a DS18B20
TinyHead, my light RadioHead version: https://gitlab.com/thijsvanulden/TinyHead
This is the Logic Analyzer view of what happens measured on the Data pin of the 433MHz transmitter. So something is happening at least. I can't find an Analyzer 'plugin' to translate the message coded in RadioHead, it's not Manchester encoding as it seems.

Memory Usage -> http://bit.ly/pio-memory-usage
DATA:    [========  ]  75.8% (used 388 bytes from 512 bytes)
PROGRAM: [========= ]  86.4% (used 7080 bytes from 8192 bytes)

#include <Arduino.h>
#include <util/delay.h>
#include <OneWire.h>
#include <RH_ASK.h>
#include <DallasTemperature.h>

#define TICKLE_ID 0

#define ONE_WIRE_BUS 2

#define RADIOHEAD_BAUD 2000
#define RADIOHEAD_TX_PIN 1
#define RADIOHEAD_RX_PIN -1

#define LEDPIN 0

struct tickle {
  uint16_t id = TICKLE_ID;
  uint16_t value1;
  uint16_t value2;
};

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
RH_ASK driver(RADIOHEAD_BAUD, RADIOHEAD_RX_PIN, RADIOHEAD_TX_PIN);

void blink(int repeat) {
  for (int i = 0; i < repeat; i++) {
    digitalWrite(LEDPIN, HIGH);
    _delay_ms(100);
    digitalWrite(LEDPIN, LOW);
    _delay_ms(100);
  }
}

void senddata(float temperatuur) {
  blink((int) temperatuur); // this always works
  struct tickle package; // make a Tickle package
  package.id = TICKLE_ID; // hard-coded device ID
  package.value1 = 0; // any positive int up to 2^16
  package.value2 = temperatuur * 100; // any positive int up to 2^16
  driver.send((uint8_t *)&package, sizeof(package));
  driver.waitPacketSent(); // wait for it ~Barney
}

void setup() {
  pinMode(LEDPIN, OUTPUT);
  digitalWrite(LEDPIN, HIGH);
  sensors.begin();
  driver.init();
  _delay_ms(100);
  digitalWrite(LEDPIN, LOW);
}

void loop() {
  sensors.requestTemperatures();
  _delay_ms(100);
  senddata(sensors.getTempCByIndex(0)); // hard coded 17.07 works
  _delay_ms(10000);
}

Changes made as suggested by @Jot
void senddata(float temperatuur) {
  temperatuur = (uint16_t) temperatuur;
  blink(temperatuur);
  struct tickle package; // make a Tickle package
  package.id = (uint16_t) TICKLE_ID; // hard-coded device ID
  package.value1 = (uint16_t) 0; // any positive int up to 2^16
  package.value2 = (uint16_t) 100; // any positive int up to 2^16

  blink(sizeof(package));
  driver.send((uint8_t *)&package, sizeof(package));
  driver.waitPacketSent(); // wait for it ~Barney
}

Working code, the end result
You may need to skip the Powernap code, it's a sleep library for ATtiny85. And I use the TinyHead library for 433MHz. The OneWire interaction with the sensors is 'borrowed' from http://www.nerdkits.com/forum/thread/2849/ so please send the beer and kudo's there.
#include <Arduino.h>
#include <util/delay.h>
#include <OneWire.h>
#include <RH_ASK.h>
#include <powernap.h>

#define TICKLE_ID 0
//
#define ONE_WIRE_BUS 2
//
#define RADIOHEAD_BAUD 2000
#define RADIOHEAD_TX_PIN 1
#define RADIOHEAD_RX_PIN -1

#define LEDPIN 0

struct tickle {
  uint16_t id = TICKLE_ID;
  uint16_t value1;
  uint16_t value2;
};

Napper napper;
OneWire TemperatureSensor(2);
RH_ASK driver(RADIOHEAD_BAUD, RADIOHEAD_RX_PIN, RADIOHEAD_TX_PIN);

void blink(int repeat) {
  for (int i = 0; i < repeat; i++) {
    digitalWrite(LEDPIN, HIGH);
    napper.delay(100);
    digitalWrite(LEDPIN, LOW);
    napper.delay(100);
  }
}

void senddata(float temperatuur) {
  blink((int) temperatuur);
  struct tickle package; // make a Tickle package
  package.id = TICKLE_ID; // hard-coded device ID
  package.value1 = 0; // any positive int up to 2^16
  package.value2 = temperatuur * 100; // any positive int up to 2^16

  blink(sizeof(package));
  driver.send((uint8_t *)&package, sizeof(package));
  driver.waitPacketSent(); // wait for it ~Barney
}

void setup() {
  pinMode(LEDPIN, OUTPUT);
  digitalWrite(LEDPIN, HIGH);
  driver.init();
  napper.setup();
  napper.delay(100);
  digitalWrite(LEDPIN, LOW);
}

void loop() {
  byte i;
  byte data[12];
  int16_t raw;
  float celsius, fahrenheit;

  TemperatureSensor.reset();       // reset one wire buss
  TemperatureSensor.skip();        // select only device
  TemperatureSensor.write(0x44);   // start conversion

  delay(1000);                     // wait for the conversion

  TemperatureSensor.reset();
  TemperatureSensor.skip();
  TemperatureSensor.write(0xBE);   // Read Scratchpad
  for ( i = 0; i < 9; i++) {       // 9 bytes
    data[i] = TemperatureSensor.read();
  }

  // Convert the data to actual temperature
  raw = (data[1] << 8) | data[0];
  celsius = (float)raw / 16.0;
  napper.delay(100);
  senddata(celsius);
  napper.napminutes(1);
}

Which arduino board do you use? The OneWire and DallasTemperature require some memory, but the RadioHead requires a lot of memory.

@Jot - how is that relevant? if senddata(17.07); works as intended, but senddata(sensors.getTempCByIndex(0)); does not?

what sensor are you using? .... what format is the returned data?

Is it possible you think you are sending three bytes of data while you might actually be sending six bytes of data.

@Thijs, still using the attiny85? or is it a secret and you don't you want to tell us which arduino board you use? When you use a non-standard arduino board, then I would like to know which core you use. Perhaps that is a secret as well? There are issues and notes about many problem with the attiny85 and RadioHead. Have you read: "Caution: we have not had good success building RH_ASK sketches for ATTiny 85" on this page: https://www.airspayce.com/mikem/arduino/RadioHead/ The RadioHead uses a lot more memory than the old VirtualWire. I would not even recommend the RadioHead for an Arduino Uno.

What do you mean by “the integer is no longer an integer and it never gets sent”? What makes you believe an integer can be anything but an integer? What are the exact symptoms you observe?

Yes, I use an ATtiny85. It is the Dallas sensor DS18B20. The returned format is float. @Jot sry forgot to mention I use the ATtiny85. I have 17 sensors running with this chip and using TinyHead, my light version of RadioHead, no problems there. VirtualWire does not provide the same functionality and is deprecated for years with the developer referring to RadioHead.
The exact symptoms are that the RadioHead library does not send out the message. In depth debugging is really hard with an ATtiny85 so can't really tell you more at the moment but I'm open to ideas.
@st2000 please elaborate?

@st2000 I changed my code so the LED blinks the package size and sizeof(package) returns 6.

...yes, this is because your structure is made of 3 uint16_t values.  Then you force the code to consider it as uint8_t values.  Of which there is enough memory set aside for 6 such values.  I was wondering if this was what you were expecting to send?  Or if this was why you do not think you are sending the correct data.

...also, as other's here point out, the Arduino paradigm has been ported to many many different processors.  And some of the ports are not 100% functional.  In fact, it can easily be said that not 100% of all Arduino programs run on 100% of all "so called" Arduino platforms.

Please also add a link in your question to TinyHead. I can't see the problem. Therefor you have to be able to get closer to the problem with other output. Can you add a serial port, a display, or a led? Perhaps you can blink a led 17 times for 17 degrees in the function senddata and check if you see any difference for a constant or the ds18b20. By the way, I have stripped down the RadioHead for myself, saving a lot of ram. That makes it possible to use it with an arduino uno. I doubt if the TinyHead for a attiny85 is tiny enough so it can still use the ds18b20 libraries.

@st2000 where do I force the code to consider it uint8? What would be the alternative?

@Jot I’ve used an LED to signal the temparature and its read fine. I also used it to signal the package size for the transmission and it’s 6 bytes. I will try to connect my logic analyzer later. Yes is all works with a constant. Thats the problem, it always works with any integer unless the integer comes from the sensor, even when I verify this interger is fine by blinking the LED.

@Thijs I think I did not read it very well and was rude, my apologies. Can you do a test: fool the compiler to make it think that getTempCByIndex is used, but send a constant. In the function senddata: convert it: uint16_t t = temperature; get rid of it: t /= 10000; add a constant: t += 1789; fill the package: package.value2 = t;. Linking the getTempCByIndex function into the binary might be too much for the ram usage.

@Jot no problem. I've made the changes and nothing is transmitted but I do see the right temperature signaled by the blink function. On the logic analyzer there is a signal again, but I still cant decode it.

I'll try to use another more light library or write my own oneWire stuff so I can free up some memory.

Casting values is like telling the compiler "don't mind what these memory locations were, now I want you to treat them differently".  So, you used 6 bytes of memory to store 3 uint16_t values.  Then you told the compiler to look at the 6 bytes of memory as if they were uint8_t values.   You further cemented your intentions by specifying the "size" of the values.  That is, the size of function returned that you had used 6 bytes of memory for the storage of the 3 uint16_t variables or, as you casted them, 6 uint8_t variables.

@st2000 I still do not know where I tell the compiler to look at the 6 bytes of memory as if they are uint8_t, could you please specify the exact line where I do this? As far as I know I just declare a variable to be a 16 bit long integer and never change that.

In this line:   driver.send((uint8_t *)&package, sizeof(package));

I can’t believe I missed that, not sure what happens for the sensors that work fine.. at the receiving end the 6 int8’s are interpreted as 3 int16’s again

It works when I do not use a heavy DallasTemperature library but directly use OneWire as seen here: http://www.nerdkits.com/forum/thread/2849/, so I think it was indeed the memory issue @Jot mentioned..

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


text:
Manchester 433MHz Nano to ATTiny85
My transmitter is a Nano, the receiver is a Tiny85.
I use a Logic Analyzer to check if stuff is moving, I can clearly see data coming in at the receiver.
The receiver does not 'decode' the data, man.receiveComplete() is never True so in the end nothing happens.
I think the problem may be the difference in clock speeds, there are some things I have tried. The Nano is sending every second, in the logic analyzer I can see this come in every second so he is 'right on time'.
But I am not so sure about the ATTiny85..

ATTiny85
Tiny Core
8MHz (burned bootloader 3x)

It is still to fast, counting to 3 is not working ok..
Bootloader burning log
    /home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/bin/avrdude -C/home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/etc/avrdude.conf -v -v -pattiny85 -cstk500v1 -P/dev/ttyUSB0 -b19200 -e -Uefuse:w:0xFF:m -Uhfuse:w:0xD7:m -Ulfuse:w:0xE2:m

avrdude: Version 6.3, compiled on Dec 16 2016 at 12:32:01
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/etc/avrdude.conf"
         User configuration file is "/home/thijs/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATtiny85
         Chip Erase delay              : 400000 us
         PAGEL                         : P00
         BS2                           : P00
         RESET disposition             : possible i/o
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    12     4    0 no        512    4      0  4000  4500 0xff 0xff
           flash         65     6    32    0 yes      8192   64    128 30000 30000 0xff 0xff
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: PAGEL and BS2 signals not defined in the configuration file for part ATtiny85, using dummy values
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x1e930b (probably t85)
avrdude: erasing chip
avrdude: PAGEL and BS2 signals not defined in the configuration file for part ATtiny85, using dummy values
avrdude: reading input file "0xFF"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0xFF:
avrdude: load data efuse data from input file 0xFF:
avrdude: input file 0xFF contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.02s

avrdude: verifying ...
avrdude: 1 bytes of efuse verified
avrdude: reading input file "0xD7"
avrdude: writing hfuse (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xD7:
avrdude: load data hfuse data from input file 0xD7:
avrdude: input file 0xD7 contains 1 bytes
avrdude: reading on-chip hfuse data:

Reading | ################################################## | 100% 0.02s

avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0xE2"
avrdude: writing lfuse (1 bytes):

Writing | ################################################## | 100% 0.02s

avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xE2:
avrdude: load data lfuse data from input file 0xE2:
avrdude: input file 0xE2 contains 1 bytes
avrdude: reading on-chip lfuse data:

Reading | ################################################## | 100% 0.02s

avrdude: verifying ...
avrdude: 1 bytes of lfuse verified

avrdude done.  Thank you.

/home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/bin/avrdude -C/home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/etc/avrdude.conf -v -v -pattiny85 -cstk500v1 -P/dev/ttyUSB0 -b19200

avrdude: Version 6.3, compiled on Dec 16 2016 at 12:32:01
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/thijs/.arduino15/packages/arduino/tools/avrdude/6.3.0-arduino8/etc/avrdude.conf"
         User configuration file is "/home/thijs/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATtiny85
         Chip Erase delay              : 400000 us
         PAGEL                         : P00
         BS2                           : P00
         RESET disposition             : possible i/o
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    12     4    0 no        512    4      0  4000  4500 0xff 0xff
           flash         65     6    32    0 yes      8192   64    128 30000 30000 0xff 0xff
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: PAGEL and BS2 signals not defined in the configuration file for part ATtiny85, using dummy values
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.04s

avrdude: Device signature = 0x1e930b (probably t85)

avrdude done.  Thank you.

high level

zoomed

I have tried to use the Analyzer options for Manchester encoding in Saleae Logic but I do not know how to configure it right..
Receiver Code

#include <Manchester.h>
#include <TinyWireM.h>                  // I2C Master lib for ATTinys which use USI
#include "LiquidCrystal_attiny.h"

LiquidCrystal_I2C lcd(0x27,16,2);

#define RX_PIN 1
uint8_t moo = 1;
#define BUFFER_SIZE 4
uint8_t buffer[BUFFER_SIZE];

int curs = 0;

void setup() {
//  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
  delay(1000);
  pinMode(4, OUTPUT);
  lcd.init();
  lcd.backlight();
  lcd.home ();
  lcd.setCursor (0, 0);
  lcd.print("Start ");
  man.setupReceive(RX_PIN, MAN_1200);
  man.beginReceiveArray(BUFFER_SIZE, buffer);
  count();
}

void loop() {
  if (man.receiveComplete()) {
    uint8_t receivedSize = 0;

    //do something with the data in 'buffer' here before you start receiving to the same buffer again
    receivedSize = buffer[0];
    for(uint8_t i=1; i<receivedSize; i++)
      Serial.write(buffer[i]);

//    pushtolcd(".");
    lcd.print(".");
    Serial.println();

    man.beginReceiveArray(BUFFER_SIZE, buffer);
    moo = ++moo % 2;
  }
}

void pushtolcd(String text) {
  lcd.home ();
  lcd.setCursor (0, curs);
  curs++;
  lcd.print(text);
  delay(500);
}

void count() {
  for (int i=0; i<3; i++) {
    lcd.print(i);
    delay(1000);
  }
};

Sender code
#include <Manchester.h>

#define TX_PIN  5  //pin where your transmitter is connected
#define LED_PIN 13 //pin for blinking LED

uint8_t moo = 1; //last led status
uint8_t data[20] = {11, '1','2', '3', '4', '5', '6', '7', '8', '9','1','2','3','4','5','6','7','8','9'};

void setup()
{
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, moo);
  man.workAround1MhzTinyCore(); //add this in order for transmitter to work with 1Mhz Attiny85/84
  man.setupTransmit(TX_PIN, MAN_1200);
}

uint8_t datalength=2;   //at least two data
void loop()
{

  data[0] = datalength;

  man.transmitArray(datalength, data);
  moo = ++moo % 2;
  digitalWrite(LED_PIN, moo);

  delay(800);
  datalength++;
  if(datalength>18) datalength=2;
}


text:
Reading Reveive Hold Register from USART in SPI Mode on Arduino Due
Sending with this function here works fine:

uint16_t usart0spiTransfer16(uint16_t spiMessage16) {
    uint16_t sdo = 0;
    byte firstByte = spiMessage16;
    byte secondByte = (spiMessage16 >> 8);
    while (((USART0->US_CSR  >> 1) & 1) == 0);
    digitalWrite(SS, LOW);
    USART0->US_THR = secondByte;                //write to USARTO Transmit Hold Register

    //this byte is returned twice
    secondByte = USART0->US_RHR;                //read from USART0 Receive Hold Register
    while (((USART0->US_CSR  >> 1) & 1) == 0);  //TXRDY: Transmitter Ready
    USART0->US_THR = firstByte;

    //trying to read a second time gives me the same value as before
    firstByte = USART0->US_RHR;

    while (((USART0->US_CSR  >> 9) & 1) == 0);
    digitalWrite(SS, HIGH);

    sdo = (firstByte << 8 ) | (secondByte & 0xFF);
    return sdo;
}

and when i wait for RXRDY after secondByte = USART0->US_RHR; with while (((USART0->US_CSR  >> 0) & 1) == 0); i will stay there forever since it does not change
how do i read the registers value for the second time?


text:
How do I Read and Write data from a USB stick?
Hello I have an Arduino Uno and I salvaged a USB port from an old computer. The USB port has 4 pins on it and it accepts USB sticks. I was wondering if it is possible to connect it to my Arduino so my Arduino can load data from files on the USB. I don't want to go out and buy a shield but I don't mind using libraries. Is it possible to read and write data from a USB stick with Arduino?

Usb OTG mass storage library. Good luck

Requires an USB Host Shield. The UNO can only work as device otherwise. Talking to a stick requires host role.

The Uno does not have any USB host or OTG capabilities on its own, and bit banging it is not easy. A USB Host shield, or a better microcontroller is needed.


text:
Arduino Micro Cannot get Interrupt 6 work on PIN 7
After finding out about the situation with pin7 from this tutorial:
https://forum.sparkfun.com/viewtopic.php?f=32&t=35847
    void setup(){

    EICRB |= (1<<ISC60)|(0<<ISC61); // sets the interrupt type for EICRB (INT6).
                                  // EICRA sets interrupt type for INT0...3

    /*
    ISCn0  ISCn1   Where n is the interrupt. 0 for 0, etc
      0      0   Triggers on low level
      1      0   Triggers on edge
      0      1   Triggers on falling edge
      1      1   Triggers on rising edge
    */
EIMSK |= (1<<INT6); // activates the interrupt. 6 for 6, etc

void loop(){
//do other things here
}

ISR(INT6_vect) {
  // interrupt code goes here
  }

I have set:
EICRB |= (0<<ISC60)|(0<<ISC61);

Because I need it to be triggered on LOW.
I could still not get it work on the micro. IF I use the pin as regular input pin I can clearly see LOW/HIGHs on pin 7 with digitalread.
I have a sensor attached there which goes LOW in case it is triggered.
I wonder if anybody knows what else can I try to get it work. I already hardwired everything in my circuit board, there are no more free interrupts and no way to change them.

ORing with 0 does nothing.

And did you define an ISR?

I've used following code and loopback from pin 8 to pin 7:
// loopback:  pin 8 -> pin 7

void setup() {
  pinMode(7, INPUT_PULLUP);
  pinMode(8, OUTPUT);
  pinMode(LED_BUILTIN_TX, OUTPUT); // to see pin 8 logic level on TX led
  pinMode(LED_BUILTIN, OUTPUT); // toggled by ISR

  EICRB |= _BV(ISC60);  // Triggers on edge
  EIMSK |= _BV(INT6);   // activates the interrupt
}

ISR(INT6_vect) {
  PINC = _BV(PC7);  // toggle led 13 (@ PC7)
}

void loop() {
  digitalWrite(8, HIGH);
  digitalWrite(LED_BUILTIN_TX, HIGH);

  delay(500);
  digitalWrite(8, LOW);
  digitalWrite(LED_BUILTIN_TX, LOW);
  delay(500);

}

And it works perfectly. Only problem I can imagine is to figure out correctly which pin is really 7 as label is on the right side of pin (not under nor left).


text:
Unexpected behaviour of blinking LED code
I'm new to Arduino so this may be a really silly doubt but I'm not finding an explanation for it anywhere online. I first uploaded this code (to blink 5 LEDs) on my Arduino Uno :
 void setup(){
 pinMode(12, OUTPUT);
 pinMode(11, OUTPUT);
 pinMode(10, OUTPUT);
 pinMode(9, OUTPUT);
 pinMode(8, OUTPUT);
}

void loop(){
digitalWrite(12, HIGH);
delay(1000);
digitalWrite(12, LOW);
delay(1000);
digitalWrite(11, HIGH);
delay(1000);
digitalWrite(11, LOW);
delay(1000);
digitalWrite(10, HIGH);
delay(1000);
digitalWrite(10, LOW);
delay(1000);
digitalWrite(9, HIGH);
delay(1000);
digitalWrite(9, LOW);
delay(1000);
digitalWrite(8, HIGH);
delay(1000);
digitalWrite(8, LOW);
delay(1000);
}

The 5 LEDs glowed brightly. But when I uploaded the following code (using an if statement to reduce the size of the previous one), the LEDs glowed dimly.
int LEDpin = 13;
void setup(){
pinMode(LEDpin, OUTPUT);
}

void loop(){
digitalWrite(LEDpin, HIGH);
delay(1000);
digitalWrite(LEDpin,LOW);
delay(1000);
if(LEDpin >= 8){
LEDpin--;
} else {
  LEDpin = 8;
  }
}

Also, when I just typed the if statement without the else part, nothing happened after the LED at pin 8 had glowed on and off. Can someone please tell me why the LEDs glowed dimly in the second one and why nothing glowed after LED 8 when I skipped the else part?

The problem with your code is that:
you have not initialised all the LED pins as output. Only pin 13 is initialised as output.
So, initialise all the pins to output. A correct code would look like this:
int LEDpin = 13;
void setup(){
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
}

void loop(){
digitalWrite(LEDpin, HIGH);
delay(1000);
digitalWrite(LEDpin,LOW);
delay(1000);
if(LEDpin >= 8){
LEDpin--;
} else {
  LEDpin = 12;
  }
}

LEDpin needs to be assigned to 12 in both the initial declaration and in the else statement (and not 13 and 8 respectively). Otherwise, the first loop will try to write to pin 13 which is not initialised as an OUTPUT in setup(), and finally will only write to pin 8, instead of continuing to cycle from 12 to 8...

I see that you have (correctly) edited your answer for the else statement, however, the initial declaration of LEDpin is still set to 13, when it should be 12. So, the first line should be int LEDpin = 12; What will happen the first time the loop() is executed?

As Abhishek mentioned in his answer is correct, but the better way is to use for loops while dealing with many led's.
Let's say you have led's connected from pin 2 to 8.
int pin = 2;
void setup()
{
   for (Pin = 2; Pin < 8; Pin++)
   {
     pinMode(Pin, OUTPUT);
   }
}
void loop()
{
   for (int Pin = 2; Pin < 8; Pin++)
   {
     digitalWrite(Pin, HIGH);
     delay(1000);
     digitalWrite(Pin, LOW);
     delay(1000);
    }
}

As Abhishek Jain explained, the pin's need to be initialised for OUTPUT.
However there is another error.
The code in loop() counts down to 8, once, flashing the LEDs, but then only lights an LED on pin 8 because it always goes through the else which maintains LEDpin's value as 8. LEDpin needs to be reset to 12, after it passes 8.
Better code might be
int LEDpin = 12;
void setup(){
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
}

void loop(){
  digitalWrite(LEDpin, HIGH);
  delay(1000);
  digitalWrite(LEDpin,LOW);
  delay(1000);
  if(LEDpin >= 8){
    LEDpin--;
  } else {
    LEDpin = 12;   // <---- start with the first LED again
  }
}

For what its worth, I wouldn't do the code this way. I would write something using for loops, like:
const int firstLED = 8;
const int lastLED = 12;
int LEDpin;

void setup() {
  for (LEDpin = firstLED; LEDpin <= lastLED; ++LEDpin) {
     pinMode(LEDpin, OUTPUT);
  }
}

void loop() {
  for (LEDpin = firstLED; LEDpin <= lastLED; ++LEDpin) {
    digitalWrite(LEDpin, HIGH);
    delay(1000);
    digitalWrite(LEDpin,LOW);
    delay(1000);
  }
}

@ayerhs7 - Initializing all the pins to OUTPUT is necessary, but not sufficient. If you want all of the LEDs to blink repeatedy, and not just once when the Arduino is reset, LEDpin must be reset to 13, which is missing from the answer that you have accepted. IMHO, for clarity, you should either update your answer to reflect the fact that you only need the LED on pin 8 to blink, or comment that the answer you have accepted does not solve the problem, or maybe explain why you accepted it.


text:
Shift register with relay board behaving erratically
I have a nodemcu connected to a shift register(https://www.amazon.de/gp/product/B07CHBYR7Z) to control an 8 channel relay board (https://www.amazon.de/Elegoo-Relaismodul-Optokoppler-Arduino-Raspberry/dp/B01M61VVGV). The realy board is connected to various pumps. The setup itself works quite well normally. However after some switching cycles or when I manually bridge the relay to activate a pump the shift register suddenly either doesnt react at all. Switches on everything or is off by one. I read that it might be possible that I have flow back from the relay coil so I added the diode over the gnd and vcc pin of the relay board. However that didnt help either. Can anybody tell me what I am doing wrong? I hope the schematic is legible.

Can you explain what you are doing when you say "manually bridge the relay"?  Also, what are you switching through the relays?  110 volts AC from mains?  Or are you switching lower voltage?  And, if lower voltage, are you using the same power supply / source as that which powers the Arduino?  Lastly, are the Arduino and this control board located close (within inches) of each other?

With manually briding i mean connecting the two "output" pins from the relay with a cable to activate the pump without switching the relay for testing purposes. I am switching a 220v light bulb as well as 5 pumps which are 12v and connected to a different power supply but to the same multi plug. The distance from the arduino to the relay is ~15cm. The arduino and the relay board are on the same power supply (the relay board is connected to Vcc from the arduino)

Do you have the required bypass caps on the shift register?

No. Where would I need to put those?

Item 2 in my answer:  "as near as possible to each integrated circuit".  Oh, I see, it is commonly understood that these should go across the power pins of each integrated circuit.

If this is a noise issue, there are a number of mitigating actions to consider.  Also, consider that most if not all noise mitigating approaches are generic and may not apply to all situations.

It is almost always easier to mitigate noise at the source.  Filtering the power & shielding are two approaches.
When laying out digital integrated circuits, it is common to include bypass or decoupling capacitors as near as possible to each integrated circuit.  If unfamiliar with these, these capacitors go across the power pins of the integrated circuit.
If an electrically noisy environment is anticipated, making all communication leads and cables as short as possible prevents the likely hood of unexpected results.
If cables need to be long different communications methods such as balanced line or differential signalling should be considered.
Bring all power grounds to a single point.  This mitigates current loops which can cause unexpected power voltage fluctuations.
Consider the power requirements and generally use a power supply that is rated for double to have a margin of safety.
Avoid running cables containing high power or switched power near or in parallel to cables containing low voltage logic.

For this particular application / design:

Likely the reversed bias diode on the relay power supply lines is not needed.  There appears to be optical isolators on the relay board which should prevent the inductance of the relays from feeding back.
Verify you are creating the correct signal to the 74HC595 chip.  Use the timing diagrams on page 8 of this ti.com 74HC595 specification sheet as a guide.
Consider the gauge of the power cables.  Thinner wires over longer runs will drop the voltage proportional to the current demand.  If all 8 relays are active, the current demand may be as much as an Amp.

Thank you I will try those. The signals should be correct as I am using the arduino library for the shift register and as I said it is normally working. Only it sometimes stops and I need to turn off power to fix that.


text:
Casting custom shared_ptr object
I am using custom shared_ptr class for some program on Arduino, and I need to do something like this:
shared_ptr<Base_class> b_ptr;
shared_ptr<Child_class> ptr((shared_ptr<Child_class>) b_ptr);

In my shared_ptr class I have three constructors:
shared_ptr() : pData(0), reference(0){...}
shared_ptr(T* pValue) : pData(pValue), reference(0){...}
shared_ptr(const shared_ptr<T>& sp) : pData(sp.pData), reference(sp.reference){...}

and some other stuff...
For casting I tried to write the following:
    template< typename T2 >
operator T2 * () const
{
   return (T2 *)pData;
}

and:
    template< typename T2 >
operator shared_ptr<T2> () const
{
    shared_ptr<T2> temp((T2 *)pData);
    return temp;
}

but can't get it to work.

why do you need a shared ptr in the first place? there's not a lot of memory to warrant dynamic allocation for objects in the first place...

It's better not to use C-style casting in C++. It's working for POD types, but it's basically saying this pointer to elephant is now pointer to train. You should learn about static_cast and dynamic_cast (but I'd skip reinterpret_cast as it's roughly equivalent to the C-style casting)

For doing:
shared_ptr<Base_class> b_ptr;
shared_ptr<Child_class> ptr(b_ptr);

you have to use another constructor. If you take a look on this Example of shared_ptr implementation, you can see:
template<class U> shared_ptr(const shared_ptr<U>& s) ...

That's exactly the constructor, that takes shared_ptr of different type .
And similarly for assigment operator.

Thankyou for you answer. But how will I initialize private data like:               pData(s.pData), reference(s.reference)? I can't access them directly, since now they are  other class members.

I don't know much about your shared_ptr class. Anyways, you can assign pointer to the child into pointer to the parent directly (by implicit conversion).

I got it working by making template a friend of sared_ptr class. Thankyou for your help

@Mykolas Btw, if the reference is class member, it'll never work. You have to use something common for all copies.

Yes, I know. The reference is a separate class. Each shared_ptr object stores a pointer to this related reference object. Thankyou for the comment. @KIIV


text:
What is the use of reserved pins and SDD2, SDD3 pins of the NodeMCU?

How to use the reserved pins on the NODEMCU? What is their use? Also what is the use of SDD pins?
Thanks.

you can use GPIO10 as an input.

The ESP8266 uses an external flash memory chip to store your program. It communicates with this flash chip over a 4 bit SDIO interface, on GPIO6-11. These pins are labeled SDDn, SDCLK and SDCMD.
Usually, the interface uses all 4 data lines (QIO), but you can also configure it to use only 2 of the 4 lines (DIO), giving you access to two more GPIO pins (9 & 10).
The reserved pins are not mentioned in the schematic. They cannot be IO pins, because there simply are no other pins on the ESP8266/ESP-12. It could be pins connected to the USB chip, connected to power lines, or not connected at all. The designers probably wanted to allow for extra pins on next iterations of the board, without changing the form factor. A quick search online didn't yield any results, so your best bet is to trace the connection on the PCB, or measure it with a multimeter. You probably shouldn't be using them anyway, because they are "reserved".

it is SPI so in some special cases it can be used, but the SDK controls the CS pin of the flash. while it is HIGH, the bus is free


text:
How we can implement the interrupt?
I want to implement the Interrupt on the Adafruit_RGBLCDShield Select button to start/stop the data logging?

There is no interrupt for the select button.
The buttons, and the LCD itself, are connected to an I2C IO expander. Reading the state of the buttons is a polling operation - the library sends a request to the IO expander to get the current state, and then returns that to you as a bitmap.
While it is true the IO expander can be configured to generate an interrupt signal on one of its IO pins when an input changes state, that pin is not connected to anything on the PCB, so you would need to physically modify the shield to connect it to an interrupt pin on the Arduino. And on top of that, the library doesn't implement the settings needed to enable the interrupt - so you'd have to resort to configuring it all manually.
If you really want to do that kind of thing, then you will have to examine the datasheet for the IO expander and learn how it works.


text:
ESP8266 send TCP HEX packet with 4 chars
I'm building a remote for my WiFi-RGB Lights. I have an ESP8266, which should send one TCP packet with 4 chars.
My code:
#include <ESP8266WiFi.h>

const char* ssid     = "Wifi";
const char* password = "wifikey";

void WiFiEvent(WiFiEvent_t event) {
  Serial.printf("[WiFi-event] event: %d\n", event);
}

void setup() {
  Serial.begin(115200);
  WiFi.disconnect(true);
  delay(1000);
  WiFi.onEvent(WiFiEvent);
  WiFi.begin(ssid, password);
}

void loop() {
  delay(1000);
  const uint16_t port = 5577;
  const char * host = "192.168.178.150";
  WiFiClient client;
  client.connect(host, port);
  client.print(char(0x71));
  client.print(char(0x24));
  client.print(char(0x0f));
  client.print(char(0xa4));
  client.flush();
  client.stop();
  delay(5000);
}

The problem: I send 4 TCP packets, while I should send 1 TCP packet with all 4 chars.
Thanks for your help.

TCP data flow is not packet oriented, rather that is detail hidden in the implementation itself; a properly implemented TCP server must accept data arriving in any combination of packets, including one character per packet, words or lines broken between packets, packets that contain the end of one thing and the start of another, etc.

You can try sending all characters in a single print() but you're basically trying to use undocumented behavior of one thing to accommodate erroneous behavior of another.

Sounds like the problem is on the receiving end. Try shift/or-ing all values into one unsigned long and send that with one call to print.

After searching and experimenting on this, I believe the short answer to the question is that you need to send the command string like a buffer of characters AND put your Hex Coded command for the LED controller as an escaped string of characters.
Here is my code (it toggles the LED Controller between Green and Blue every 5 seconds, but you can extend this for other commands and colors as described at http://jpelectron.com/sample/Electronics/WiFi%20LED%20control/):
/*
Send Commands to LED Controller via Wifi Network and Wemos D1 Board
*/
#include <ESP8266WiFi.h>

const char* ssid     = "***yourWifiSSID***"; //Change this value for your network
const char* password = "***yourWifiPassword***"; //Change this value for your network
boolean connected = false;
boolean colorToggle = false;

void WiFiEvent(WiFiEvent_t event) {
    //Serial.printf("[WiFi-event] event: %d\n", event);

    switch(event) {
    case 3:
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
        connected = true;
        break;
    case 6:
        Serial.println("WiFi lost connection");
        connected = false;
        break;
    }

    // 0 : WL_IDLE_STATUS when Wi-Fi is in process of changing between statuses
    // 1 : WL_NO_SSID_AVAILin case configured SSID cannot be reached
    // 3 : WL_CONNECTED after successful connection is established
    // 4 : WL_CONNECT_FAILED if password is incorrect
    // 6 : WL_DISCONNECTED if module is not configured in station mode

}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
    Serial.begin(115200);
    WiFi.disconnect(true);
    delay(1000);
    WiFi.onEvent(WiFiEvent);
    WiFi.begin(ssid, password);
    Serial.println("");

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

}

// the loop function runs over and over again forever
void loop() {
    //if we are connected
    if(connected){
      digitalWrite(LED_BUILTIN, LOW); //Turn on LED on the Board
      turnLEDSOn();
    }
    else
    {
      digitalWrite(LED_BUILTIN, HIGH); //Turn off LED on the Board
      setup();
    }
}

void turnLEDSOn() {
    const uint16_t port = 5577;
    const char * host = "192.168.10.2";  //Change to whatever your LED Controller IP is

     WiFiClient client;

     if (client.connect(host, port)) //Try to connect to TCP Server
     {
        Serial.println("Connected to LED Controller... ");
        if (colorToggle)
        { //Green
          char command[] = "\x31\x00\xff\x00\x00\x00\xf0\x0f\x2f";
          client.write((uint8_t *)command, sizeof(command));
          colorToggle = false;
          delay(5000);
        }
        else
        { //Blue
          char command[] = "\x31\x00\x00\xff\x00\x00\xf0\x0f\x2f";
          client.write((uint8_t *)command, sizeof(command));
          colorToggle = true;
          delay(5000);
        }

        Serial.println("Command sent ... "); // command is the color or animation sent to the LED controller
     }
     else
     {
        Serial.println("connection failed ... ");
     }

      if (client.available())
      {
        //Read from LED Controller
        char c = client.read();
        Serial.print(c);
      }

      if (!client.connected())
      {
        Serial.println();
        Serial.println("disconnecting ... ");
        client.stop();
        for(;;);
      }
}


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:
Import library in Arduino IDE
I'm trying to use an HX711 load cell amplifier with my NodeMCU 0.9. I've found this library on Github and, following this guide, I tried to use it.
Unfortunately I keep getting this error:
sketch/HX711.cpp:2:19: fatal error: HX711.h: No such file or directory
 #include <HX711.h>

I suppose that there's some problem with C++ but I don't understand what is.
Here's the initial code:
#include <ESP8266WiFi.h>
#include "HX711.h"

Here's the folder structure:
Samples
  |-- nodemcu_test
        |--nodemcu_test.ino
        |--HX711.cpp
        |--HX711.h

Original question

You want to import a library not an example.
Arduino Folder
    |-- libraries
        |--HX711
            |--HX711.cpp
            |--HX711.h

ex:
C:\Program Files (x86)\arduino-1.8.5-windows\arduino-1.8.5\libraries\HX711

Put the files in a folder called HX711 to have everything nice and tidy.
I use the standalone version of arduino ide, if you have it installed I suspect the folder would be under
My Documents\Arduino\libraries\

According to the documentation.
You should put the nodemcu_test.ino in your sketchbook folder as I would generally avoid putting non-library files in the libraries folder. If you do want to keep the examples for a specific library close to the library create a subfolder:
Arduino Folder
    |-- libraries
        |--HX711
            |-- examples
                |--nodemcu_test.ino
            |--HX711.cpp
            |--HX711.h

As Juraj pointed out, this has the additional advantage of them being accessable in the examples menu.
If you want the libraries close to your sketch you are actually working on, follow the guide and put the library files in your sketchbook folder for your project. I would not advise for the following reasons:
I read that in newer IDEs 1.8.X you would need to put the files in a /src/subfolder. For me it did work without that, but the main caveat remained:
#include <HX711.h>

means to look in the library folder as mentioned above.
If you want to put the files somewhere else, you have to use
#include "HX711.h"

and specify the path (or in this example it was located where my .ino was). But now I also need to change
#include <HX711.h>

to
#include "HX711.h"

in the HX711.cpp file. What a hassle!
So my takeaway message would be: Stick with Arduino\libraries\.

@idkfa,  fix and refine the paragraph about examples and you have my upvote

@Juraj I extended the paragraph and even learned something on the way. Thanks for explaining why you didn't vote!

@idkfa Sorry, I would upvote if I could, by now you deserve the best answer :)

the examples from the example folder of a library are offered in the Examples menu in the IDE

"you would need to put the files in a /src/subfolder". You only need to do that if you want to put the library in a subfolder of the sketch folder. This can be convenient if you don't want library files cluttering up your sketch but you always have the option of just putting all the files in the sketch's root folder.


text:
HM-10 and Arduino Due
I am trying to communicate between HM-10 module (without any breadboard or soldering) and experience problem with reading data from serial.
Here is the code:

#define TO_HEX(i) (i <= 9 ? '0' + i : 'A' - 10 + i)

void afterSetup() {
  Serial3.write("AT+NAME?");
  delay(500);
}

void setup() {
  // initialize both serial ports:
  Serial.begin(9600);

  /*Serial3.begin(115200);  // The Bluetooth Mate defaults to 115200bps
  delay(100);  // Short delay, wait for the Mate to send back CMD
  Serial3.println("U,9600,N");  // Temporarily Change the baudrate to 9600, no parity
  // 115200 can be too fast at times for NewSoftSerial to relay the data reliably*/
  Serial3.begin(9600);  // Start bluetooth serial at 9600

  Serial.write("\n\n\n==== START ====\n");

  afterSetup();
}

unsigned char mode = 2;

void wr(HardwareSerial*, int);

void wr(HardwareSerial *target, int bt, unsigned char mode) {
    //target->write(TO_HEX(((bt & 0xF000) >> 12 )));
    //target->write(TO_HEX(((bt & 0x0F00) >> 8 )));
    if(mode > 0) {
      target->write("\t\t\t\t");
    }
    target->write(TO_HEX(((bt & 0x00F0) >> 4 )));
    target->write(TO_HEX((bt & 0x000F)));
    target->write(" (");
    target->write(bt);
    target->write(")\n");
    return;
}

void loop() {

  // read from port 1, send to port 0:
  if (Serial3.available()) {
    int inByte = Serial3.read();

    if(mode != 1) {
      mode = 1;
    }

    wr(&Serial, inByte, 1);
  }

  // read from port 0, send to port 1:
  if (Serial.available()) {
    int inByte = Serial.read();
    Serial3.print((char)inByte);

    if(mode != 0) {
      mode = 0;
    }

    wr(&Serial, inByte, 0);
  }
}

Wiring is simple:
HM-10    | due
-------------------
RX       | TX3
TX       | RX3
VCC      | 3V3
GND      | GND

Basically, I am able to get data from serial, but it corrupted.
Here is an example:

Command: AT+NAME?
Expected: HMSoft
Response:
        28 (()
        25 (%)
        2A (*)
        35 (5)
        15 ()
        FE (�)

And another, simpler:

Command:  AT
Expected: OK
Response: F5

What am I doing wrong?

Why are you printing from Serial3 before calling begin() on it?


text:
Multiple if statement conditions
I would like to make this code using the Arduino Uno. I am using three on/off switches and based on the truth table would like to turn on one of 8 LEDs. When I use digitalWrite(), I get an error code saying that there are too few arguments.
Here is the code
int x = A3;    // select the input pin for the switch
int y = A4;
int z = A5;

int ledPin1 = 2;      // select the pin for the LED
int ledPin2 = 3;
int ledPin3 = 4;
int ledPin4 = 7;
int ledPin5 = 8;
int ledPin6 = 9;
int ledPin7 = 12;
int ledPin8 = 13;

void setup(){

  // declare the ledPin as an OUTPUT:
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  pinMode(ledPin5, OUTPUT);
  pinMode(ledPin6, OUTPUT);
  pinMode(ledPin7, OUTPUT);
  pinMode(ledPin8, OUTPUT);

  pinMode(x, INPUT);
  pinMode(y, INPUT);
  pinMode(z, INPUT);
}

void loop() {

  if ( (x = LOW) && (y = LOW) && (z = LOW))              //condition 1
  {
    digitalWrite (ledPin1 = HIGH);
    digitalWrite (ledPin2 = LOW);
    digitalWrite (ledPin3 = LOW);
    digitalWrite (ledPin4 = LOW);
    digitalWrite (ledPin5 = LOW);
    digitalWrite (ledPin6 = LOW);
    digitalWrite (ledPin7 = LOW);
    digitalWrite (ledPin8 = LOW);
  }

  if ( (x = LOW) && (y = LOW) && (z = HIGH))             //condition 2
  {
    ledPin1 = LOW;
    ledPin2 = HIGH;
    ledPin3 = LOW;
    ledPin4 = LOW;
    ledPin5 = LOW;
    ledPin6 = LOW;
    ledPin7 = LOW;
    ledPin8 = LOW;
  }

  if ( (x = LOW) && (y = HIGH) && (z = LOW))             //condition 3
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = HIGH;
    ledPin4 = LOW;
    ledPin5 = LOW;
    ledPin6 = LOW;
    ledPin7 = LOW;
    ledPin8 = LOW;
  }

  if ( (x = LOW) && (y = HIGH) && (z = HIGH))              //condition 4
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = LOW;
    ledPin4 = HIGH;
    ledPin5 = LOW;
    ledPin6 = LOW;
    ledPin7 = LOW;
    ledPin8 = LOW;
  }

  if ( (x = HIGH) && (y = LOW) && (z = LOW))               //condition 5
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = LOW;
    ledPin4 = LOW;
    ledPin5 = HIGH;
    ledPin6 = LOW;
    ledPin7 = LOW;
    ledPin8 = LOW;
  }

  if ( (x = HIGH) && (y = LOW) && (z = HIGH))               //condition 6
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = LOW;
    ledPin4 = LOW;
    ledPin5 = LOW;
    ledPin6 = HIGH;
    ledPin7 = LOW;
    ledPin8 = LOW;
  }

  if ( (x = HIGH) && (y = HIGH) && (z = LOW))                //condition 7
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = LOW;
    ledPin4 = LOW;
    ledPin5 = LOW;
    ledPin6 = LOW;
    ledPin7 = HIGH;
    ledPin8 = LOW;
  }

  if ( (x = HIGH) && (y = HIGH) && (z = HIGH))                //condition 8
  {
    ledPin1 = LOW;
    ledPin2 = LOW;
    ledPin3 = LOW;
    ledPin4 = LOW;
    ledPin5 = LOW;
    ledPin6 = LOW;
    ledPin7 = LOW;
    ledPin8 = HIGH;
  }
}

I used your code as a reference but when I uploaded it, it gives me "too few arguments to function". Any solutions?

void loop() {
 if ( (x = LOW) && (y = LOW) && (z = LOW))              //condition 1
 {

Apart from the issue of needing == instead of = you are never reading those pins. In fact you are comparing the pin numbers (which will never change), not the data on those pins.
You need:
void loop() {
  if ( (digitalRead (x) == LOW) &&
       (digitalRead (y) == LOW) &&
       (digitalRead (z) == LOW))              //condition 1
    {

... and so on.

This is wrong too, I'm surprised it compiled:

   digitalWrite (ledPin1 = HIGH);
   digitalWrite (ledPin2 = LOW);
   digitalWrite (ledPin3 = LOW);
   digitalWrite (ledPin4 = LOW);
   digitalWrite (ledPin5 = LOW);
   digitalWrite (ledPin6 = LOW);
   digitalWrite (ledPin7 = LOW);
   digitalWrite (ledPin8 = LOW);

It should be:
  digitalWrite (ledPin1, HIGH);
  digitalWrite (ledPin2, LOW);
  digitalWrite (ledPin3, LOW);
  digitalWrite (ledPin4, LOW);
  digitalWrite (ledPin5, LOW);
  digitalWrite (ledPin6, LOW);
  digitalWrite (ledPin7, LOW);
  digitalWrite (ledPin8, LOW);

when i use digital write i get an error code saying that there are too few arguments.
  ...
   I just dont know why the simulation program is still not lighting the LED

Oh I see, it did not compile. No wonder the LEDs didn't turn on.

digitalWrite (ledPin1 = HIGH); should be digitalWrite (ledPin1, HIGH);
PS if ( (x = LOW) && (y = LOW) && (z = LOW)) should be if ( (x == LOW) && (y == LOW) && (z == LOW)). = is for assignment, == is for comparison.

Thanks I changed all of that in the code. I just dont know why the simulation program is still not lighting the LED.

you should simply write code to compute the state necessary for each led based on the truth table and write out that state to the specific digital pin only once; you would not need so many if/else conditions and so many calls to the digitalWrite function either; by the way your code will also work fine if you update your assignments to digitalWrite statements in your code in all the if/else blocks;

Here's a little tip for you (it has nothing to do with your problem, it's just a good programming method).  This will massively reduce the size of your program.
You have three boolean state variables, and you are comparing the state of all combinations - that's 8 combinations.  If you take each boolean value as 1 bit of a value between 0 and 7 - that is values (as binary) 000, 001, 010, 011, 100, 101, 110, and 111 - then you can use much simpler methods for controlling your LEDs.
For instance, this (untested) code will turn three digital reads into a single number between 0 and 7:
uint8_t value = digitalRead(x) | (digitalRead(y) << 1) | (digitalRead(z) << 2);

x is the least significant bit, and z is the most significant.  So value will now be a value between 0 and 7 representing the state of those three pins.
Now you can use that value variable to decide which pin to turn on.  Here's another trick:  Store you LED pins as an array.  That means, instead of having ledPin1, ledPin2, etc, you just have a list of pin numbers known as ledPin[x]:
const uint8_t ledPin[8] = { 2, 3, 4, 7, 8, 9, 12, 13 };

Now you can use a for loop to iterate though that list and turn on the LED you want:
for (uint8_t i = 0; i < 8; i++) {
    if (i == value) {
        digitalWrite(ledPin[i], HIGH);
    } else {
        digitalWrite(ledPin[i], LOW);
    }
}

In fact, that can be further compressed, since HIGH and LOW are basically truth values (HIGH is 1, or true, and LOW is 0, or false):
for (uint8_t i = 0; i < 8; i++) {
    digitalWrite(ledPin[i], i == value);
}

So your whole program could look like this:
const uint8_t x = A3;    // select the input pin for the switch
const uint8_t y = A4;
const uint8_t z = A5;

const uint8_t ledPin[8] = { 2, 3, 4, 7, 8, 9, 12, 13 };

void setup() {
    for (uint8_t i = 0; i < 8; i++) {
        pinMode(ledPin[i], OUTPUT);
    }
    pinMode(x, INPUT);
    pinMode(y, INPUT);
    pinMode(z, INPUT);
}

void loop() {
    uint8_t value = digitalRead(x) | (digitalRead(y) << 1) | (digitalRead(z) << 2);
    for (uint8_t i = 0; i < 8; i++) {
        digitalWrite(ledPin[i], i == value);
    }
}

Saves a huge amount of typing and also ends up using considerably less Flash memory.

Thanks I am still learning about arduino programming. this is definitely an easier way to go about it. thanks again for teaching me this!

Great way to get beginners interested in arrays and booleans by way of showing their utility value. Nice.

Since you mentioned you are new to programming, I am posting your own solution modified to work with right things; this code can be optimize to a great extent if you get good at programming; For your benefit, I will post both your approach and a slightly better approach
Your approach:
int x = A3;    // select the input pin for the switch
int y = A4;
int z = A5;

int ledPin1 = 2;      // select the pin for the LED
int ledPin2 = 3;
int ledPin3 = 4;
int ledPin4 = 7;
int ledPin5 = 8;
int ledPin6 = 9;
int ledPin7 = 12;
int ledPin8 = 13;

void setup(){

    // declare the ledPin as an OUTPUT:
    pinMode(ledPin1, OUTPUT);
    pinMode(ledPin2, OUTPUT);
    pinMode(ledPin3, OUTPUT);
    pinMode(ledPin4, OUTPUT);
    pinMode(ledPin5, OUTPUT);
    pinMode(ledPin6, OUTPUT);
    pinMode(ledPin7, OUTPUT);
    pinMode(ledPin8, OUTPUT);

    pinMode(x, INPUT);
    pinMode(y, INPUT);
    pinMode(z, INPUT);
}

void loop() {

    if ( (x = LOW) && (y = LOW) && (z = LOW))              //condition 1
    {
        digitalWrite (ledPin1, HIGH);
        digitalWrite (ledPin2, LOW);
        digitalWrite (ledPin3, LOW);
        digitalWrite (ledPin4, LOW);
        digitalWrite (ledPin5, LOW);
        digitalWrite (ledPin6, LOW);
        digitalWrite (ledPin7, LOW);
        digitalWrite (ledPin8, LOW);
    }

    if ( (x = LOW) && (y = LOW) && (z = HIGH))             //condition 2
    {
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, HIGH);
        digitalWrite(ledPin3, LOW);
        digitalWrite(ledPin4, LOW);
        digitalWrite(ledPin5, LOW);
        digitalWrite(ledPin6, LOW);
        digitalWrite(ledPin7, LOW);
        digitalWrite(ledPin8, LOW);
    }

    if ( (x = LOW) && (y = HIGH) && (z = LOW))             //condition 3
    {
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, LOW);
        digitalWrite(ledPin3, HIGH);
        digitalWrite(ledPin4, LOW);
        digitalWrite(ledPin5, LOW);
        digitalWrite(ledPin6, LOW);
        digitalWrite(ledPin7, LOW);
        digitalWrite(ledPin8, LOW);
    }

    if ( (x = LOW) && (y = HIGH) && (z = HIGH))              //condition 4
    {
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, LOW);
        digitalWrite(ledPin3, LOW);
        digitalWrite(ledPin4, HIGH);
        digitalWrite(ledPin5, LOW);
        digitalWrite(ledPin6, LOW);
        digitalWrite(ledPin7, LOW);
        digitalWrite(ledPin8, LOW);
    }

    if ( (x = HIGH) && (y = LOW) && (z = LOW))               //condition 5
    {
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, LOW);
        digitalWrite(ledPin3, LOW);
        digitalWrite(ledPin4, LOW);
        digitalWrite(ledPin5, HIGH);
        digitalWrite(ledPin6, LOW);
        digitalWrite(ledPin7, LOW);
        digitalWrite(ledPin8, LOW);
    }

    if ( (x = HIGH) && (y = LOW) && (z = HIGH))               //condition 6
    {
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, LOW);
        digitalWrite(ledPin3, LOW);
        digitalWrite(ledPin4, LOW);
        digitalWrite(ledPin5, LOW);
        digitalWrite(ledPin6, HIGH);
        digitalWrite(ledPin7, LOW);
        digitalWrite(ledPin8, LOW);
    }

    if ( (x = HIGH) && (y = HIGH) && (z = LOW))                //condition 7
    {
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, LOW);
        digitalWrite(ledPin3, LOW);
        digitalWrite(ledPin4, LOW);
        digitalWrite(ledPin5, LOW);
        digitalWrite(ledPin6, LOW);
        digitalWrite(ledPin7, HIGH);
        digitalWrite(ledPin8, LOW);
    }

    if ( (x = HIGH) && (y = HIGH) && (z = HIGH))                //condition 8
    {
        digitalWrite(ledPin1, LOW);
        digitalWrite(ledPin2, LOW);
        digitalWrite(ledPin3, LOW);
        digitalWrite(ledPin4, LOW);
        digitalWrite(ledPin5, LOW);
        digitalWrite(ledPin6, LOW);
        digitalWrite(ledPin7, LOW);
        digitalWrite(ledPin8, HIGH);
    }
}

Slightly better approach:(better programmers may be able to write even more optimized code)
int x = A3;    // select the input pin for the switch
int y = A4;
int z = A5;

int ledPin1 = 2;      // select the pin for the LED
int ledPin2 = 3;
int ledPin3 = 4;
int ledPin4 = 7;
int ledPin5 = 8;
int ledPin6 = 9;
int ledPin7 = 12;
int ledPin8 = 13;

void setup(){

  // declare the ledPin as an OUTPUT:
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);
  pinMode(ledPin4, OUTPUT);
  pinMode(ledPin5, OUTPUT);
  pinMode(ledPin6, OUTPUT);
  pinMode(ledPin7, OUTPUT);
  pinMode(ledPin8, OUTPUT);

  pinMode(x, INPUT);
  pinMode(y, INPUT);
  pinMode(z, INPUT);
}

void loop() {
  int pinToTurnHigh = 2; // just making sure its a valid pin
  if ( (x = LOW) && (y = LOW) && (z = LOW))              //condition 1
  {
    pinToTurnHigh = ledPin1;
  }

  if ( (x = LOW) && (y = LOW) && (z = HIGH))             //condition 2
  {
    pinToTurnHigh = ledPin2;
  }

  if ( (x = LOW) && (y = HIGH) && (z = LOW))             //condition 3
  {
    pinToTurnHigh = ledPin3;
  }

  if ( (x = LOW) && (y = HIGH) && (z = HIGH))              //condition 4
  {
    pinToTurnHigh = ledPin4;
  }

  if ( (x = HIGH) && (y = LOW) && (z = LOW))               //condition 5
  {
    pinToTurnHigh = ledPin5;
  }

  if ( (x = HIGH) && (y = LOW) && (z = HIGH))               //condition 6
  {
    pinToTurnHigh = ledPin6;
  }

  if ( (x = HIGH) && (y = HIGH) && (z = LOW))                //condition 7
  {
    pinToTurnHigh = ledPin7;
  }

  if ( (x = HIGH) && (y = HIGH) && (z = HIGH))                //condition 8
  {
    pinToTurnHigh = ledPin8;
  }
  resetAllLEDs();
  digitalWrite(pinToTurnHigh, HIGH);
}

void resetAllLEDs()
{
  digitalWrite(ledPin1, LOW);
  digitalWrite(ledPin2, LOW);
  digitalWrite(ledPin3, LOW);
  digitalWrite(ledPin4, LOW);
  digitalWrite(ledPin5, LOW);
  digitalWrite(ledPin6, LOW);
  digitalWrite(ledPin7, LOW);
  digitalWrite(ledPin8, LOW);
}

The sole error in digitalWrites is that digitalWrite (ledPin1 = HIGH); should be digitalWrite (ledPin1, HIGH); same for other digitalWrite calls;
"too few arguments to function" clearly implies that the number of arguments you are passing are less than expected by the function;
by the way your code will also work fine if you update your assignments to digitalWrite statements in your code in all the if/else blocks;
you can read more about the digitalWrite function in the link below
https://www.arduino.cc/en/Reference/DigitalWrite


text:
Flashing firmware in ft232rl
I am new with arduino and hardwares at all and I am having some problems in a project where I want to assemble the head tracker device from this project https://git.iem.at/DIY/MrHeadTracker/wikis/mrht-bno055 ... They use an Arduino pro mini for data processing (with a .ino sketch provided by them), an Arduino USB 2 Serial micro for connecting the pro mino to the pc, and a sensor BNO055 by Adafruit which provides orientation data. I am using the same hardwares instead of the USB converter that in my case is the ft232rl by FTDI. The step I am having problem is the one where I have to flash the HIDUINO firmware (they provide an .hex file) so I can use the whole thing as a MIDI device.
The point is that I just don't understand if I have to overwrite the pro mini's serial firmware or the usb converter's and how it's the correct way to do it, mainly because I can't find examples with the usb converter I have and every new reference I read makes me think of one possibility. In the first link they suggest reading the information in https://github.com/ddiakopoulos/hiduino/wiki which presents 2 methods: DFU method, that tells I need Atmel Flip software for Windows and ISP method, that I don't know if is my case because I can't find out if my ftdi board is an ISP programmer. I've read about it and in other references also, but I am still not sure about what I have to do.
I hope that someone can help! And sorry for the basic doubts...
Thanks!

The arduino USB2serial has an AVR that can be flashed with new firmware. Your FTDI device does not have MCU that can be re-programmed.

@Craig, actually, you can make some changes to the FTDI adapter ... http://www.ftdichip.com/Support/Utilities.htm#FT2xxR

@Craig if that is the case, it means I can't use the board for this application because it can't be reprogrammed or i just don't need to overwrite any firmware because there's nothing to be reprogrammed? Thanks for the answer!

@jsotola Which would be the right section of the link you sent? Thank for your answer!

@Enzor, I do not know if any sections apply to you ... it is unclear what you are trying to do. .... the ftdi chip is just a USB to serial adapter

@jsotola sorry for that... I actually have problemas to explain the problem too... but what I am trying to find out is how to do this step "Flash the USB2Serial interface according to https://github.com/ddiakopoulos/hiduino/wiki.
You can use the provided MrHeadTracker.hex file (HiduinoFirmware directory).", which makes me think I have to do something in my usb to serial conterver, the ftdi, because is the board I am using to substitute the Arduino USB2 serial from their project...

@jsotola The main sketch (.ino) is already uploaded in the pro mini... the device is designed to be a class-compliant MIDI, including the way the code ( https://git.iem.at/DIY/MrHeadTracker/tree/master/Arduino/MrHeadTrackerBNO055Switchable )is written that uses MIDI library... Here's antoher thing they say that makes me think it's all about the usb conv "To enable plug-and-play support without any additional
software, the Arduino USB2Serial converter is used.
Its Atmel 16u2 micro-controller can be programmed to
appear as a class-compliant USB-MIDI device using the
HIDUINO library"


text:
max7219 chained display showing text only on the first display
I'm using a max7219 like this one max7219. When I first tested my circuit, I used an 8x8 display and the code worked just fine. Now, after I modified the code and changed the display with the chained one, the text is showing only on the first matrix. I've seen someone that had another problem with the same matrix module, only that in his case the same text was printed on all the matrixes unsolved problem, in the end he didn't find a solution. Below, I'll attach my code. Please help me find the problem.
//Pin connected to ST_CP of 74HC595
int latchPin = 6;
//Pin connected to SH_CP of 74HC595
int clockPin = 7;
////Pin connected to DS of 74HC595
int dataPin = 5;

int period = 30;

byte rotl(byte n, byte b)
{
  return (n << b) | (n >> (8 - b));
}

byte X[] {

0x80,
0x80,
0x80,   //L
0x80,
0x80,
0x80,
0x80,
0xFF,

/*0x10,
0x00,
0x10, //I
0x10,
0x10,
0x10,
0x10,
0x10,

0XF0,
0x90,
0x80, //C
0x80,
0x80,
0x80,
0x90,
0xF0,

0xF0,
0x09,
0x09,
0x09,
0x09,
0x09, //A
0x09,
0xF0*/

};

void setup() {
  //set pins to output so you can control the shift register
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop()
{
  for (int i = 0; i < 8; i++)
  {
    X[i] = rotl(X[i], 1);
  }
  for(int i = period;i>0;i--)
  {
    displayX();
  }

}

void DisplayMatrix(byte numCol, byte numLine)
{
  byte numberToDisplay1 = numCol;
  byte numberToDisplay2 = numLine;

  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay1);
  shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay2);
  digitalWrite(latchPin, HIGH);
  delay(1);

}

void displayX()
{
   DisplayMatrix(X[0],1);
   DisplayMatrix(X[1],2);
   DisplayMatrix(X[2],4);
   DisplayMatrix(X[3],8);
   DisplayMatrix(X[4],16);
   DisplayMatrix(X[5],32);
   DisplayMatrix(X[6],64);
   DisplayMatrix(X[7],128);
}

I don't think you understand how the protocol works. Have you read the MAX7219 datasheet?

Why don't you just get a copy of the library that drives the max7219 ??  http://playground.arduino.cc/Main/LEDMatrix.

Communicating with more than one MAX7219 chip when cascaded involves sending data to all the chips at once. You have to treat the cascaded sequence of chips as a single entity - an entire display in its own right.
With one chip you send an 8-bit register value followed by an 8-bit data value. To use two chips you have to send twice that - an 8-bit register and 8-bit data for the second chip, followed by an 8-bit register and 8-bit data for the first chip.
The chips have a "NO-OP" register (0x00) which can be used to ensure that nothing is done on that chip if you don't want to change anything.
So setting line 3 to 0x55 on the first display, and line 5 to 0xAA on the second display you would send the sequence \ 0x05,0xAA,0x03,0x55 / as a single transaction (lower CS \ before, raise it / afterwards).
If you only wanted to set line 2 on the second display to 0x69 you would send the sequence: \ 0x02,0x69,0x00,0x00 /
For three chips you need to send three blocks of 8+8 values. For four chips, 4 blocks of 8+8. Etc.
Note that it is important to send enough data for all the chips - you can't shortcut and only send data for the first display if that is all you want to talk to, since whatever is currently in the first display's shift register will get sent out to successive chips, and you will get the display duplication as seen in the other question.


text:
I2C communication with LCD screen via 2.5m long cable
I’m attempting to connect a 4x20 LCD to an Arduino Mega 2560 Rev3 using the I2C protocol via a 2.5m VGA cable. I understand that such a long cable isn’t ideal for I2C communication, but I cannot change this setup. I’ve reviewed a related question here, which was insightful, but I still have some doubts about how to make this work with my specific configuration.
My setup:

Microcontroller: Arduino Mega 2560 Rev3
I2C Expander: PCF8574 (remote 8-bit expander for I2C bus)
LCD: 20x4 HD44780-compatible
Cable: 2.5m VGA cable

SDA connected to pin 13
SCL connected to pin 14
GND connected to the VGA cable’s external sleeve

Libraries Used:

<Wire.h>
<hd44780.h>
<hd44780ioClass/hd44780_I2Cexp.h>

Questions:

Can I adjust the I2C clock frequency using the following code snippet without causing conflicts with the libraries used?
Wire.begin();
TWBR = 152;

Pull-up resistors:

I understand the Arduino Mega uses built-in 10k Ω pull-up resistors on the SDA and SCL lines. In my code, I didn’t explicitly configure SDA and SCL as pull-ups. I simply declared the LCD object like this:
hd44780_I2Cexp lcd; // declare lcd object: auto locate & auto config expander chip

Does the library’s auto-configuration automatically handle the pull-ups?

I’ve read that lower pull-up resistance is beneficial for longer cables. How can I modify the pull-up resistors on the Arduino Mega 2560? What resistance value would you recommend for this 2.5-meter cable?

Caps on SDA and SCL at the I2C expander end of the cable
Does it make sense to add 0.1 uF ceramic resistors between ground and SDA and ground and SCL?

If you really want lower pull up resistance, you can just put external pull-ups in parallel.  Making it bigger would be difficult.

Wire library has Wire.setClock(), read the doc. 2) Someone already answer this; 3) I2C stands for Inter-Integrated-Circuit protocol, meaning that it was design for short distance between ICs. If you really want to try 2.5m, as per I2C specification, the bus capacitance should not be higher than 200pf for fast mode. If you use a CAT 5 cable which has capacitance less than 52pf/m, with 2.2k pull-up and clock of 100kHz or lower, it might well within the I2C spec.

Since you mention VGA, do you know DDC? Its second version uses I²C... You might want to do some research. For example, it uses pins 12 and 15.

Any reason for not using the hardware I2C port on pins 20 and 21?

The problem with bus length is due to the way pull-ups work. For high-to-low transitions i2c node drives pin low, so the wire potential always falls fast. But for low-to-high transition the node goes to hi-z state instead. So the wire potential rises due to pull-up resistor only.
Now imagine that there is also some (parasitic) capacitor between wire and ground. Then the wire becomes a middle point for RC circuit. Therefore, its potential rise time becomes proportional to R multiplied by C. R is set by the spec between 1 and 10k. So if C is big enough then any low-to-high transition cannot be fast either.
So what are the options?

Reduce R. It's enough to add another pull-up resistor (so it's in parallel with existing one). Beware though not to make it too small and let the magic smoke out. Might be not a problem for SCL but SDA is always bidirectional.

2. Reduce C. Usually we just don't use long wires. In your case though you need to twist the wires one around another. Or just use good twisted pair cable.

Slow SCL speed. The spec sets 100kb/s as the slowest clock speed. However, only the host decides what the real speed is. The slaves might be missing too fast clocks but usually they don't have any problems with slow ones. Of course, hardware/library implementations may not support such feature. But making i2c bit-banging implementation is really trivial. Then you can make clock as slow as you need.

Using bidirectional buffer(s) in the middle of your cable. That's a bit controversial advice as a buffer will create a delay of its own. But I guess it doesn't hurt to experiment with. If some cheap "logic level shifter" module can't help then, maybe, some dedicated ic (txs010x etc.) will do better. Who knows?

Desolder i2c board and drop i2c bus completely. The screen itself is not bound to i2c protocol. You can attach, say, 74hc595 instead and switch to SPI (which is also short distance thing but should work for 2-3 meter cable). Or simply draw all (eight or so) wires in parallel without any fancy serial-to-parallel protocol stuff. Maybe you'll need also some buffer chips, maybe not. In the worst case some UART based solution could resolve virtually any trouble with cable length/quality.

On Reduce C, twist pair does not reduce C. The Capacitance is determined by the tray capacitance of the PCB and the type of the wire. Twist pairs do not help I2C (or digital signalling) as both SDA and SCL are ground-referenced, and it would not be beneficial to twist the SCL and SDA wires together as this would increase crosstalk between them. 2) Hardware I2C doe not necessary operate at 100kHz, even you configure the I2C as 100kHz, you often found that the actual clock speed could be as low as 80kHz depend on MCU's clock configuration and internal prescaler.

@hcheung 1. Twisting signals with gnd, as i2c devices need common ground and no one likes having a separate cable for it; 2. If it works for 100 or for 80 then it's okay; the point is that the bus master could set even much lower speed if only software allows for it.

Twist with GND will only increase the capacitance, not reduce it. Twist pair improve EMI (for analog signal) but the issue with I2C protocol is the capacitance of the line (<200pf for fast mode). Read the I2C protocol specification.