text:
How do I use the Arduino Mega as a 16-bit SPI slave?
I have to interface an Arduino Mega as a slave with a SPI master running at 1 MHz SCK. The master will send and ask for two bytes in a single transaction. I tried using the following code for the Mega. Its intended functionality is to store the master's sent data in acc and return local data ret, which is simply an integer to be incremented every transaction.
However, while the master data is stored in acc (verified through serial output), the data returned to the master is not the value in ret. Instead, the first response byte is correct (MSB of ret) and the second response byte is just the first byte received by the Mega, which was the value already present in SPDR.
How do I send the second byte of ret as the second byte of the response? What am I doing wrong?
// SPI Slave

#include <SPI.h>

// return to master
volatile unsigned int ret;

// accept from master
volatile unsigned int acc;

// MSB/LSB indicator
volatile byte SB;

void setup(void)
{

  ret = 0;
  SB = 0;

  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // turn on interrupts
  SPCR |= _BV(SPIE);

  // set CPOL, CPHA modes
  // byte dataMode = 0;
  // SPCR = (SPCR & ~SPI_MODE_MASK) | dataMode;

}

// SPI interrupt routine
ISR(SPI_STC_vect)
{

  if(SB == 0) {
    acc = SPDR << 8;
    SPDR = ret;
    ret++;
  }
  else {
    acc += SPDR;
    SPDR = ret >> 8;
  }
  SB = (SB + 1) & 0x01;

}

void loop(void)
{
  // interrupt processing only
}

Edit Changed SCK from 16 MHz to 1 MHz

Have you done the timing math yet?

I don't know which timing you're asking for. Are you saying that the ISR is too long?

I'm late to the party, but...
I experienced exactly the same issues having a Arduino Uno as a SPI slave communicating to a Arduino Mega as SPI master. My conclusion is that the slave must take some time to process the SPI transfer of the first byte (your code in the SPI interrupt handler), but the master is not waiting for it. So the transfer of the second byte starts before your handler is completely executed, so the master receives the same byte again.
In my case, I fixed this with an ugly sleep in the master before sending the second byte:
SPI.beginTransaction(spi_settings);
word input = 0;
digitalWrite(spi_devices[port].pin_ss, LOW);
input |= SPI.transfer(output >> 8) << 8;
delayMicroseconds(20); // Must give time to slave to read first byte
input |= SPI.transfer(output);
digitalWrite(spi_devices[port].pin_ss, HIGH);
SPI.endTransaction();

Not elegant, but it works.

You might need to check the Arduino Mega/ATmega2560 product description and SPI slave mode.

In SPI Slave mode, the control logic will sample the incoming signal
  of the SCK pin. To ensure correct sampling of the clock signal, the
  minimum low and high periods should be: Low period: longer than 2 CPU
  clock cycles. High period: longer than 2 CPU clock cycles.

This implies the maximum SCK in slave mode. 16 MHz SCK would be too fast for an Arduino Mega (at 16 MHz).
Also there is a significant latency to the ISR. To achieve higher slave mode clock frequency:

Time between slave mode chip select and clock must be stretched to compensate for the ISR latency.
The ISR will need to busy wait for all data (as the Arduino SPI transfer() is implemented).

Cheers!

The master is running at 1 MHz. I'm sorry for the wrong info. Corrected the question.

Great! Now you need to show how you have verified the code. Please remember that Serial output in an ISR is not a very good idea.

I did use Serial output within the ISR for verification, but the final code is what I posted. The bytes returned to the master were extracted on the master side, which were the same in both cases with or without Serial.


text:
What would be a good way to identify items spending as little as possible?
I'm a software developer for quite some time and now I'm going to start developing for Arduino. My question is related to technology I can use. It's also my first time posting here, so if this site is not the proper place for this questions would you tell me which one I could use to get this answer?
My problem:
I need to identify items within a certain range (~3ft). So I thought about a RFID tag on each item and a reader. The problem with that approach is currently the price. The lowest price I found for RFID tags are about US$0.09 per unit. Which is way too much for this project. up to US$0.01 per unit would be acceptable.
Is there any other way I could identify these items, based on range, not being directed to the reader's laser, that would be cheaper?
I though also about something like stores do with their products to prevent theft. Adding a plastic thingy on their clothes and those totems alert if an item with that plastic thingy passed through.
I appreciate any help :)
Thanks
EDIT
Imagine a bag and products being thrown inside this bag. In my mind I'd have a mechanism in which there would be like a rim around this bag that reads the products information. That rim would be a RFID (just for illustration's sake) reader.
Items would be thrown inside this bag, sometimes plenty of items at once. And they all need to be identified.
Something like this:

I'm not actually going to implement this solution on a bag, but I think it perfecly illustrates my point.
I hope I was able to clarify the problem now :)

The "plastic thingy" uses RFID.

@IgnacioVazquez-Abrams cool :) so I think I'm on the right track here :) Would you know of any alternatives to RFID in this case or at least cheaper RFID options? As I said US$0.09 won't work. Thanks.

How about a barcode reader and print barcodes on labels to stick on your things?

Print QR codes on the objects and use a webcam to read them. PS 3ft is way to far away for rfid anyways.

@Majenko the problem with that is I'd need to directly scan it, wouldn't I (at least AFAIK)? and as I mentioned that's not something that can be requested. Once the item goes through one specific area it needs to be identified. Thanks

@Gerben the problem with that is I'd need to directly scan it, wouldn't I (at least AFAIK)? and as I mentioned that's not something that can be requested. Once the item goes through one specific area it needs to be identified. Thanks

What do you mean with "directly scan it"?

@Gerben well, using a scanner directly on the QR code, right? The only "variation" of QR codes I know work like, but if there are others please let me know... As I said I need to work on a range basis (like RFID) not on the user scanning an item. Imagine a conveyor belt with the factory's irregularly shaped products rolling over. The QR code might be facing up, sideways, down, etc... there's not way of knowing, so in that scenario I'd need something to identify the items by range, not "directly scanning" its code. Thank you.

It would be helpful if you were less vague on the application you want to use it for. You solve the upside-down problem, by having more than one QR code, or by having multiple scanners, or some way to flip the item, so you can check both sides. You don't have to put the scanner near the QR code. Just use a webcam and some computer-vision software. That way the QR code can be anywhere on the conveyor.

@Gerben I understand, I'm not looking for ways to fix the item's placement on the conveyor belt, I know that could be arranged in other ways. I need something to identify a product without being required to directly scan it. Please check my updated answer, hopefully it will make things clearer.

I'd place a few cameras around the perimeter of the bag-entrance. No need to "directly scan" it.

@Gerben Yes, but you still have the case in which two products thrown inside the bag at the same time have the QR code facing each other, something that would prevent the cameras to read it. Thanks.

How about using NFC?

@dhimaspw Thanks, I though about that, but the prices I found are even higher than those of RFIDs... I tried most Chinese sites and the prices are higher, unfortunately...

Is there a way to re-use the RFID tags? Or maybe transport the bags in a cardboard boxes (with a label), so the box itself can be scanned?

Seems like you're stuck in "requirements hell". In my theorie this means that your requirements are too strict, and you or your client won't let go of these requirements.
It can help to do a research, set up some "research questions". And if possible with some sub questions, like:
"How can we measure multiple objects at a price of only 0.01$ per object. Withouth having direct line of sight to all sides of the packaging."
With sub questions:

What techniques are available to identify objects.
In what environment will this system work?
How do other companies detect Products?
What techniques fit these requirements and environment.

And if none fit at question 4

How can we change the requirements or environment to have one technique fit.

The idea is, that after the research, you probably have a valid answer. But also that you can convince your Boss/client (or yourself), bases on your research, what solution is acceptable, even if it means altering the requirements.
You may also want to check how other companies do this, since it's a pretty common thing to identify objects etc.

For us, it is extremely difficult to say whatever will fit your needs. And you'll most likely have to adapt something.
To start off, you will either need some kind of vision or RF. But any RF tag is most likely to be too costly.
So you're either stuck with vision or increasing the price limit.
With vision, usually you either require some kind of barcode or qr code. Or you'll have to detect the object itself.
Another wat could be to differentiate on the objects' variables. Like check the weight, color, conductivity or even shape. This could be tricky, but not unlikely.
Mind that it also depends on what items you want to detect.

Well, I agree that my question was lacking information, but research was done and that's why the RFID solution was commented here. After much research RFID was found to be a suitable solution. The problem is the price. The requirements are there, I didn't specify them all when I first posted, but they are there now. So even though RFID does solve the problem, it is at a too high price per item. That's why I'm looking for solutions with the same capability that are cheaper. Thanks for your answer.

Well, if there is a price restriction, how comes that RFID is found as a suitable solution? Since, it's not a viable solution, based on price.

But, my point is, that you should check out the options you have and present this options to whoever wants you to develop this. So the conclusion of your research will be: "You either have to pay a few cents extra and get RFID working OR you can use vision (using QR or something specific), since it's cheap but will require the label to be visible.

Paul, thank you for your comments. RFID was found to be a suitable solution technically, when it came to price it was rejected. The only reason why I said that was to explain what was needed for this project (RFID suits the needs). As to "paying a few cents extra" is impossible since it would render the project inviable. Answering your other comment, that is not possible as well. I'm going to try to use photoshop to draw exactly what I mean, I think I'm not being able to explain myself properly. Do you know of any tools to prototype I could use? I'm gonna start drawing on PS for now. Thanks.

You could describe the environment a little better. But, if RFID is the only technical possible solution, but it's not economical viable solution, it means that there is no solution ;D

My point being that your requirements have to change (or find a more practical approach, but that would require an awful lot of knowledge into the environment and probably even reshaping some requirements)

Well, yes, but I never said it was the only possible solution. Just that it was one that we found... hence why I'm here looking for a cheaper technology with a functionality similar to RFID. I'm going to update my post and explain in details what I need. :) I think now the example will be clear... :)

If there was something like RFID, but 10x cheaper, it would've been more common than RFID :p (or actually, nobody would use RFID, right?) I have no other solution as altering the requirements (by proving that the current requirements are too strict). And if that's impossible, you should reconsider your project. Trying to do the impossible sound honorable, but in practice it'll get you nowhere.

And I get the idea of detecting items that are being put in a bag. But you don't tell why you want to identify these? Are you making an "automatic shopping cart" or another way to sort items? I don't see in what context it will be used.

I don't have enough reputation here to start a chat, could you? I think it will be better. Thanks anyway :)

source: Stack Exchange

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

sort: votes


text:
Demux 1 LED at a time
I have the 14051 Demux set up with an Arduino Uno R3 and I am able to light up all three LED's at once with a 1 second delay however, I want to light up 1 LED at a time how can I do this?

My Hardware Setup

Sketch

/*  Arduino sketch   */

int64_t wait= 1000;
void setup()
{
  pinMode(7,OUTPUT);
  digitalWrite(7,LOW);
  DDRB = 0b00000111;  //PORT 8,9,10 as output
  PORTB = 0b00000000; //PORT 8,9,10 set to LOW
}

void loop()
{
  PORTB=0b00000000; //Data falow - X0
  uint8_t Sensor0 =  analogRead(A0); //read data from X0
  delay(wait);

  PORTB=0b00000001;  //Data flow - X1
  uint8_t Sensor1 =  analogRead(A0); //read data from X1
  delay(wait);

  PORTB=0b00000010;  //Data flow - X2
  uint8_t Sensor2 =  analogRead(A0); //read data from X2
  delay(wait);

  digitalWrite(7,HIGH);  // Inhibit / stop all data
  delay(wait);
  digitalWrite(7,LOW);  // Inhibit /  let data flow
}

How would analogRead(A0) be able to feed current to the selected LED? Looks like a lot of cut-and-paste-programming?

The answer is the same as the one to your other question, which to me looks like a duplicate. Anyway you should not read the data from the analog pin, but rather digitalWrite(A0, HIGH);

@frarugi87 Can you post an example of this code implemented with the sketch I posted.

@MALKAVIAN in the setup write pinMode(A0, OUTPUT); digitalWrite(A0, HIGH); and in the loop remove all the lines with the analogRead (the A0 pin is already high from the setup)

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


text:
Can I power ESP8266 with more than 3.5 V?
I am concerned whether I need to use a voltage divider to power my ESP8266 module. My concerns stem from the warnings that I have heard in multiple tutorials. Everyone seems to regard the ESP8266 as being very sensitive to supply voltage.
Has anyone use the ESP8266 with an supply voltage greater than 3.5 V? What were the effects? Is it even necessary to make a voltage divider?
I am asking because my application has limited real estate.

Surely you mean 3.3V :)

Some of the pins on ESPs are protected against excessive voltage, personally I always err on the side of caution and use regulators and level shifters, but with the real estate restrictions I'd suggest you check the manual on what the absolute maximum is that you version of the board can take.

Are you talking about providing power to the ESP, or just an input-pin? For power use a voltage regulator. For inputs you could indeed use a voltage divider.

To be clear I was talking about the power input.

If your voltage source is high enough, spend less than a buck on a regulator like a LD1117-3.3

you cannot power an ESP from a voltage divider because it's current is not steady.

My esp32 chip got fried when I supplied it with 3.5V (using an LM317) directly to the 3.3-pin. So.. very sensitive.

The datasheet usually is definitive on the allowable range of voltages.
Look in Section 5.1: Electrical Characteristics.
Working Voltage Value:

Min: 2.5 V
Typical: 3.3 V
Max: 3.6 V

If you have to feed in signals that could go higher than 3.3 V in normal operation, you need to either clamp it with Zener diodes, or use a voltage divider.
If you are asking about powering the chip with more than 3.3 V, don't. You can get away with a 3.3 V linear regulator and 2 capacitors so that you are powering it with no more than designed supply voltage.

The result to apply more voltage to a circuit is that the components will be burn. The same if you apply for a long time the maximum voltage. So the board works at 3.3v, your source maybe fluct between that but you will burn it if you apply 3.6 or more as a regular voltage.

Usually ESP8266 modules have an onboard voltage regulator, USB connector and a pin labeled 5V. This pin or the USB cable certainly tolerate resp. need a 5V power supply.
The ESP8266 controller itself will not survive 5V, neither at the Vcc nor at the signal pins.
BTW: a voltage divider (two resistors) is ok for signals, but does not help with the power supply.

I have 4 pieces of ESP01-S with DHT11 that connect to the WiFi every 30 minutes and send temperature data and then go into DeepSleep.  In addition, an ESP01-S as a motion detector and one as a push button.  These two usually in DeepSleep.
All are directly connected to a Li-Ion battery as power supply.  This has been running for over a year (except for changing the battery) and so far I haven't had any problems

Welcome to Arduino:SE.  I don't think this actually answers the question.

This is anecdotal information i.e. it might work for you but it (greatly) exceeds the manufacturer's specifications. Connecting directly to a Lithium Ion cell means the ESP8266 is exposed to voltages of over 4 V when the battery is fully charged.

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


text:
Parse Bluetooth string
I'm developing on android with bluetooth LTE, I can send hex codes, but I send one code at time, so I need to send many informations in this way, how can I recognize a string and save the datas inside an array to parse it later?
Here is my sketch:
 char c=' ';
 String inString,one,check;
 char inData[11];
 char inChar;
 int counter=0;
 bool started = false;
 bool ended = false;
 byte index;

boolean NL = true;
const int LED1 = 6;
const int LED2 = 7;
const int LED3 = 2;
const int LED4 = 3;
const int LED5 = 4;
const int LED6 = 5;

void setup() {
   Serial.begin(9600);
    Serial.print("Sketch:   ");   Serial.println(__FILE__);
    Serial.print("Uploaded: ");   Serial.println(__DATE__);
    Serial.println(" ");

    BTserial.begin(9600);
    Serial.println("BTserial started at 9600");

    pinMode(LED1, OUTPUT);
    pinMode(LED2, OUTPUT);
    pinMode(LED3, OUTPUT);
    pinMode(LED4, OUTPUT);
    pinMode(LED5, OUTPUT);
    pinMode(LED6, OUTPUT);

}

void loop() {

  if (BTserial.available()>0)
    {
      Serial.print("bts: ");
      Serial.println(BTserial.available());
      c = BTserial.read();
      check =  String(c, HEX);

      if(check=="ffbc"){
        Serial.println("check");
        index=0;
        while (BTserial.available()>0){

            inChar = BTserial.read();
            check=String(inChar,HEX);
            if(check != "0xfff3")
            {
                inData[index] = inChar;
                index++;
            }
        }
        for (int i=0;i<=11;i++){
          one =  String(inData[i], HEX);
          Serial.print(i);Serial.print(": ");Serial.println(one);
        };

      }

             if(check=="ffca"){
             // Serial.write(c);
              digitalWrite(LED1, !digitalRead(LED1));
             }
             if(check=="ffcb"){
              //Serial.write(c);
              digitalWrite(LED2, !digitalRead(LED2));
              }
              if(check=="ffcc"){
              //Serial.write(c);
              digitalWrite(LED3, !digitalRead(LED3));
             }
             if(check=="ffcd"){
              //Serial.write(c);
              digitalWrite(LED4, !digitalRead(LED4));
              }
              if(check=="ffce"){
             // Serial.write(c);
              digitalWrite(LED5, !digitalRead(LED5));
             }
             if(check=="ffcf"){
             // Serial.write(c);
              digitalWrite(LED6, !digitalRead(LED6));
              }
    }
}

Without the loop I can read all the single datas, but for my job it's not enough, to recognize the data applications I send a "sample string" to recognize the type of informations I want to send.

i think i solved in some way, i send always the same codes at the start and at the end of the datas, so i can racognize the end and then i parse the first element of the destination array. tell  me what you think abou, if it could help someone else:
 if (BTserial.available()>0)
{
  c = BTserial.read();
  check =  String(c, HEX);
  if(check!="fff3"){              // i always start wit an fff3
  inData[index] = c;
  index++;
 }
  else if(check=="fff3"){         //end of data
  index=0;                        //reset the index for the next set of data
  if(String(inData[1], HEX)=="ffbc"){
    Serial.println("read the next 10 data of the array");
    }else if(String(inData[1], HEX)=="11"){
    Serial.println("turn on led 1");
    }

    // for more operations use a switch/case over the if

  }

Why are you using a string to check for the start/end data? You can simply use the hex representation: if(c == 0xfff3). And I'm a bit confused, that you have a 4-digit hex code for one read operation. If you use the SoftwareSerial library as your BTserial object, a call of the read() function returns one byte at a time, so it would be a 2-digit hex code

hi, i'm using the bluetooth nativescript plugin, i don't know why but if i send a character after 9 arduino receives ffxx, (if i send 0xaa, it sends 0xffaa). when i made the first experiments i couldnt understnd the set of characters to parse, so i found the string. for the btserial i use altsoftserial


text:
How to send messages to multiple numbers using Arduino uno & SIM800 module?
I am using following code to send message using Arduino Uno & SIM800 module.
But I need to send same message on multiple numbers then what changes should I make in my code.
const int buttonPin = 8;   // Main gate sensor 1
const int buttonPin1 = 7;  // Main gate sensor 2
const int buttonPin2 = 9;  // Store room sensor 1
const int buttonPin3 = 10; // Store room sensor 2

bool i = false;
bool j = false;
bool k = false;
bool l = false;

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

  pinMode(buttonPin, INPUT);
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  pinMode(buttonPin3, INPUT);

  digitalWrite(buttonPin, LOW);
  digitalWrite(buttonPin1, LOW);
  digitalWrite(buttonPin2, LOW);
  digitalWrite(buttonPin3, LOW);

  delay(1000);
}
void loop()

{
  sensor1();
  sensor2();
}
  void sensor1()
  {
  if (digitalRead(buttonPin1)== LOW && digitalRead(buttonPin) == HIGH  && i == false)

  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91...................");
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main Gate is Closed");
    Serial.write(0x1A);
    delay(1000);
    i = true;
    j = false;

  }

  if (digitalRead(buttonPin)== LOW && digitalRead(buttonPin1) == HIGH &&  j == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91........................");
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main Gate is open");
    Serial.write(0x1A);
    delay(1000);
    j = true;
    i = false;
  }
  }
  void sensor2()
  {
  if (digitalRead(buttonPin2) == HIGH && digitalRead(buttonPin3)==LOW && k == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91....................");
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Closed");
    Serial.write(0x1A);
    delay(1000);
    k = true;
    l = false;
  }
  if (digitalRead(buttonPin3) == HIGH &&digitalRead(buttonPin2)== LOW && l == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91....................");
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Open");
    Serial.write(0x1A);
    delay(1000);
    l = true;
    k = false;
  }
}

Write a function that sends any message to any number and call it numerous times

@nilesh just add some delay between two massege
I modified your code check it
const int Main1 = 8;
const int Main2 = 9;
const int Store1 = 7;
const int Store2 = 10;
bool i = false;
bool j = false;
bool k = false;
bool l = false;

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

  pinMode(Main1, INPUT);
  pinMode(Main2, INPUT);
  pinMode(Store1, INPUT);
  pinMode(Store2, INPUT);

  digitalWrite(Main1, LOW);
  digitalWrite(Main2, LOW);
  digitalWrite(Store1, LOW);
  digitalWrite(Store2, LOW);

  delay(1000);
}
void loop()

{
  sensor1();
  sensor2();
}
void sensor1()
{
  if (digitalRead(Main1) == HIGH && digitalRead(Main2) == LOW && i == false)

  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91-----------");// first number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main gate closed");
    Serial.write(0x1A);
    delay(5000);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91-----------");// Second number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main gate closed");
    Serial.write(0x1A);
    delay(1000);
    i = true;
    j = false;

  }
  if (digitalRead(Main2) == HIGH && digitalRead(Main1) == LOW && j == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91---------------");//first number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main gate Open");
    Serial.write(0x1A);
    delay(5000);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91--------------"); second number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Main gate Open");
    Serial.write(0x1A);
    delay(1000);
    j = true;
    i = false;
  }
}
void sensor2()
{
  if (digitalRead(Store1) == HIGH && digitalRead(Store2) == LOW && k == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
   Serial.print("+91-----------");// first number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is closed");
    Serial.write(0x1A);
    delay(10000);
    Serial.print("AT+CMGS=\"");
    Serial.print("+91-----------");// second number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Closed");
    Serial.write(0x1A);
    delay(1000);
    k = true;
    l = false;
  }
  if (digitalRead(Store2) == HIGH && digitalRead(Store1) == LOW && l == false)
  {
    Serial.println("OK");
    delay(1000);
    Serial.print("AT+CMGF=1\r\n");
    delay(500);
    Serial.print("AT+CMGS=\"");
   Serial.print("+91-----------");// first number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Open");
    Serial.write(0x1A);
    delay(5000);
    Serial.print("AT+CMGS=\"");
   Serial.print("+91-----------");// Second number
    Serial.print("\"\r\n");
    delay(2000);
    Serial.print("Store room is Open");
    Serial.write(0x1A);
    delay(1000);
    l = true;
    k = false;
  }
}

thanks
bhupendra.sinkar727@gmail.com

I have same question but minor different.
sim.println("AT+CMGS="+91xxxxxxxxxx"\r");
i dont want to write this. i want to write mobile number on serial monitor in arduino and on that number, i want to send message. how can i do?

Try out this one. Here, I made the code for two number. Just simply add a new function for every new number. I hope it will help you.
const int buttonPin = 8;   // Main gate sensor 1
const int buttonPin1 = 7;  // Main gate sensor 2
const int buttonPin2 = 9;  // Store room sensor 1
const int buttonPin3 = 10; // Store room sensor 2

bool i = false;
bool j = false;
bool k = false;
bool l = false;

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

  pinMode(buttonPin, INPUT);
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  pinMode(buttonPin3, INPUT);

  digitalWrite(buttonPin, LOW);
  digitalWrite(buttonPin1, LOW);
  digitalWrite(buttonPin2, LOW);
  digitalWrite(buttonPin3, LOW);

  delay(1000);
}
void loop()

{
  sensor1();
  sensor2();
}

void sensor1()
{
  if (digitalRead(buttonPin1)== LOW && digitalRead(buttonPin) == HIGH  && i == false)
  {
    numOneGateClose();
    numTwoGateClose();
    i = true;
    j = false;
  }

  if (digitalRead(buttonPin)== LOW && digitalRead(buttonPin1) == HIGH &&  j == false)
  {
   numOneGateOpen();
   numTwoGateOpen();
    j = true;
    i = false;
  }
}

void sensor2()
{
  if (digitalRead(buttonPin2) == HIGH && digitalRead(buttonPin3)==LOW && k == false)
  {
    numOneRoomClose();
    numTwoRoomClose();
    k = true;
    l = false;
  }

  if (digitalRead(buttonPin3) == HIGH &&digitalRead(buttonPin2)== LOW && l == false)
  {
    numOneRoomOpen();
    numTwoRoomOpen();
    l = true;
    k = false;
  }
}

void numOneGateClose()
{
  Serial.println("OK");
  delay(1000);
  Serial.print("AT+CMGF=1\r\n");
  delay(500);
  Serial.print("AT+CMGS=\"");
  Serial.print("+91...................");
  Serial.print("\"\r\n");
  delay(2000);
  Serial.print("Main Gate is Closed");
  Serial.write(0x1A);
  delay(1000);
}

void numTwoGateClose()
{
  Serial.println("OK");
  delay(1000);
  Serial.print("AT+CMGF=1\r\n");
  delay(500);
  Serial.print("AT+CMGS=\"");
  Serial.print("+91...................");
  Serial.print("\"\r\n");
  delay(2000);
  Serial.print("Main Gate is Closed");
  Serial.write(0x1A);
  delay(1000);
}

void numOneGateOpen()
{
  Serial.println("OK");
  delay(1000);
  Serial.print("AT+CMGF=1\r\n");
  delay(500);
  Serial.print("AT+CMGS=\"");
  Serial.print("+91........................");
  Serial.print("\"\r\n");
  delay(2000);
  Serial.print("Main Gate is open");
  Serial.write(0x1A);
  delay(1000);
}

void numTwoGateOpen()
{
  Serial.println("OK");
  delay(1000);
  Serial.print("AT+CMGF=1\r\n");
  delay(500);
  Serial.print("AT+CMGS=\"");
  Serial.print("+91........................");
  Serial.print("\"\r\n");
  delay(2000);
  Serial.print("Main Gate is open");
  Serial.write(0x1A);
  delay(1000);
}

void numOneRoomClose()
{
  Serial.println("OK");
  delay(1000);
  Serial.print("AT+CMGF=1\r\n");
  delay(500);
  Serial.print("AT+CMGS=\"");
  Serial.print("+91...................");
  Serial.print("\"\r\n");
  delay(2000);
  Serial.print("Main Gate is Closed");
  Serial.write(0x1A);
  delay(1000);
}

void numTwoRoomClose()
{
  Serial.println("OK");
  delay(1000);
  Serial.print("AT+CMGF=1\r\n");
  delay(500);
  Serial.print("AT+CMGS=\"");
  Serial.print("+91...................");
  Serial.print("\"\r\n");
  delay(2000);
  Serial.print("Main Gate is Closed");
  Serial.write(0x1A);
  delay(1000);
}

void numOneRoomOpen()
{
  Serial.println("OK");
  delay(1000);
  Serial.print("AT+CMGF=1\r\n");
  delay(500);
  Serial.print("AT+CMGS=\"");
  Serial.print("+91........................");
  Serial.print("\"\r\n");
  delay(2000);
  Serial.print("Main Gate is open");
  Serial.write(0x1A);
  delay(1000);
}

void numTwoRoomOpen()
{
  Serial.println("OK");
  delay(1000);
  Serial.print("AT+CMGF=1\r\n");
  delay(500);
  Serial.print("AT+CMGS=\"");
  Serial.print("+91........................");
  Serial.print("\"\r\n");
  delay(2000);
  Serial.print("Main Gate is open");
  Serial.write(0x1A);
  delay(1000);
}

I would like to point out, that there really should be SEND MESSAGE method that would make the whole script shorter and easier to debug. Basic REUSE principle in programming.

it send message  to only first number

@NileshSurwade Have you write a different number on both functions? means you have to add different number in numOneSensor1() and numTwoSensor1(). And same things for numOneSensor2() and numTwoSensor2()

Lead by example. That code isn't a good example. As @Divisadero says, write a SEND MESSAGE function and reuse it many times.

@ Hasan sir, I added two different number in numOneSensor1() and numTwoSensor1(). And i done same thing for numOneSensor2() and numTwoSensor2(). But it does not work it only send massage on first number. Please help.

@NileshSurwade Ok, let me check and update my code again.

@NileshSurwade I update my code. I hope it will help.


text:
Why does my LCD screen display white rectangles?
I recently got an Arduino LCD screen. I tried connecting it to the UNO with the 10k potentiometer and all the needed equipment but all I got were white rectangles instead of characters. I have uploaded the hello world code but I saw no changes.

Looks like you may have the contrast set (or wired) wrong.

Or you have drawn white rectangles to the screen.

As @Majenko already mentioned, you have to set the right contrast. Use potentiometer to find out what value suits you right.


text:
Multimaster I2C with same address
I use the Wire Library and need to have multi-master setting. I see multi-master examples, where the masters have their own ID's -- which make sense.
Now I have just connected three devices on the bus with the same ID (for example 0x05) and they can communicate! Every node can listen to all traffic, which is not common but this was exactly what I want.
The question is: Will I have trouble in the future? Is my setup something like "multi-slave"?

If all the slaves do is listen that shouldn't be a problem. If you should ever want the slaves to talk back to the master then you will instantly get collisions and it will all fall apart.

actually this problem ist solved by a string-based protocol and any nodes sends only if it get requested. But didn't tested, what happends if they try to send in the same time. I use Wire.write and receiveEvent.

Andy, that is a problem. @Majenko, perhaps the Wire library accepts a wrong ack/nak at this moment, but that might change in the future. What about the clock pulse stretching for different slaves ? I see too many problems. When sending data to multiple slaves, you can use the broadcast. It is not enabled in the Wire library, but Nick Gammon shows how to enable it in the slaves: http://www.gammon.com.au/i2c Requesting data has to be done for each slave seperately. You have to stick to the standard rules. If you can make it work, it might fail in the future if the Wire libraries is improved.

I didn't knew about broadcasting, thanks. Your source seems to be very detailled

const byte MY_ADDRESS = x;  // where x is whatever unique address you like

byte RxByte[32]  //32 byte buffer

void setup() {
  //insert unique ddress
  Wire.begin(MY_ADDRESS);

// this line allows the arduino to listen for i2c broadcast at address 0

TWAR = (MY_ADDRESS << 1) | 1;
//set up a receive handler
 Wire.onReceive(receive_data);

then call
Wire.beginTransmission (0)  //transmit broadcast so all devices will receive

Wire.write( address of destination) // make the first byte the destination

Wire.endTransmission ();

then you need a receive handler

void receive_data() {
//use a buffer to temporarily store the data

for ( int d = 0; Wire.available() > 0 ;d++){

RxByte[d] = Wire.read();} // READ WIRE BUFFER UPTO 32BYTES, INTO AN ARRAY
datareceived = 1;

//then test if it was for this device
if (RxByte[0] == MYADDRESS){ do somthing with RxBytes[1-31];}
else {}

I use this extensively its very handy and works well I have a complex transmission table which has a 4 byte header and the rest of the bytes can be used as data send
destination, myaddress, a command, and how many data bytes to follow

Addendum to Original answer. below is a complete working example.
//so the basics of the tranmission table are the first 4 bytes (ie Rx or Tx byte 0-3 depending on if we are talking about the sender or recipient)
    //are used as a header 0= recipient (0 for broadcast. or address) 1= senders address 2= is the command (ie tells the recipient what to do)
    //and 4= the number of data bytes which follow in the packet
    //not all of these need to be specified at any time but its usefull to have a structure to follow at each end which never changes
    //copy and past this upload to 2 arduinos connected by i2c change the 2 addresses and it should work.
its a n example of how data can be moved around in a multi master situation
that should hopefully give you some ideas. it looks complicated but half of it is just generating some example data and triggering method and the transmit part is repeated 3 times to send out different data.. you should be able to create a more general purpose transmit block for your application
to send data just attach a button or wire to pin 2 directly to ground
watch the 2 serial windows
#include <Wire.h>
//device address  MAKE DIFFERENT FOR EACH

const byte MY_ADDRESS = 20;
const byte PARTNER_DEVICE = 25;

// transmission table stuff
byte RxByte[32]; //setup a receive buffer to hold data
byte TxByte[32]; //setup a transmit buffer to hold data
byte datareceived;

// stuff to generate some data
const int Sensor1 = A0;
byte SensorVal1 = 0;

//stuff to debounce pin 2
const byte digitalpin = 2;
byte pinstate = 0;
byte lastpinstate = 0;
unsigned long checktime = 0;
const byte debouncetime = 50;

// timer
unsigned long timing_loop = 5000;

void setup() {
  Wire.begin (MY_ADDRESS);
  TWAR = (MY_ADDRESS << 1) | 1;                                                      // ENABLE BROADCASTS TO BE RECEIVED
  Wire.onReceive(ReceiveData);     // INTERUPT ON I2C DATA RECEIVE
  Serial.begin(9600);
  pinMode (  digitalpin  , INPUT_PULLUP );// set the pin to input pullup so we can trigger the code by connecting directly to ground
  Serial.println( "READY" );
}

void loop() {
  // generate some random data

  GenRandData();
  //Serial.print(  pinstate);Serial.print( " " );Serial.println( lastpinstate );
  // debounces pin 2 so we can trigger a data broadcast
  pinstate = digitalRead (digitalpin);
  if ( pinstate != lastpinstate && millis() >= checktime) {
    if ( pinstate == 0 && lastpinstate == 1 ) {
      checktime = millis() + debouncetime;
      Serial.println( " button working" );
      REQUEST();
    }
    lastpinstate = pinstate ;
  }

  // this triggers the process data method after receive of data
  if (datareceived == 1  ) {
    datareceived = 0 ;
    ProcessData();
  }

  // 10 second timer triggers transmission of some data
  if ( millis() >= timing_loop ) {
    BROADCAST();
  }
}
void GenRandData() {
  // this just reads analog0 and maps it to a byte then sequentially shifts the transmit buffer
  SensorVal1 = random(255);
  TxByte[7] = TxByte[6];
  TxByte[6] = TxByte[5];
  TxByte[5] = TxByte[4];
  TxByte[4] = SensorVal1;
}

void ReceiveData() {
  // READ AVAILABLE BYTES INTO 32BYTE BUFFER (while data is available)
  for ( byte d = 0; Wire.available() > 0 ; d++) {
    RxByte[d] = Wire.read();
  }
  //set a trigger event
  datareceived = 1;
  Serial.println( "receive" );
}

void ProcessData() {
  Serial.println( "process" );
  // check what the data is an who its for then do something with it (RECEIVE TABLE)
  if (RxByte[0] == MY_ADDRESS) { // for this device
    switch (RxByte[2]) {
      case 1:       Serial.print("RECEIVED DATA FOR THIS DEVICE, = "); Serial.println( RxByte[4] ); break;
      case 255:       Serial.println("RECEIVED A REQUEST FOR DATA, SENDING READ FROM  > Sensor1"  ); ActAsMaster();              break;
      default:      Serial.print("D-Type byte = error"); Serial.println(RxByte[2]);                   break;
    }
  }

  else if (RxByte[0] == 0) {       //handle broardcast
    Serial.print( "RECEIVED BROADCAST FROM DEVICE = " ); Serial.println( RxByte[1] );
    Serial.print( "DATASIZE = " ); Serial.print( RxByte[3] ); Serial.println( " Bytes" );
    Serial.print( "DATABYTE 1 = " ); Serial.println( RxByte[4] );
    Serial.print( "DATABYTE 2 = " ); Serial.println( RxByte[5] );
    Serial.print( "DATABYTE 3 = " ); Serial.println( RxByte[6] );
    Serial.print( "DATABYTE 4 = " ); Serial.println( RxByte[7] );
    Serial.println( "DONE" );
  }
  Serial.println(  );
}

void BROADCAST() {
  // this is transmission table to send data to everyone
  Serial.println("Sending broadcast");
  byte count = 0;
  byte errorcode;
Tx:
  Wire.beginTransmission (0);                       // broadcast
  Wire.write(0);                                    // ADDRESS =0 BROARDCAST
  Wire.write(MY_ADDRESS);                           // SEND my address
  Wire.write(0);                                    // DATA TYPE CODE
  Wire.write(4);                                    //number of bytes being sent
  Wire.write(TxByte[4]);                            //data
  Wire.write(TxByte[5]);                            //data
  Wire.write(TxByte[6]);                            //data
  Wire.write(TxByte[7]);                            //data
  errorcode = Wire.endTransmission ();
  if (errorcode != 0 && count <= 2) {
    count++;
    Serial.println( "fail" );
    goto Tx;
  }
  //reset timer to run this again
  timing_loop = millis() + 10000 ;
  Serial.println(  );
}

void ActAsMaster() {
  //this is transmission table to send data to specific device OR return a result of a task
  Serial.println("Sending data");
  byte count = 0;
  byte errorcode;
Tx:
  Wire.beginTransmission (RxByte[1]);               //the return address
  Wire.write(RxByte[1]);                            //recipient address (return)
  Wire.write(MY_ADDRESS);                           // SEND MASTER ADDRESS
  Wire.write(1);                                  // DATA TYPE CODE
  Wire.write(1);
  Wire.write(SensorVal1);
  errorcode = Wire.endTransmission ();
  if (errorcode != 0 && count <= 2) {
    count++;  // if fail and not exceed count try again
    Serial.println( "fail" );
    goto Tx;
  }
  Serial.println(  );

}
void REQUEST() {
  //this is transmission table to send data request of partner device
  Serial.println("Sending request");
  byte count = 0;
  byte errorcode;
Tx:
  Wire.beginTransmission (PARTNER_DEVICE);               //the return address
  Wire.write(PARTNER_DEVICE);                            //recipient address (return)
  Wire.write(MY_ADDRESS);                           // SEND MASTER ADDRESS
  Wire.write(255);                                  // DATA TYPE CODE (MASTER ADDRESS)
  Wire.write(0);
  errorcode = Wire.endTransmission ();
  if (errorcode != 0 && count <= 2) {
    count++;  // if fail and not exceed count try again
    Serial.println( "fail" );
    goto Tx;
  }
  Serial.println(  );
}

i tried to keep it minimal but still show complete capability.. i guess im not very good at minimal.

//so the basics of the tranmission table  - are you writing code, or answering a question?

just trying to clearly explain whats going on.. this code is just a massively edited piece of a major project so it was significantly  easier to quickly assemble this than try to explain an answer..  after previous comment >>Please, post a minimal but complete sketch that compile OK. Your code is confusing for beginners, because it mix free text with code and have code not inside any function (like loop). – Look Alterno yesterday<<

thanks for detailled example. My code is the same like the first example code and works. I have to test the second example. But i dont see any software colision prevention. I would prefer to ignore collided and corupted frames just by a "software master", also there will be a changeable master, which will check communication and if there is collision than will try to fix it. Actually any software solution is better than a third line for me.

i havent done anything with collision detection and correcting in software as my hardware solution prevents it but this part >>errorcode = Wire.endTransmission ();
if (errorcode != 0 && count <= 2) {
count++;  // if fail and not exceed count try again
Serial.println( "fail" );
goto Tx;
} should at least try to make sure the packet is delivered as its probably unlikely for the collision to happen 3 times.

1 thing you could do here is use a couple mS delay if a collision occurs maybe using the address as means of making it different on each device(i use that for something else, works great) switching who is (official) master is easy just broadcast a specific message with the new master device address and have them all save that to memory for later use, or enable special functions


text:
Arduino fade to color change
I am making a fun LED Christmas tree project using this code:
// Source location \\adam\U_DRIVE\_BACKED_UP\_Documents\Electronics\XmasTree
#include <FastLED.h>
#define NUM_LEDS 102
#define DATA_PIN 6
CRGB leds[NUM_LEDS];
void setup() {
  Serial.begin(9600);
  Serial.println("Boot");
  // put your setup code here, to run once:
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);

  //  SetRandomLight;
  SetAllOff();
  delay(10); //Delay before getting going.
  BootUp();
  randomSeed(analogRead(0) + analogRead(1) + analogRead(2) + analogRead(3) + analogRead(4) + analogRead(5) + analogRead(6));
}

void loop() {
  // put your main code here, to run repeatedly:
  SingleDrift();
  FastLED.show();
  //delay(random(50));
}

void FadeAll(int x)
{
  for (int i = 0; i < NUM_LEDS; i++)
  {
    leds[i].subtractFromRGB(x);
  }
}

void SetRandomLight() {
  for (int i = 0; i < NUM_LEDS; i++)
  {
    leds[i].r = random(128);
    leds[i].g = random(128);
    leds[i].b = random(128);
    Serial.println(i);
  }
}

void SetAllOff()
{
  Serial.println("Blanking all.");
  for (int i = 0; i < NUM_LEDS; i++)
  {
    leds[i] = 0x000000;
    leds[i].r = 0;
    leds[i].g = 0;
    leds[i].b = 0;

    //Serial.println(i);
  }
  FastLED.show();
}

void SingleDrift() {
  int mini = 5;
  int maxi = 255;
  FastLED.setBrightness(maxi);
  for (int i = 0; i < NUM_LEDS; i++)
  {
    if (leds[i].r > 64) leds[i].r = leds[i].r - 8;
    if (leds[i].g > 64) leds[i].g = leds[i].g - 8;
    if (leds[i].b > 64) leds[i].b = leds[i].b - 8;

    int rnd = random(10);
    if (rnd == 1 && leds[i].r >= 2) leds[i].r = leds[i].r - 1;
    if (rnd == 2 && leds[i].g >= 2) leds[i].g = leds[i].g - 1;
    if (rnd == 3 && leds[i].b >= 2) leds[i].b = leds[i].b - 1;
    if (rnd == 4) leds[i].fadeToBlackBy(2);
    if (rnd == 5) leds[i].g++;
    //if (rnd == 6 && leds[i].g < 240) leds[i].g = leds[i].g + 1;
    //if (rnd == 7 && leds[i].b < 240) leds[i].b = leds[i].b + 1;
    if (leds[i].g < 2) leds[i].g = 2;
  }

  int i = random(NUM_LEDS);
  Serial.println(i);
  if (leds[i].r + leds[i].g + leds[i].b > 10) return; //If the LED is still bright, do not change it.
  if (random(100) > 80)
  {
    //Choose a colour
    int r = random(20);
    switch (r)
    {
      case 99:
        for (i = 0; i < NUM_LEDS; i++)
        {
          int x = leds[i].r;
          leds[i].r = leds[i].b;
          leds[i].b = x;
        }

      case 1:
      case 2:
      case 3:
        leds[i] = CRGB::Red;
        break;
      case 4:
      case 5:
      case 6:
        leds[i] = CRGB::Green;
        break;
      case 7:
        leds[i] = CRGB::Blue;
        break;
      case 8:
        leds[i].r = random(128, 255);
        leds[i].g = random(128, 255);
        leds[i].b = random(128, 255);
      case 9:
        leds[i] = CRGB::Yellow;
        break;
      case 10:
        leds[i] = CRGB::Crimson;
        break;
      case 12:
        leds[i] = CRGB::Aqua;
        break;
      case 13:
        leds[i] = CRGB::BlueViolet;
        break;
      case 14:
        leds[i] = CRGB::MidnightBlue;
        break;
      case 15:
        leds[i].setRGB( 255, 255, 255);
        break;
    }
  }
}

void BootUp()
{
  for (int i = 0; i < NUM_LEDS; i++)
  {
    leds[i].b = map(i, 0, NUM_LEDS, 0, 255);
    leds[i].r = map(i, NUM_LEDS, 0, 0, 255);
  }
  for (int pc = 0; pc < 100; pc++)
  {
    FastLED.setBrightness(pc);
    FastLED.show();
    delay(3);
  }
  for (int i = 0; i < NUM_LEDS; i++)
  {
    leds[i] = -leds[i];
    FastLED.show();
    delay(10);
  }

  for (int i = 0; i < NUM_LEDS; i++)
  {
    leds[i].setRGB( 0, 10, 0);

    FastLED.show();
    delay(10);
  }
}

The LED cycle currently fades to green every time, so I would like to add different color fades. However, I could not figure out how to change the color/timing after poking around. Could someone please point me in the right direction for what I changes to the code I need to make?

why don't you look at the example code in the fastLED library? ... you should be able to find it in the example sketches in the arduino IDE

That code is a bit of a mess. It has some code that will never execute, as well as very confusing structure.
If it were me I would throw away that code and start over with code that does some other animation. You won't break anything, so play.
As to the code you posted:
It looks to me like the first for loop that cycles through all the LEDs is set to first fade all the LEDs down towards 0 brightness by 8 while their value is > 64.
After the global fade, it then uses a random number 0-9 to decide what to do next for each LED.

If the random value is 1, 2, or 3, it reduces the red, green, or blue channels by 1.
If the random value is 4, it drives the current LED to black.
If the random value is 5, it increases the green channel of the current LED by 1.
finally, it sets the green channel of the current LED back to 2 if it drops below 2. That means that every LED will end up with flicker with a dim green color unless the next section changes that LED's color to something different.

I added "**this" comments to the lines that drive the LEDs towards green.
  for (int i = 0; i < NUM_LEDS; i++)
  {
    if (leds[i].r > 64) leds[i].r = leds[i].r - 8;
    if (leds[i].g > 64) leds[i].g = leds[i].g - 8;
    if (leds[i].b > 64) leds[i].b = leds[i].b - 8;

    int rnd = random(10);
    if (rnd == 1 && leds[i].r >= 2) leds[i].r = leds[i].r - 1;
    if (rnd == 2 && leds[i].g >= 2) leds[i].g = leds[i].g - 1;
    if (rnd == 3 && leds[i].b >= 2) leds[i].b = leds[i].b - 1;
    if (rnd == 4) leds[i].fadeToBlackBy(2);
    if (rnd == 5) leds[i].g++;  //**This will tend to make this LED flicker green.
    //if (rnd == 6 && leds[i].g < 240) leds[i].g = leds[i].g + 1;
    //if (rnd == 7 && leds[i].b < 240) leds[i].b = leds[i].b + 1;
    if (leds[i].g < 2) leds[i].g = 2; //**This will make each LED stop at dim green.
  }

If you want the LEDs to end up at some color other than green, you might want to change those last lines of the first for loop You could change that first section to something like this:
  for (int i = 0; i < NUM_LEDS; i++)
  {
    if (leds[i].r > 64) leds[i].r = leds[i].r - 8;
    if (leds[i].g > 64) leds[i].g = leds[i].g - 8;
    if (leds[i].b > 64) leds[i].b = leds[i].b - 8;

    int rnd = random(11);
    if (rnd == 1 && leds[i].r >= 2) leds[i].r = leds[i].r - 1;
    if (rnd == 2 && leds[i].g >= 2) leds[i].g = leds[i].g - 1;
    if (rnd == 3 && leds[i].b >= 2) leds[i].b = leds[i].b - 1;
    if (rnd == 4) leds[i].fadeToBlackBy(2);

    if (rnd == 5) leds[i].g++;  //**This will tend to make this LED flicker green.
    if (rnd == 6) leds[i].r++;  //**This will tend to make this LED flicker red.
    if (rnd == 7) leds[i].b++;  //**This will tend to make this LED flicker blue.

    if (rnd == 8) && (leds[i].g < 2) leds[i].g = 2; //**This will make the LED go dim green
    if (rnd == 9) && (leds[i].r < 2) leds[i].r = 2; //**This will make the LED go dim red
    if (rnd == 10) && (leds[i].b < 2) leds[i].b = 2; //**This will make the LED go dim blue
  }

Then it picks one random LED, and 20% of the time, does more random stuff to the color of that LED if it is dim enough. It uses a random value from 0-19 to decide what to do in the next switch statement. The first case is case 99:, which can never execute because the random value will never be greater than 19. For other values, it forces that LED to be a bright primary color, or maybe white, or maybe a color with random RGB values ranging from 128 to 255.

I think line 84 that keeps the leds green instead of going black. I think line 81 is there to create some kind of shimmer effect on some of the green leds and to skew the color to a bit more green. So I removed those. To prevent the leds from going to black instead of green, I added an if statement that stops any further fading out, if the total "brightness" is 16 or lower. I have no idea how this will look. You might have to tweak this 16-value a bit.
That's the best I could do without a full rewrite of the code.
void SingleDrift() {
  int mini = 5;
  int maxi = 255;
  FastLED.setBrightness(maxi);
  for (int i = 0; i < NUM_LEDS; i++)
  {
    if (leds[i].r > 64) leds[i].r = leds[i].r - 8;
    if (leds[i].g > 64) leds[i].g = leds[i].g - 8;
    if (leds[i].b > 64) leds[i].b = leds[i].b - 8;

    if ( (leds[i].r + leds[i].g + leds[i].b) > 16) // prevent fading to black
    {
      int rnd = random(10);
      if (rnd == 1 && leds[i].r >= 2) leds[i].r = leds[i].r - 1;
      if (rnd == 2 && leds[i].g >= 2) leds[i].g = leds[i].g - 1;
      if (rnd == 3 && leds[i].b >= 2) leds[i].b = leds[i].b - 1;
      if (rnd == 4) leds[i].fadeToBlackBy(2);
      //if (rnd == 5) leds[i].g++;
      //if (rnd == 6 && leds[i].g < 240) leds[i].g = leds[i].g + 1;
      //if (rnd == 7 && leds[i].b < 240) leds[i].b = leds[i].b + 1;
      //if (leds[i].g < 2) leds[i].g = 2; // I think this line kept the leds green
    }
  }
  ...

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


text:
How to properly use interruptions with twi (I2C)
I would like to reprogram Wire.h, or a part, to use interruptions, in order to not waste time to wait. I'm using an Arduino Mega with an Adafruit motor shield v2.3.
In the datasheet, page 262, 24.9.2, bit 0, I can read that I have to set the TWIE flag to one to be able to catch the interruption.
So, I started to write this code :
//https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf

#include <avr/interrupt.h>

#define ADDRSHIELD 0xC0//adresse sur 8 bits

#define TWI_FREQ 100000L
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |=  _BV(bit))

#define START       0x08  //TWI start
#define MT_SLA_ACK  0x18   //slave ACK has been received
#define MT_DATA_ACK 0x28   //master ACK has been received

#define LED0_ON_L 0x6

#define TWI_STATUS      (TWSR & 0xF8)

int etat = 0;
uint8_t currentstep = 0;
uint8_t _addr;
uint8_t _data;

ISR(TWI_vect)
{
  //I remove the TWINT flag
  TWCR |= (1<<TWINT);

  switch(etat)
  {
    case 0:
      //start has been send, let's check if it's ok
      if(TWI_STATUS == START)
      {
        //on charge l'adresse dans TWDR et on clear le bit TWINT dans TWCR pour demarrer la transmission
        TWDR = _addr;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 1;
        //Serial.println(etat);
      }
      else
      {
        etat = -1;
      }
      break;
    //addr has been send
    case 1:
      if(TWI_STATUS == MT_SLA_ACK)
      {
        TWDR = _data;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 2;
        //Serial.println(etat);
      }
      else
      {
        etat = -2;
      }
      break;
    //data have been send
    case 2:
      if(TWI_STATUS == MT_DATA_ACK)
      {
        // disable twi module, acks, and twi interrupt
        TWCR = (1<<TWIE)|(1<<TWEN)|(1<<TWSTO);
        etat = 3;
        //Serial.println(etat);
      }
      else
      {
        etat = -3;
      }
      break;
    //stop condition
    case 3:
      // desactivate internal pullups for twi.
      digitalWrite(SDA, 0);
      digitalWrite(SCL, 0);
      etat = 0;
      //Serial.println(etat);
      //Serial.println("Next");
      break;
  }
}

void sendData(uint8_t addr, uint8_t data)
{
  _addr = addr;
  _data = data;

  i2cSetup();
  //start condition
  TWCR = (1<<TWSTA)|(1<<TWEN)|(1<<TWIE);
}

void i2cSetup(void)
{
  // activate internal pull-ups for twi
  sbi(PORTD, 0);
  sbi(PORTD, 1);

  // initialize twi prescaler and bit rate
  cbi(TWSR, TWPS0);
  cbi(TWSR, TWPS1);

  TWBR = ((F_CPU / 100000) - 16) / 2;
}

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

void loop()
{
  if(etat == 0)
  {
    sendData(0xC0, 0b1010101);
  }
  if(etat == 3)
  {
      Serial.println("Next");
  }
  if(etat == -1)
  {
    Serial.println("Error from start");
    delay(100);
    exit(-1);
  }
  if(etat == -2)
  {
    Serial.println("NACK");
    delay(100);
    exit(-1);
  }
  if(etat == -3)
  {
    Serial.println("DATA NACK");
    delay(100);
    exit(-1);
  }
}

My problem is, once I reset TWIE to one on my interruption, the code looks like to freeze(in ISR(), case 0, TWCR =...). In my mind, the interruption is call only when TWIE is set to one and when the twi module says (when he sets TWINT to one I guess) that he finished the job. I don't understand how to properly use this interruption.
EDIT :
Thanks to @jfpoilpret, know I clearly know the problem, the slave doesn't reply by an acknowledge (in my switch, case 0, the status isn't equal to START (0x08)). In the datasheet, p246, they clearly explain how to use registers, but I'm not sure how to use the flag TWIE. I don't know if I have to set them both to one, or if i have to completely leave TWINT (I tried both, but nothing worked...).
Thanks for your help,
julien

First off, when using interruptions, you must make your ISR code as quick as possible. In particular, NEVER USE Serial.print... from an ISR.

I thought Serial.print wasn't too long. I'll modify my code.

Well, there is no more print in my ISR. Thanks you, so know I clearly know the problem, the slave doesn't reply by an acknowledge (in my switch, case 0, the status isn't equal to START (0x08)). I'll edit my question.

Well, after some tests, I achieved to make all of this working, thank you !

Great! Can you please post, as an answer, the modifications you made so that this can help other people with the same problem in the future?

Of course, I was doing it. Thank you a lot for your tips !

Perfect. Here is an additional hint to improve your program: make volatile your global variables when they are shared between your ISR and the rest of your code (i.e. etat, _addr and _data) otherwise the compiler might optimize access to these, thinking they never change.

One last point I think you should fix (I did not pay attention to it before, sorry): etat is currently an int (2 bytes), reading or writing it requires several assembly instructions and hence may be interrupted. You should rather declare it as int8_t (one byte only, access not interruptible) as it still fits values you need.

Done. Again, thanks ! If you have 3 minutes, you could post all of this as an answer, I would be glad to check it as the answer !

Well I believe there must be other general answers on this site about how to properly write ISR functions. I just wanted to quickly point you about some important hints for your code. One last point: you declared etat as uint8_t instead of int8_t: they are one byte each, but first one is unsigned, not suitable for negative values you assigned it, although it will probably work -maybe some compiler warnings- as long as you don't try if (etat < 0) which won't work.

Exactly, that's what append when I don't think... Thanks !

After some tests, it's working !
First off all, I used Serial.println in my ISR, that's made it freeze apparently.
Second, apparently, I can't send more than 6 bits, else I'll have an error (data NACK), I thought it was 8.
This is my code working :
//https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf

#include <avr/interrupt.h>

#define ADDRSHIELD 0xC0//adresse sur 8 bits

#define TWI_FREQ 100000L
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |=  _BV(bit))

#define START       0x08  //TWI start
#define MT_SLA_ACK  0x18   //slave ACK has been received
#define MT_DATA_ACK 0x28   //master ACK has been received

#define LED0_ON_L 0x6

#define TWI_STATUS      (TWSR & 0xF8)

volatile int8_t etat = 0;
volatile uint8_t _addr;
volatile uint8_t _data;

ISR(TWI_vect)
{
  switch(etat)
  {
    case 0:
      //start has been send, let's check if it's ok
      if(TWI_STATUS == START)
      {
        //on charge l'adresse dans TWDR et on clear le bit TWINT dans TWCR pour demarrer la transmission
        TWDR = _addr;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 1;
      }
      else
        etat = -1;
      break;
    //addr has been send
    case 1:
      if(TWI_STATUS == MT_SLA_ACK)
      {
        TWDR = _data;
        TWCR = _BV(TWIE) | _BV(TWEN);
        etat = 2;
      }
      else
        etat = -2;
      break;
    //data have been send
    case 2:
      if(TWI_STATUS == MT_DATA_ACK)
      {
        // disable twi module, acks, and twi interrupt
        TWCR = (1<<TWIE)|(1<<TWEN)|(1<<TWSTO);
        etat = 3;
      }
      else
        etat = -3;
      break;
    //stop condition
    case 3:
      // desactivate internal pullups for twi.
      digitalWrite(SDA, 0);
      digitalWrite(SCL, 0);
      etat = 0;
      break;
  }
  //I remove the TWINT flag
  TWCR |= (1<<TWINT);
}

void sendData(uint8_t addr, uint8_t data)
{
  _addr = addr;
  _data = data;

  i2cSetup();
  //start condition
  TWCR = (1<<TWSTA)|(1<<TWEN)|(1<<TWIE)|(1<<TWINT);
}

void i2cSetup(void)
{
  // activate internal pull-ups for twi
  sbi(PORTD, 0);
  sbi(PORTD, 1);

  // initialize twi prescaler and bit rate
  cbi(TWSR, TWPS0);
  cbi(TWSR, TWPS1);

  TWBR = ((F_CPU / 100000) - 16) / 2;
}

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

void loop()
{
  if(etat == 0)
  {
    sendData(0xC0, 0b0010101);
  }
  if(etat == 3)
  {
      Serial.println("Next");
  }

  if(etat == -1)
  {
    Serial.println("Error from start");
    delay(100);
    exit(-1);
  }
  if(etat == -2)
  {
    Serial.println("NACK");
    delay(100);
    exit(-1);
  }
  if(etat == -3)
  {
    Serial.println("DATA NACK");
    delay(100);
    exit(-1);
  }
}

Thanks a lot to jfpoilpret !

Note that you can accept your own answer after some days by clicking on the tick beside it.

Two observations.

The datasheetss does a fairly good job of Laying out the states and required conditions to move forward. Your code simply needs to mimic that. A short cut is to take a look at lpc210x datasheetss as it has fairly simple c code for the state machine implementation in the Isr.
What I typically do for slow multi byte transmission, i2c or UART, is to point a pointer to a string to be transmission, load up the datasheetss register and enable the interrupt. In the Isr, test if all the data has been transmission. If yes, turn off the Isr. Otherwise, load up thee next char. The data received can be processed via a callback function.

This approach minimizes user involvement. On a SPI with buffer, it can transmit without interruption.

Why ?
The Arduino Mega 2560 is not very fast. The gain by using interrupts is not a lot.
The Wire.endTransmission and Wire.requestFrom wait until the I2C transaction has finished. That might seem a waste of time, but for the slow ATmega microcontrollers, not a lot of time is wasted.
The overhead by more code might even slow it down. A I2C library that is completely in software might even be faster than the original Arduino Wire library. Although the Arduino Wire library uses interrupts, the overhead by the Wire library creates a few extra delays during the I2C transaction.
It took years (it really did) to have a normal working Wire library for ATmega microcontrollers and it still is not very good. For example a hardware problem on the I2C bus could halt a sketch. I have seen a number of custom I2C libraries that run into problems one way or the other.
You can waste less time with:

Make a well designed sketch, using millis instead of delay.
Write a good interface to the sensor. I see a lot bad usage of the Wire library with unnecessary I2C transactions.
Increase the I2C speed to 200kHz or 400kHz with Wire.setClock.
Try to use the SPI bus if possible. For a 3.3V sensor with a SPI interface, a 3.3V Arduino board is the best choice. For example the Arduino Due with ARM M4 or a small board with ARM M0+ processor.
When using the SPI bus with a Ethernet shield, try setting the SPI bus faster.
When using a SD card, try full speed, instead of half speed.
Use the newest Arduino IDE, because the 'lto' optimization was enabled which helps a lot.

Really serious work for better I2C functions has been done for the Teensy. It is still compatible with the Arduino Wire functions, but extra functions have been added that do not wait.

I need it because I use interruptions (every 1ms) to call functions to read sensors, etc etc, and to send data in I2C. If I used wire.h, it tooks 3.6ms to send my data. Even if I wanted to use it  in 400kHz, and if it would took 0.9ms, it's always too loog, because I need additional time in the loop() to manage others things. So, with this, I can manage I2C with others things.

I only use delay() to let the time to Serial.println to print the error, before the exit(). I need I2C because my shield work with that.

Thank you for answering my "Why"-question. jfpoilpret has been a very good help (for example with the volatile single bytes). You use a complete I2C transaction for just one data byte for the motor shield every millisecond. Is that really needed ? For a software PWM signal ? I wonder what the other code is. Doing so many things every millisecond with a ATmega chip might be pushing the limit. You could try the MultiSpeed I2C scanner to test the I2C bus: http://forum.arduino.cc/index.php?topic=197360

Not only 1 byte, little bite more. Yes, it's for a PWM signal. The other code is to manage a Lora connection, logs, and maybe others futur things. I honeslty don't know if I need to send everytime the same data, I just mimic this library : https://github.com/adafruit/Adafruit_Motor_Shield_V2_Library Why would I push to the limit the ATmega ? If it isn't in my interruption, it would be in my loop(). Thank you for the scanner, I'll try it !

The PCA9685 on the motor shield creates the PWM signal. I tried to read the Adafruit library to understand why you need software PWM, but I don't understand it. Using software PWM via I2C at 1000 times per second can't be right. To set individual pins via I2C for a stepper motor is a bad idea, then you need a better motor shield. Either use the Arduino Stepper or the Mikem AccelStepper directly with Arduino pins, or a shield that can do that on its own. Perhaps someone else knows that Motor Shield, or you could try to ask on the Adafruit forum.

Thanks for you help :) Apparently, the library set only one time de PWM at the beginning, and then only manage which coil is feed or not.  Sorry if I wasn't clear, I make many mistakes in English.

It is only a PWM shield ? Then using the Arduino pins (with a 'dumb' motor driver module) would be better for a small and large stepper motor. Or maybe a complete module that drives the stepper motor and can do ramps, for a large stepper motor. Well, if you have it working now you can keep using it, but it is far from ideal.


text:
Two signal with delay
I have a two pins for two blinks leds but I need delay the second signal from first. I start the first signal and I need start the second signal 50ms later. The first signal is 500ms HIGH and 500ms LOW, and the second signal is 400ms LOW and 600ms HIGH. If I start the second signal 50ms later, I can center the high period of the first signal with the low period of the second signal.
This is my code:
long DelaySecondSignal = 50;
int A = 1;

while (A == 1)
{
    long millis_actuales = millis();

        //Control Salida_A
        if (millis_actuales - TiempoTranscurrido_SalidaA > (Estado_SalidaA ? 500 : 400)) {
            digitalWrite(SalidaA, Estado_SalidaA = !Estado_SalidaA);
            TiempoTranscurrido_SalidaA = millis_actuales;
        }

        if (millis_actuales > DelaySecondSignal)
        {
            //Control Salida_B
            if (millis_actuales - TiempoTranscurrido_SalidaB > (Estado_SalidaB ? 500 : 600)) {
                digitalWrite(SalidaB, Estado_SalidaB = !Estado_SalidaB);
                TiempoTranscurrido_SalidaB = millis_actuales;
            }
        }
}

TiempoTranscurrido_?? is a int and Estado_Salida? is a boolean.
I need start the second signal with 50ms of delay but "if (millis_actuales > DelaySecondSignal)" no work.
Thanks.

Your problem is that you are treating both signal separately. Instead you need to think about the events of turning LEDs on and off and where they lie on a combined timeline:
     0    100   200   300   400   500   600   700   800   900  1000
     |-----|-----|-----|-----|-----|-----|-----|-----|-----|-----|
     ^  ^                       ^  ^
  1 on  2 off                2 on  1 off
  1: ooooooooooooooooooooooooooooooo
  2: oooo                       oooooooooooooooooooooooooooooooooo

You see how I have looped the time around so that the turning off of the second signal, which would normally come at 1050ms, in fact comes at 50ms. By just working in a single 1000ms block of time as a loop things become much simpler.
You can do it now with just a simple set of delays, now you have it laid out in a single timeline like that:
void loop() {
    digitalWrite(led1, HIGH);
    delay(50);
    digitalWrite(led2, LOW);
    delay(400);
    digitalWrite(led2, HIGH);
    delay(50);
    digitalWrite(led1, LOW);
    delay(500);
}

All the delay() calls add up to 1000ms and it keeps looping around.
If you want to make it non-blocking you should set it up with a small finite state machine. There are 4 steady states which are the four spaces between the events on the timeline. There are 4 transitions, which are the events on the timeline.  So you:
Start in state 0 with both LEDs on (which is how they are at the start of the timeline).

0: When 50ms have passed turn off LED 2 and move to state 1.
1: When 400ms have passed turn on LED 2 and move to state 2.
2: When 50ms have passed turn off LED 1 and move to state 3.
3: When 500ms have passed turn on LED 1 and move to state 0.

This example work perfect, I can change the duty cycle and work. I have another question, How make this example without "delay()"?

Like I say in the second half of my answer - with a Finite State Machine.

I'd just base everything of millis.
int A = 1;

while (A == 1)
{
    int phase = millis() % 1000;// modulo 1 second

    // turn on A for the first 500ms of a period, and off for the rest
    if( phase<500 )
        digitalWrite(SalidaA, HIGH);
    else
        digitalWrite(SalidaA, LOW);

    // turn on B for the first 50ms, and last 550ms of a period, and off for the rest
    if( phase<50 || phase>=450 )
        digitalWrite(SalidaB, HIGH);
    else
        digitalWrite(SalidaB, LOW);

}

I did not explain myself well. This example works but not well, for example if I change the length of the period, no work ok until after 1 second. For example, I have a Rate that is "150". I divide 60 seconds beetwen 150 and I have 0.4. Now I need repeat 50% HIGH - 50% LOW of cycle in 400ms in period A, but for example the period B is 35% HIGH - 65% LOW (35*400/100 =  140ms HIGH and 400-140= 260ms LOW).

Majenko does not have this problem in his example because he repeats the cycle all time, so I asked if he knows how to do the same example with the milis() function. I need a similar PWM function with center aligned.

Just multiply all the numbers by this 0.4. So 1000 becomes 400; 50 becomes 20 etc.

Now work, I changed "millis() % 1000;" by "millis() % 400;" and work ok but I DON'T KNOW WHY IT WORK, sorry. :(

Do you know how modulo works? It's like like looking at a clock and saying; I don't care about the hours or minutes, I just want to know the seconds. After that you say; the first 5 seconds of every minute I want output A HIGH, the next 20 seconds LOW, and the rest of every minute HIGH again. For output B I want the output to be HIGH the first 30 seconds of every minute, and LOW the other 30 seconds.


text:
Not understanding C++ arrays
I'm attempting to re-write a library for the CD74HC4067 multiplexer.  There is a library available for this device on the Arduino Playground, however, it's limited in its functionality.
I have this as a private data member in the class header file:
uint8_t channelSelects[16][4];

And this in the class constructor:
CD74HC4067::channelSelects[16][4] = {
    { 0,0,0,0 }, // channel 0
    { 1,0,0,0 }, // channel 1
    { 0,1,0,0 }, // channel 2
    { 1,1,0,0 }, // channel 3
    { 0,0,1,0 }, // channel 4
    { 1,0,1,0 }, // channel 5
    { 0,1,1,0 }, // channel 6
    { 1,1,1,0 }, // channel 7
    { 0,0,0,1 }, // channel 8
    { 1,0,0,1 }, // channel 9
    { 0,1,0,1 }, // channel 10
    { 1,1,0,1 }, // channel 11
    { 0,0,1,1 }, // channel 12
    { 1,0,1,1 }, // channel 13
    { 0,1,1,1 }, // channel 14
    { 1,1,1,1 }  // channel 15
};

And I'm getting this error:
cannot convert '<brace-enclosed initializer list>' to 'uint8_t {aka unsigned char}'

Could someone please explain what I'm not understanding here ?
Many thanks in advance.

Are you sure that brace enclosed initializer list can be used in normal assigment beyond variable/const init ?

Actually, no I'm not.  The only difference I see here is the library available on the Arduino Playground has the channel selects defined as external (extern) and defined outside the class.

Aha, the channel select is static init ? So add type:
uint8_t CD74HC4067::channelSelects[16][4] = { .... };

If you have in your constructor this:
CD74HC4067::channelSelects[16][4] = ...

then you are trying to assign something into the element at position [16][4]. Thats why it's telling you

cannot convert '' to 'uint8_t {aka
  unsigned char}'

Anyway - you don't even need that second dimension. You can use binary representation like  0b00001000 ...
And if you'll think about previous line, you don't even need any array, you can do it with simple counter value and getting its bits.
However if you want to rely on this array, the constructor should look like:
CD74HC4067::CD74HC4067() :
  channelSelects {
    { 0,0,0,0 }, // channel 0
    { 1,0,0,0 }, // channel 1
    { 0,1,0,0 }, // channel 2
    { 1,1,0,0 }, // channel 3
    { 0,0,1,0 }, // channel 4
    { 1,0,1,0 }, // channel 5
    { 0,1,1,0 }, // channel 6
    { 1,1,1,0 }, // channel 7
    { 0,0,0,1 }, // channel 8
    { 1,0,0,1 }, // channel 9
    { 0,1,0,1 }, // channel 10
    { 1,1,0,1 }, // channel 11
    { 0,0,1,1 }, // channel 12
    { 1,0,1,1 }, // channel 13
    { 0,1,1,1 }, // channel 14
    { 1,1,1,1 }  // channel 15
  }
{
   // constructor code
}

(maybe one more {} enclosure, I'm not sure right now exactly)
EDIT: I'd go this way (if you need only one or two instances):
// ADC READ channel + Address selection pins
template <uint8_t ADC_Chan, uint8_t Addr0, uint8_t Addr1, uint8_t Addr2, uint8_t Addr3>
class Mux16b {
public:
  void initPins () {
    pinMode(Addr0, OUTPUT);
    pinMode(Addr1, OUTPUT);
    pinMode(Addr2, OUTPUT);
    pinMode(Addr3, OUTPUT);
    pinMode(ADC_Chan, INPUT);
  }

  int readMux(uint8_t channel) {
    digitalWrite(Addr0, channel&1 != 0);
    digitalWrite(Addr1, channel&2 != 0);
    digitalWrite(Addr2, channel&4 != 0);
    digitalWrite(Addr3, channel&8 != 0);
    // maybe some delay to stabilize voltage at the ADC_Chan input ??
    return analogRead(ADC_Chan);
  }

  // not necessary but it's easier to use   mux(10) than mux.readMux(10)
  int operator()(uint8_t channel) { return readMux(channel); }
};

// analogRead from A0, Address pins: 4 9 5 2
Mux16b<A0,4,9,5,2>  mux;

void setup() {
  Serial.begin(115200);
  mux.initPins();
}

void loop() {
  Serial.println(mux.readMux(15));

  Serial.println(mux(12)); // using overloaded operator ()

  delay(5000);
}

Thank you, KIIV.  However, this initialization is based on the original library for the device as well as an example at http://bildr.org/2011/02/cd74hc4067-arduino/.  There are 4 separate control pins the device needs to connect to on the Arduino, hence the second dimension of the array.

In the example there is declaration and initialization at once. In the class you have declaration in the class and initialization later. In the definition brackets means size (number of elements). Anywhere else it means accessing element at passed position (index)

Thanks again, KIIV.  I somewhat understand.  I moved the initialization to the header file where it was first declared, then got undefined reference for the destructor.  I commented-out the destructor in the header file and it compiled without errors.  Not real sure I like the destructor being commented-out, though.

Concerning my last comment, I was missing the destructor in the .cpp file.  I added it, and it compiled without errors.

@GregoryR.Pace I can imagine that code without any variable just by using template class. It's perfect if you have one instance (or two). For more instances with different template parameters it might take more code space.

I moved the initialization to the header file where it was first declared...  It compiled without errors.

You may just print out the array as well, compiling w/o errors doesn't neccesarily mean it does exactly what you think it does ;p Also, the values in your array are 4-bit LSB representations of the integers 0to15, you can store this much more efficiently or calculatie it runtime. Or consider using an array of objects/(bit-)structs instead of an array of arrays of unsigned chars, only to represent bools.

You need , at the channel 15 line too.

Thank you, Andreas.  I just added the comma, but still getting the same error.

That last comma is optional.


text:
My code is not uploading to Arduino Uno, Please help!
I am very new to arduino, so new that it is my first board. I keep running into this error
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00

I have searched the internet for hours, tried solutions from almost every StackExchange question related to this topic, and even Reddit posts but none of those have been able to help me. All my settings are as they are supposed to be. Both the correct board and serial port are selected but it still keeps giving me this error:
System wide configuration file is "/home/rahat/Desktop/Arduino/arduino-1.8.13/hardware/tools/avr/etc/avrdude.conf"
User configuration file is "/home/rahat/.avrduderc"
User configuration file does not exist or is not a regular file, skipping
   ` Using Port                    : /dev/ttyS4
     Using Programmer              : arduino
     Overriding Baud Rate          : 115200`

 avrdude: stk500_recv(): programmer is not responding  avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
Also my operating system is Ubuntu 20.04 LTS

You have the wrong port selected. It should be /dev/ttyACM0 or /dev/ttyUSB0

There are no ports /dev/ttyACM0 or /dev/ttyUSB0 available to me

@Majenko the only port available to me is /dev/ttyS4

Then you either have no acess rights or hardware issue.
Try lsusb. and post us an output. If it finds the hardware stating something like 'QinHeng Electronics HL-340...' (there are others).  We will try to trace access issue.
If lsusb doesnt see it then its most likely a cable, but other options are we will trace when it comes to it...

in some cases you may have to use sudo lsusb

Did you do the proper permissions? https://www.arduino.cc/en/Guide/Troubleshooting#upload (Drivers - Linux)

First of all find out on which port the Arduino is connected by running the command : dmesg | grep tty. You should get [82893.921017] usb 1-1: cp210x converter now attached to ttyXXX with the ttyXXX COM port.
Then check if the port is visible Tools->Port. If the port is not visible then you have a permission issue.


text:
'MeDCMotor' does not name a type error inside mBlock
I was using a 3rd party programming enviroment, mBlock 3.4.5 for making C++ Arduino programmes with a graphical programming language. I was compiling a program and the following eroor came up.
project_Untitled0_0.ino:65:1: error: 'MeDCMotor' does not name a type
project_Untitled0_0.ino:66:1: error: 'MeDCMotor' does not name a type
project_Untitled0_0.ino: In function 'void move(int, int)':
project_Untitled0_0.ino:85:7: error: 'motor_9' was not declared in this scope
project_Untitled0_0.ino:85:24: error: 'M1' was not declared in this scope
project_Untitled0_0.ino:86:7: error: 'motor_10' was not declared in this scope
'MeDCMotor' does not name a type

I took another look at the program and there were some lines of code that seem they are added in the program by deafult:
MeDCMotor motor_9(9);
MeDCMotor motor_10(10);
void move(int direction, int speed)
{
      int leftSpeed = 0;
      int rightSpeed = 0;
      if(direction == 1){
            leftSpeed = speed;
            rightSpeed = speed;
      }else if(direction == 2){
            leftSpeed = -speed;
            rightSpeed = -speed;
      }else if(direction == 3){
            leftSpeed = -speed;
            rightSpeed = speed;
      }else if(direction == 4){
            leftSpeed = speed;
            rightSpeed = -speed;
      }
      motor_9.run((9)==M1?-(leftSpeed):(leftSpeed));
      motor_10.run((10)==M1?-(rightSpeed):(rightSpeed));
}

Since the program does not recognise the MeDCMotor class the program failed to upload.
I am running Windows 10 home edition on a 64-bit laptop.
Is there a way to remove the lines of code that prevent me from uploading the sketch or are there other ways to solve it?

Yes, just remove them, and the lines that refer to them, and so on. Of course they're there for a reason so the program won't do what it's supposed to do.  As you have correctly identified, it can't find that class.  Perhaps you're missing a #include, perhaps it's not in the library to be included. Hard to tell from the (lack of) detail in the question.

The lines of code mentioned above are dedicated toother tipes of robots, that can be programmed with the software and are useless on the Arduino. The lines of code cannot be deleted, beacause the code that is displayed is just for preview.

You're having trouble with a non-standard piece of software, and you don't even mention what it is.  Maybe you can find the files on disk somewhere and edit them there.  Otherwise, you'll have to give us a bit more of a clue, I suspect.

I looked at some entries in a google search for error: 'MeDCMotor' does not name a type, such as 1, 2, 3 and 4.  The first three of those latter four links directly address the question you ask, and none of them answer it clearly, except to suggest re-downloading or re-installing the makeblock library.  While the fourth link addresses a “does not name a type” error for another library, rather than for makeblock, it has a relatively clear explanation of the problem for that other library:

So, as supplied, the ArduinoByteBuffer.zip file had a complex set of sub-directories, and the two files ByteBuffer.ccp and ByteBuffer.h were located one level down in: \ArduinoByteBuffers\ByteBuffer\
When I 'installed' the library, it went into the directory:

C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer\ByteBuffer.ccp
       C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer\ByteBuffer.h

To solve the problem I moved them up a level to:

C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer.ccp
       C:\Documents and Settings\Al\My Documents\Arduino\libraries\ArduinoByteBuffers\ByteBuffer.h

That seemed to be the key - moving the two files (*.ccp and *.h) out of the subdirectory.

Instead of following ordinary C or C++ library-finding rules, the Arduino IDE copies sets of files into a temporary directory according to its own rules when compiling a sketch.  You'll need to move your makeblock library files around to match up with Arduino IDE conventions.

In the MakeBlock, menu "choice of extensions", uncheck all the extensions, keeping only the one called "Makeblock" checked:


text:
Arduino - Windows can't find the drivers
I bought an Arduino UNO R3 Yesterday. It's a Chinese clone. But it has the Atmega328p and MEGA16U2 both.
I've installed the IDE fully. But it can't find the ports. The Tools > Ports option is greyd out, Cannot find The options Named "Ports (COM & LPT)" or "Other Devices" in device manager. Can't upload any sketch to board.
I tried this on my both Win7 SP1(32 BIT) & Win10, which are installed in the same pc but in different partitions. I've roamed accross stackexchange but no successful result.

Have you tried a different USB cable?

There's no issue with my cable I think. The green & orange both LEDs light up when plugged in.

That only means it's getting power. Some cheap (especially chinese) cables don't have data wires, only power wires. Try another cable. One you know for certain works.

That might be. But the drivers ought to be show themselves in the device manager. Or do they require proper connection?

The drivers don't show, only the device shows. If the device isn't detected there will be nothing there. Windows contains thousands of drivers. If the device manager listed the drivers instead of the detected devices it would be completely unmanageable.

I've tested my usb cable and it has data wires inside. And they're all conducting.

Let us continue this discussion in chat.

Maybe they forgot to install the firmware in the ATMega16U2?


text:
Play sound with speaker inside interrupt while a timer runs
I'm attempting to start a timer lasting a specific interval when the ultrasonic distance sensor measures a distance lower than 25 cm. Once that occurs, I want the speaker to make sound if the distance goes above 25 cm whilst the timer is running. I am attempting to use an interrupt to do this, but I'm having trouble.
This is what I have so far:
void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), sensor, CHANGE);
}

int makeSound() { // This function creates the sounds
  ...
}

int echo() { // This function gets the distance the sensor is measuring
  ...
}

void loop() {
  distanceCm = echo();
  if (distanceCm < 25) {
    Timer();
  }
}

int Timer() {
  half_hour_millis = millis();

  while (millis() < half_hour_millis + interval) {
    // Here goes the code that I haven't written and was hoping you could help me with
  }
}

// My interrupt function
void sensor() {
}

All the level changing on the interrupt pin is complete before the timer loop is started, so you can't interrupt the loop.  Sounds like thinking of your problem as three states: idle, armed, and triggered would be good.  Given the way you are polling distance measurement, I'm not sure that you need to use the interrupt if you get the transitions between those states right.

Indeed I don't, but I'm trying to get to know interrupts.

Andrew,
I think I see what you're trying to accomplish. I would try something like the following, and I'll explain afterward:
boolean timerRunning = false;
unsigned long start_millis;
unsigned long end_millis;

boolean tripped() //was int Start()
{
  dist = echo1();
  if (dist < 25 && dist > 0) {
    return true;
  else
    return false;
}

void loop()
{
  if(tripped())  //check for < 25cm
  {
    //if tripped and timer not running, start
    //keeping track of time
    if(!timerRunning)
    {
      timerRunning = true;
      start_millis = millis();
      end_millis = start_millis + half_hour;
    }
    //if timer already running, print millis
    else
    {
      Serial.println(millis()); //or Serial.pringln(millis()-start_millis);
                    // for time since timer started
    }
  }
  else  //not < 25cm, not tripped
  {
    //if not tripped and timer running, time for sound
    if(timerRunning)
    {
      timerRunning = false; //might as well stop timer
      alert();
    }
    //if timer not started and not tripped nothing to do
  }

  //finally, lets check time, if past half hour, stop tracking
  //elapsed time
  if(timerRunning)
  {
    if(millis > end_millis)
    {
      timerRunning = false;
    }
  }
}//end void loop()

In general, you don't want to block the loop() from looping. Some of the Arduino functions do their processing outside that loop (the interrupt pin possibly too).
I know I'm not using the interrupt, but for a couple reasons. First, it looks like the pin can only change if you call your echo1() function, as you have to trigger the ultrasonic transmitter. Secondly, the state of the pin will not reflect the distance, only that it's receiving sound. As an aside, for what it looks like you were trying to do, you would have wanted to attach the interrupt and detach the interrupt only when the timer started or ended, as opposed to in the setup. Otherwise it could interrupt at any time, such as everytime the echo1() was called.
Hopefully my code comments help explain the flow. Basically I'm keeping track of the state of things, mostly with 'timerRunning'. Based on whether the timer is running and the ultrasonics are tripped (measuring less than 25cm), the appropriate actions are taken. The only way to stop the timer is the elapsing of half an hour, or the alert condition.
Double check my math, but i think there are 1,800,000 milliseconds in half an hour, so you will want to change your constant. Also, I don't know how long you plan on having your device run, but the millis() function will rollover back to 0 after about 50 days. Your end time will end up calculating out to less than the current time and the timer will not be able to run properly (will immediately stop) for that last half hour until rollover. Just something to keep in mind.
Hope this helps and good luck!

Exactly what I needed! and thanks for the lesson heh. Oh, and I'm aware of the limit of millis(), and 50 days will be more than enough, so no problem :)

I'm aware of the limit of millis(), and 50 days ... the 50 day "limit" is only a problem if programmed poorly. Otherwise, not an issue.

To avoid the rollover problem, just code the comparison correctly instead of incorrectly.  That is, delete end_millis = start_millis + half_hour; and replace if(millis > end_millis) [sic] with if(millis()-start_millis > half_hour) because that arithmetic works ok (assuming half_hour < 2³¹)


text:
LED doesn't register as LOW after a switch has cut all power to it
I have the following build:

And the following code:
const int buttonPin = 3;
const int ledPin = 2;
int buttonState = 0;

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

  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

}

void loop() {
  while (digitalRead(ledPin) != LOW){
    buttonState = digitalRead(buttonPin);

    if (buttonState == LOW){
      digitalWrite(ledPin, LOW);
    }
  }
}

But it doesn't seem like anything is registered, as my program doesn't respond to the shut down of the LED. What have I done wrong?

Please post an actual schematic. Why do you have constants like buttonPin and ledPin and then ignore them and have pinMode(2, INPUT); and pinMode(3, OUTPUT);?

I've tried to post an actual schematic now + changed the code

On what did you base your wiring? I think/see that there are multiple wiring issues.

Try again. R1 (at the top) doesn't seem to be connected to anything. And as for the switch, is it supposed to short out the LED?

Yes, it's supposed to turn it off

These things are called "circuits" for a reason. The electrons go around in a circuit. You only have one wire to the Arduino so it is hard to see how anything happens.

Modified the build, take a look again, please. I still don't register anything though when the LED gets shut down by the switch

Looking at your schematic, I get a bit confused.
You should start out with creating the schematic, try to base it on existing schematics on the web/tutorials.
I believe you're trying to read out a button and set an led accordingly?
So start out with the schematic and then try to build a breadboard setup for this. Randomly wiring things up on your breadboard doesn't really make sense, you need a plan.
I've created a shematic of which I believe should work a treat.

simulate this circuit – Schematic created using CircuitLab
Using internal pull-ups on the SW1, to avoid the input floating.
Using 220ohms resistor, based on "Basic Red 5mm - Sparkfun LED", 5V source, 2V forward 16mA (http://led.linear1.org/1led.wiz).
Be carefull not to set the SW1 as an output (high) and push the button, this theoretically burns out the I/O pin.
But even then, this is only basic, you may want to consider input protection (http://www.thebox.myzen.co.uk/Tutorial/Protection.html)
It's very easy to mess something up or do something incorrectly in electrical engineering. To be honest, it may help to watch a lot of tutorials or read books on electronics. It's very usefull to have a basic understanding before wiring things up.
At least base your actions on a (good) tutorial or reference material from Arduino self.
Try to wire up the circuit according to my schematics
Mouseover for example (but please try it yourself before checking!)

The same actually counts for programming, first try to make it clear what you want to achieve. Maybe even write out the steps that your program should do on a functional level.
I have no idea how you program could actually compile, the while and if statements don't have any closing brackets.
const int buttonPin = 2;//I switched the LED and button in my design.
const int ledPin = 3;//So the LED is on a PWM pin, which makes more sense.

void setup() {
  //Serial.begin(9600); //We're not using serial, so why start serial?
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
}

void loop() {
   int value = digitalRead(buttonPin);
   digitalWrite(ledPin, value);
   //or digitalWrite(ledPin,digitalRead(buttonPin));//for short
}

Thank you for this elaborate answer ... Seems like I made everything more difficult, hah. Sorry everyone. Anyway, I forgot to add the closing brackets, I've added them now.

@andrew no point, starting out with something can be hard/confusing. That's why it helps to read some tutorials, they often include wiring diagrams (and sometimes pictures) and put the code in the end, so you can verify if it's working.

Indeed, thanks. I have a question though, why does it make more sense to put the LED on a PWM pin?

Ah, pwm can be used to dim the LED, it's nothing critical, but it's nice to have such a feature.

Alright, I'll keep that in mind. Thanks for all the help, doesn't seem like my badly-formulated question deserves an answer.

The diagram is open to several different interpretations, depending on what's inside the four-terminal switch.  On many such SPST switches, two adjacent terminals are connected to each other inside it, and the other two likewise.  Which are which in the diagram isn't indicated.
That aside, what is clear from the diagram is that pin 2 is connected by wires to +5V, and will always read in as high.

Edit 1:
The schematic [posted later] is unclear.  It should be arranged so that solid lines represent wires or pins, with solid lines between things that are connected.  Place items in the drawing to reduce unnecessary and confusing crossing lines.  For example, supposing that the dashed line from pin 2 of R1 represents a wire between pin 2 of R1 and pin 2 of LED1, it is unclear whether the wire bends around the top right pin of S1 (can't read number) or connects with that pin on its way to LED1.  For another example, nothing is shown connecting to pin 1 of R1, and only one long dashed line connects the R1/S1/LED1 group to the Uno.

Please take another look, I added a new diagram.

I don't get a plausible understanding of the wiring from either the diagram or the schematic.  Also see edit 1.

Sorry ... I'm new at this. Pin3 is connected to the LED. It is the crooked wire. Pin2 is connected to the switch. It is wire no. 2 from the left. The first wire from the left connects the resistor to the switch