Unable to Configure MQTT Client ID using Adafruit MQTT Library I am utilizing the MQTT library that Adafruit has created, located here, and the library itself works wonderfully - however I am finding myself unable to edit the Client ID or configure the PINGRESP. The code that I am currently using can be seen below -

WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, "10.116.10.191", 1883);

When the client connects to the MQTT Broker the client ID turns into a random string of letters, numbers, and symbols, as seen below -

1534023607: Client ]7llG5K6J4=^tPHJHqgTUFc<Ep^m3vJ`4vSL2oB<cO[^_chw[GBp]v3smagpOqWS has exceeded timeout, disconnecting.
1534023608: New connection from 10.116.7.21 on port 1883.
1534023608: New client connected from 10.116.7.21 as ^k_aQq];7xigbIUD`htDex>IPfAoNX:4JiUkR9vY9WG[`m`GL[KqZJAk7RaEkkIu (c1, k300).
1534023608: Sending CONNACK to ^k_aQq];7xigbIUD`htDex>IPfAoNX:4JiUkR9vY9WG[`m`GL[KqZJAk7RaEkkIu (0)
1534023608: Received SUBSCRIBE from ^k_aQq];7xigbIUD`htDex>IPfAoNX:4JiUkR9vY9WG[`m`GL[KqZJAk7RaEkkIu
1534023608:     quantity (QoS 0)
1534023608: ^k_aQq];7xigbIUD`htDex>IPfAoNX:4JiUkR9vY9WG[`m`GL[KqZJAk7RaEkkIu 0 quantity
1534023608: Sending SUBACK to ^k_aQq];7xigbIUD`htDex>IPfAoNX:4JiUkR9vY9WG[`m`GL[KqZJAk7RaEkkIu

After a duration of time has passed the client exceeds the time out and disconnects.. Any advice on overcoming this obstacle would be greatly appreciated. I've tried the following for changing the ClientID, per the client constructor to the MQTT broker -

Adafruit_MQTT_Client(Client *client, const char *server, uint16_t port,
   const char *cid, const char *user, const char *pass):

WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, "10.116.10.191", 1883, "Rear-Controller");

This was the result of adding the clientID, ("Rear-Controller"), after the MQTT Broker port # -

 New client connected from 10.116.7.21 as GFONMktFXFSG1rARE@JWCRv@P^XwLifdo<rCg]YFs4Ndf_>2_XIsjFsAtS08Cf\: (c1, k300, uRear-Controller)

The Client ID is expected to be stored in flash memory (it is read using pgm_read_byte). However, on the Arduino, unless told otherwise it first copies the string literal into RAM.  That means that the function is getting the address of the string in RAM, not in flash, and using it as if it were the address in flash, and that gets gibberish.

You need to force it to be in flash by creating a PROGMEM string:

const char clientid[] PROGMEM = "clientfoo";
Adafruit_MQTT_Client mqtt(&client, "10.116.10.191", 1883, clientid);


Can't identify + or - in the 5v USB wall adapter, does it matter? I want to power the UNO with the USB power adapter (the charger of a phone), the adapter delivers 5.0 volts and comes from the wall (in the photo a regulator is added). However, the legs of the USB adapter look the same, can I plug it to the wall indistinctly like I do when I charge the phone, or do I need to know which leg is + and which one is - ? (I don't have measurement equipment).

Power (which comes from your wall outlet), is AC, which means alternating current. It changes 50 or 60 times per second from direction, so this is the reason it does not matter if you plug it reversed or not. Some countries have plugs which can be plugged in normally or 180 degrees rotated (but you cannot see what is 0 or 180 degrees since these are symmetrical).

The circuit inside the adapter makes sure the AC is converted to DC, where it matters what is Plus or Minus.


How to add Ultrasonic Sensor to the board? I am making an RC car , have combined the Arduino UNO R3 with the AR 293d, and pluged in the HC-SR04 sensor to the SRO4 hole at the left top corner in the below graph. However, besides one sensor  I would like to add three more HC-SR04 sensor.

Reference:
http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/

The problems are

1) is the board sufficient to plug three more sensor ?

2) or what extra board I need if not sufficient and how to combine those board

2) also, can I plug in other hole?

Thanks for helping

Update: breadboard connection

So I have to get a stuff like this?

http://www.tandyonline.co.uk/small-solderless-breadboard.html

and one more question, sorry for begin newbie, there are many holes on breadboard, which hole I should connect those three sensor on it, and the hold I should connect the breadboard with the AR-293D board?

And for programming, is there any way to get the pin at the breadboard as I have read some program before, the pin is assign with a number?

Thanks again for helping.

1) Not really. You have so little space and you have to selder them. Try using wires

2) If you want it to be flexible use a sandard solderless breadoard on the center of the car and then with male-female jumperwires try connecting them.

3) The board has traces. That means some holes have a very specific purpose.

Updated:

On every breadboard the holes are connected verticaly. For example, in the image from your breadboard you posted 1A, 1B, 1C, 1D and 1E are connected together.
If you would like to have all of the 3 sensors better use wires and then atach them on to your breadboard.

Here is a picture:
https://www.dropbox.com/s/3ij4w6eytio8p08/Screen%2016-25-31.png?dl=0


How can I work with two devices that use the SPI protocol? I'm working with a project in which I need to use an SD card module and an RFID antenna simultaneously. The devices that I'm using are the MFRC522 and the CATALEX SD Card Adapter. Both have SPI Protocol, and they're using the libraries MFRC522.h and SD.h.

This is the pin layout that I'm using:

/////// For RFID //////////
             Arduino
             Mega
  Signal     Pin
  ---------------------
  RST/Reset  5
  SPI SS     53 (CUSTOM)
  SPI MOSI   51
  SPI MISO   50
  SPI SCK    52

//////// For SD ///////////
             Arduino
             Mega
  Signal     Pin
  ----------------------
  SPI SS     49 (CUSTOM)
  SPI MOSI   51
  SPI MISO   50
  SPI SCK    52

As you can see the only line that they are not sharing is the Slave Select (aside from the RST pin of the RC522 module), so I believe that my wiring is correct.
I tried setting in LOW the chip select of the device that I wanted to use and in HIGH the one that I didn't. But this didn't work.

Any help you could provide would be appreciated! Thanks!

If that SD card adapter looks similar like the picture, I never could get it to work together with another SPI device.

What I used was a data logger shield for Arduino (with SD card slot and proto part, unused in my case), something like this: SD logger


Arduino ESP8266 Ticker interrupted by DallasTemperature/OneWire? I have been using the Ticker to blink a led successfully.
However, now I am fetching temperature from a DS18B20 in the main loop (which is using the OneWire library) and the blink is now erratic.

Is the Ticker suspended by the DallasTemperature/OneWire library?

It this suspending interrupts or something?

Maybe using the same interrupt?

Ticker does not interrupt your code. It is a OS-timer and will call your function once the time is elapsed.

The Tiker callback can be interrupted by a "real" interrupt or another Task with higher priority and does not provide any reliability - it will just be called.

A solution (not the best) would be to disable manually all interrupts, if you can't solve it in another way.

If you just want a blinking led, you should use a Timer interrupt as your callback is short and fast. Maybe with the ICACHE_RAM_ATTR attribute.


Temperature control using a DHT11 I am trying to do a project on temperature control and found an example but cannot get the code to work. I have read forums and tried to fix the issue which is below the code.

Code:

#include<DHT.h>      // Including library for dht
#include<LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
#define dht11dpin 12
DHT11;
#define pwm 9
#byte degree[8] =
{
  0b00011,
  0b00011,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000
};

#void setup()
{
  lcd.begin(16, 2);
  lcd.createChar(1, degree);
  lcd.clear();
  lcd.print("   Fan Speed  ");
  lcd.setCursor(0, 1);
  lcd.print("  Controlling ");
  delay(2000);
  analogWrite(pwm, 255);
  lcd.clear();
  lcd.print("Circuit Digest ");
  delay(2000);
}

void loop()
  DHT11.read(DHT11pin);
  int temp = DHT11.temperature;
  lcd.setCursor(0, 0);
  lcd.print("Temperature:");
  lcd.print(temp);   // Printing temperature on LCD
  lcd.write(1);
  lcd.print("C");
  lcd.setCursor(0, 1);
  if (temp < 26 )
  {
    analogWrite(9, 0);
    lcd.print("Fan OFF            ");
    delay(100);
  }
  else if (temp == 26)
  {
    analogWrite(pwm, 51);
    lcd.print("Fan Speed: 20%   ");
    delay(100);
  }
  else if (temp == 27)
  {
    analogWrite(pwm, 102);
    lcd.print("Fan Speed: 40%   ");
    delay(100);
  }
  else if (temp == 28)
  {
    analogWrite(pwm, 153);
    lcd.print("Fan Speed: 60%   ");
    delay(100);
  }
  else if (temp == 29)
  {
    analogWrite(pwm, 204);
    lcd.print("Fan Speed: 80%    ");
    delay(100);
  }
  else if (temp > 29)
  {
    analogWrite(pwm, 255);
    lcd.print("Fan Speed: 100%   ");
    delay(100);
  }
  delay(3000);
}

Error:

In file included from C:\Users\neilb\Documents\Arduino\sketch_jan20b\sketch_jan20b.ino:2:0:
C:\Users\neilb\Documents\Arduino\libraries\DHT_sensor_library/DHT.h:32:15: error: expected unqualified-id before numeric constant
 #define DHT11 11
               ^
C:\Users\neilb\Documents\Arduino\sketch_jan20b\sketch_jan20b.ino:6:1: note: in expansion of macro 'DHT11'
 DHT11;
 ^
C:\Users\neilb\Documents\Arduino\libraries\DHT_sensor_library/DHT.h:32:15: error: expected initializer before numeric constant
 #define DHT11 11
               ^
C:\Users\neilb\Documents\Arduino\sketch_jan20b\sketch_jan20b.ino:35:1: note: in expansion of macro 'DHT11'
 DHT11.read(DHT11pin);
 ^
sketch_jan20b:36: error: request for member 'temperature' in '11', which is of non-class type 'int'
 int temp=DHT11.temperature;
                ^
sketch_jan20b:37: error: 'lcd' does not name a type
   lcd.setCursor(0,0);
   ^
sketch_jan20b:38: error: 'lcd' does not name a type
   lcd.print("Temperature:");
   ^
sketch_jan20b:39: error: 'lcd' does not name a type
   lcd.print(temp);   // Printing temperature on LCD
   ^
sketch_jan20b:40: error: 'lcd' does not name a type
   lcd.write(1);
   ^
sketch_jan20b:41: error: 'lcd' does not name a type
   lcd.print("C");
   ^
sketch_jan20b:42: error: 'lcd' does not name a type
   lcd.setCursor(0,1);
   ^
sketch_jan20b:43: error: expected unqualified-id before 'if'
   if(temp <26 )
   ^
sketch_jan20b:50: error: expected unqualified-id before 'else'
     else if(temp==26)
     ^
sketch_jan20b:57: error: expected unqualified-id before 'else'
      else if(temp==27)
      ^
sketch_jan20b:64: error: expected unqualified-id before 'else'
      else if(temp==28)
      ^
sketch_jan20b:71: error: expected unqualified-id before 'else'
     else if(temp==29)
     ^
sketch_jan20b:77: error: expected unqualified-id before 'else'
      else if(temp>29)
      ^
sketch_jan20b:83: error: expected constructor, destructor, or type conversion before '(' token
   delay(3000);
        ^
sketch_jan20b:84: error: expected declaration before '}' token
 }
 ^
exit status 1
request for member 'temperature' in '11', which is of non-class type

It's a bit hard to see, but

DHT11;

does not look like a correct statement, assuming DHT11 is a class (not a define like shown) it should be something like

DHT11 dht;

where dht is an instance and you can use that.

Than in

DHT11.read(DHT11pin);

you should replace it by

dht.read(DHT11pin);


Adapt program to suit Arduino UNO I am trying to use a program that has been written for  STM32 microprocessor for interfacing with a Time to Digital Converter TDC GP22 via SPI interface. I would like to use the same program and adapt it to suit Arduino Uno for interfacing with TDC GP22. This would really help save a lot of time.

Can someone please suggest me the most effective way to do this ?

You'll be wasting your time tring to convert the code on a procedure by procedure basis.  Arduino has different libraries, different clocks, different pins, etc.

I suggest you flowchart the code, and then work out which of the Arduino libraries (SPI, LCD, etc.) you can use to achieve the flow.  You'll be able to drop some of the initialisation code probably as Arduino is easier to run "out the box".

There's no quick-and-easy solution here - it's a re-write... as you'll find is often the case migrating code from one MCU to another.


What is the maximum wire length for serial communication between two Arduinos? I am building a project in which two Arduinos will be linked by three wires: TX an RX for serial communication and a common GND. What would be the maximum length of the wires here before communication gets affected?

I am using an Arduino Mega R3 on one side and an Arduino Mini on the other one.

I have no particular requirement for the Baud rate, I could use the lowest one if this helps in any way.

You need to specify

The order of range you are interested in - is it in the order of metres, tens of metres, kilometers or interstate ?:-) . ALL are possible with suitable compromise.
How you intend to connect to the circuit - direct Arduino pins, high/low buffer, differential drivers, ...

If you use 5V/0V "unipolar" then at say 9600 baud you can get many metres with suitable drivers. If you use an Arduino pin directly wire resistance and inductance will start to matter as range increases.

At 300 baud you can achiever hundreds of metres with twisted pair cables. As range increases aspects like cross-talk from the other circuit and external noise increase in importance. At longer ranges having 4 wires with signal + ground twisted together in each case helps BUT it is likely that at ranges of interest 2 wires plus ground will work OK.

If you are prepared to use enough voltage and slow enough signalling you can signal over thousands of miles - as was done with very early telegraph cables. The thousands of volts needed and signalling speeds of perhaps a few bits per second will be a disincentive in most cases.


Recover from wrong Wi-Fi password on Arduino Yún I'm trying to customize my Arduino Yún to work as an access-point (or hotspot) for providing services to clients directly connected and, alternatively, to work as a client on a wireless network for downloading resources from the Internet.

The access to such a wireless network is gained after the user submits a network SSID and password in the web control panel provided by Yún.

How can I recover from a user submitting a wrong password? At the moment the Yún stays stuck without any connection, and thus is unreachable via SSH to attempt any recover.

The simplest option is to provide a serial console interface which will either give full access to the OS (pipe through Console) or a menu driven interface that sends instructions to the main chip (through Bridge).

The user would then connect to the USB interface and use a terminal program to access the configuration in whatever way you have chosen.  This could either be via options within your installed sketch, or by uploading a special sketch through the USB connection.


ESP send data to Arduino I'm trying to send data from my esp to my arduino using serial using the following codes :

esp :

server.on("/drive",HTTP_GET, handleDrive);
void handleDrive()
{
    server.send(200,"text/html", "Drive!");
    String sendToArduino = "";
    for (int i=0;i<server.args();i++)
    {
   sendToArduino = sendToArduino+server.argName(i)+"="+sendToArduino.arg(i)+"&";
    }
    Serial.println(sendToArduino);
}

and on arduino :

Serial.begin(9600);
esp8266.begin(115200);

if (esp8266.available())
{
   String  readString="";
   while (esp8266.available())
   {
     delay(2);
     char c = esp8266.read();
     readString += c;
   }
}

but when i send data from esp to arduino i get it with "noise"

Ex : "variable1=1234"   i recive it on arduino "variab@e=12"
What can i make to make sure that what i send is same in arduino ?

Firstly you need to write a more reliable serial reading routine on the Arduino. As it stands your routine is lucky you even get what you do. You need to write a routine that doesn't care about time, but instead cares about the terminating character of the line you are receiving.

Here is an article I wrote all about it.

Secondly, you cannot communicate reliably using SoftwareSerial at 115200 baud.  While the Arduino is capable of receiving a byte at that baud rate using bit banging, there typically isn't enough time between successive bytes to allow the Arduino to store what it has just received, and so it starts receiving partway through the next byte, corrupting both it and the following byte. That's the cause of the corruption you are seeing.

You should either slow down the baud rate (9600 is a good choice), or send the data one byte at a time and add a delay between each byte (somewhat hacky...).


Binary addressing and coding to control a 96 input mux matrix I’m trying to wrap my head around using binary addresses in a mux. Failing miserably.
For the circuit I have six 16 channel analog multiplexers CD74HC4067 as slaves to an eight channel multiplexor CD54HC4051 master.
They are bringing in 96 sensor readings (IR receiver diodes through Op Amps) into an array
that, in turn,  is used to constantly update lotsa LEDs through a series of shift registers (TLC5940) using the Arduino TLC5940 Library.

I’ve included the possible wiring scheme that the code is trying to control.
It probably needs work too.

Question: I’ve seen, and SEMI-understand matrixes that address 32 inputs
(4 x 8 bits) but not quite understanding how I can address the six mux chips
with 96 inputs. Or if I can even do it this way. Example from this forum: How to code for cascading multiplexers?
Is it possible with this matrix of 96 inputs, and how? Am I barking up the wrong tree?

Code so far:

    #include <Tlc5940.h> //Arduino TLC5940 Library controls the individual LEDs - "Pixels"

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

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

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

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

//  ANALOG PIN :
#define  InputFromMux A0

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

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

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

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

}

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

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

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

    delay(2);

    //edited as per @Gerben. thanks so much

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

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

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

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

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

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

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

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

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

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

      } //end For(x..) Loop

}//endMainLoop

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

Depending on the "binary" input to A/B/C (shown as S0/S1/S2 on your schematic) there is a low resistance path between one of the 8 inputs and the single output. The CD74HC4067 works in a similar way, except it switches 16 inputs.

So, if you set up the binary number 2 (010) in A/B/C then the third input is selected (number 02 because it is zero-relative).

In your schematic you have 6 x CD74HC4067 which therefore can have 16 x 6 inputs (96 inputs in total). The outputs of those 6 are fed into the 54HC4051 (2 aren't used) so therefore the 54HC4051 can select which of the 6 16-input chips it is interested in right now, by setting up a number between 0 and 5 on the 8-input multiplexer.

The four binary inputs to the 6 x CD74HC4067 are all tied together as you can see on the schematic.

Thus your method would be:

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

Those two loops will give you 96 inputs, which is what you are trying to read.

This technique takes 7 output pins to output the binary numbers (3 bits plus 4 bits). It also needs one input pin to read the result.

Judging by the schematic it uses SPI (serial data) to control the 6 x TLC5940 shift registers which lets it turn LEDs on and off with only two control pins (SCK and MOSI named SCLK and SOUT on your schematic).

The chips are daisy-chained together so all of those TLC5940s are controlled by those two pins.

This fairly minimalist design has therefore left some spare pins on the Arduino Pro.

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

I know you changed the question by the time I saw this, but the code below illustrates what I mean by the two loops:

const int MUX_CHIPS = 6;
const int LEDS_PER_CHIP = 16;
const int TOTAL_IR_INPUTS = MUX_CHIPS * LEDS_PER_CHIP;
// Master IR -mux sensor pins for Arduino Pro MINI
const byte  M_S0 = 2;
const byte  M_S1 = 4;
const byte  M_S2 = 5;
// Slave IR mux sensor pins
const byte  S_S0 = 6;
const byte  S_S1 = 7;
const byte  S_S2 = 8;
const byte  S_S3 = 12;
//  ANALOG PIN :
const byte INPUT_FROM_MUX = A0;

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

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

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

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

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

void loop() {

  unsigned long start = micros ();

  // read from IR diodes

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

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

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

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

  // display results here ...

} // of loop

The exact code above took 5148 µs (around 5 ms) to execute the loop once on my Uno. If we remove the speedup of the ADC (analogRead) it takes 13252 µs (13 ms).

To allow for your exact wiring you need to ignore the low-order bit on the master MUX because you are not using input A0_13 in which case you need to add 2 to the master value in the outer loop:

    // select appropriate slave on the master MUX
    byte master_plus_2 = master + 2;  // allow for not using input A0
    digitalWrite(M_S2, (master_plus_2 & 0b100) ? HIGH : LOW);
    digitalWrite(M_S1, (master_plus_2 & 0b010) ? HIGH : LOW);
    digitalWrite(M_S0, (master_plus_2 & 0b001) ? HIGH : LOW);


Waking an ESP8266 from Light-Sleep using a signal from MQTT? I was wondering if it would be possible to wake an ESP8266 from a request over MQTT while it is in Light-Sleep mode? I am planning to implement a smart switch that would receive messages from a Raspberry Pi to turn off and on, however, I don't want to have to manually hit a button to trigger an external reset (I've seen this done in many examples already). I also don't think it would be efficient for me to just set a timer and have the ESP wake up in intervals. For instance, if I want to have the smart switch turn on an appliance and the PI sends a request over MQTT when the ESP is sleeping... this will do me no good. Curious if anyone has run into this issue before and what recommendations you have.

I was wondering if it would be possible to wake an ESP8266 from a request over MQTT while it is in Light-Sleep mode?

No. The ESP8266 has to be awake to communicate with the MQTT server.

The best you can hope for is a periodic wakeup to connect to the server and check for any new data.  But of course that relies on the data being set to QOS 2 so it keeps trying to be delivered until the ESP8266 is awake to receive it.


How to connect NRF24 receiver and Micro SD Card Module to Arduino UNO I would like to know how to connect a NRF24 receiver and Micro SD card module to Arduino board. I have already connected the NRF24 module to the arduino board but now i can't connect the Micro SD card module since the ports like 13,12,11 are used by the NRF24 module. Is there a way to connect those two modules?. I'm trying to save the receiving data on the Micro SD card.

SPI is a multi-drop bus protocol. That means that multiple devices can share the same physical communication medium (wires).

The only thing that needs to be "unique" for a device is its chip select pin which the master device (Arduino) uses to choose which of the devices on the SPI bus it's talking to.

So you can share pins 11, 12 and 13, but choose a different chip select pin for each device.

However, SD cards are notorious for not working well with other devices (especially with some cheap breakout boards) and your mileage may vary.


I want to run jvm on arduino.What minimum configuration do I need? If Arduino IDE itself is built on Java can I run JVM on the Arduino? If yes how should I do it?

Search for "embedded java". Oracle supports it for ARM cores, which is what some of the arduino-like boards such as the Teensy 3.X have, but I doubt they have enough resources to support it.

There is haiku-vm (google it!) that's designed with AVR processors in mind, but I don't know how actively it is being worked on.

Googling "embedded java avr" yields a tremendous amount of results; did you even try that?


Serial printing from Flash Memory (F() macro, PROGMEM, sprintf_P, SPTR) I have been testing on an Arduino UNO various techniques for serial printing from Flash Memory instead of RAM. At the same time, I have been using the freeMemory() function from Adafruit.

I created a program that prints the word "test", with various methods:

Simple print:

Serial.print("test");
Serial.print(freeMemory());

This call reports free RAM = 2267

Using the F() Macro:

Serial.print(F("test"));
Serial.print(freeMemory());

This call reports free RAM = 2299

Using sprintf_P()

char buf[100];
sprintf_P(buf,PSTR("test"));
Serial.print(buf);
Serial.print(freeMemory());

This call reports free RAM = 2267

Using strcpy_P()

 char buf[100];
 strcpy_P(buf, (PGM_P)F("test"));
 Serial.print(buf);
Serial.print(freeMemory());

This call reports free RAM = 2267

Using strcpy_P and const char[] PROGMEM

char buf[100];
const char buff[] PROGMEM = "test";
strcpy_P(buf, buff);
Serial.print(buf);
Serial.print(freeMemory());

This call reports free RAM = 2267

The basic point of this question is to gather all the possible Flash memory printing techniques. Also it would be really useful if you could explain in detail what exactly does each of the keywords F(), (PGM_P)F, PSTR, const PROGMEM.

IMPORTANT EDIT1:
Depending on where and how I use the call Serial.print(freeMemory()); the results change. For example, at the last example (PROGMEM, strcpy_P) when I included another Serial.print(freeMemory()); before the call of the printing functions, then both freeMemory() calls report 2299!

Another interesting problem is that the freeMemory() reports 2299 as freeRam, while the SRAM of my arduino UNO is only 2kbytes.

EDIT2:
Following the suggestion in comments, I changed "test" to "testtesttesttesttesttesttesttesttesttesttesttesttesttesttesttest". Now all different methods report a free ram of 2299, including the simple Serial.print().

freeMemory():

#ifdef __arm__
// should use uinstd.h to define sbrk but Due causes a conflict
extern "C" char* sbrk(int incr);
#else  // __ARM__
extern char *__brkval;
#endif  // __arm__
int freeMemory() {
  char top;
#ifdef __arm__
  return &top - reinterpret_cast<char*>(sbrk(0));
#elif defined(CORE_TEENSY) || (ARDUINO > 103 && ARDUINO != 151)
  return &top - __brkval;
#else  // __arm__
  return __brkval ? &top - __brkval : &top - __malloc_heap_start;
#endif  // __arm__
}

First, the freeMemory() function that you used from Adafruit was originated from a github, I don't know about the __arm__ implementation, but for the avr, it is incomplete for handling the corner case when the program does not use the malloc() function, if your program never use malloc(), the formula used in freeMemory() will produce the wrong result. A simple corrected version for AVR that I used is here:

extern unsigned int __heap_start;
extern char *__brkval;

int freeMemory() {
  char top_of_stack;

  if (__brkval == 0) {
    Serial.println(((int)&top_of_stack - (int)&__heap_start));
  } else {
    Serial.println((int)&top_of_stack - (int)__brkval);
  }
}

  explain in detail what exactly does each of the keywords F(), (PGM_P)F, PSTR, const PROGMEM.

PSTR("string literal")

PSTR came into Arduino from part of avr-libs(a C library) defined in avr/pgmspace.h, it is actually a macro, not a function as many think it was, and is defined as:

#define     PSTR(s)   ((const PROGMEM char *)(s))

It looks a little bit intimidated but it actually quite simple, it not only tell the avr-gcc that the string literal s should be kept in program memory (i.e. Flash memory in the case of Arduino), but allows the program to convert it into a const char *s PROGMEM variable so that it can be pass around into some PROGMEM-aware functions as a parameter.

 //this is a PROGMEM-aware function in c
 printMsg_P(const char* str) {
     char buf[strlen_P(str)+1];
     strcpy_P(buf, str);
     puts(buf);
 }

 // this handle the normal string array function
 printMsg(const char* str) {
     puts(str);
 }

F("string literal")

F() is also a macro but it is not part of the avr/progmem.h, it is actually part of the String class defined in WString.h together with a definition of a class called __FlashStringHelper:

class __FlashStringHelper;
#define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal)))

To understand the F() macro and the difference between F() and PSTR() take a little bit explanation.

As you can see from the definition of F(), it casts a string literal into a const char* variable using PSTR(), and then re-cast it into a class __FlashStrngHelper. If you further looks at the __FlashStringHelper, it is actually an empty class without any construct or method, it is literally empty, so why is this useful? and why can't just pass the string literal around by just using PSTR().

This has to do with C++'s function overload. Function overload is a feature of C++ where multiple methods could have the same function name but each with different parameters. Within all the Serial.print() methods, there is a method Serial.print(const char* str) that will take in a string literal and print it to serial monitor, but it is not PROGMEM-aware, if you pass in a PROGMEM string literal Serial.print(PSTR("string literal"));, the same method will accept what you pass in because it meet the type checking (remember PSTR is actually const char*), but it will not print out the correct string for PSTR("string literal") because it simply expecting a normal string.

In c, as we see before, we solves the problem by using two functions with different names for handling normal string and PROGMEM string, but Serial is a C++ class, it needs another function overloaded method to be PROGMEM-aware, and PSTR() is clearly not the solution as we just mentioned.

What WSting.h and Print.cpp did is to create an overload method that is PROGMEM-aware by accepting a class as parameter, so that you can pass a F() wrapped string literal which has a data type of class __FlashStringHelper into the Serial.print() and get the print out correctly from program memory. See the source code yourself.

Serial.print(const __FlashStringHelper *ifsh)

So in summary, the F() and PSTR() are alike, both telling the compiler to keep the string literal in the program memory, and allow the string literal to be pass around into some function as parameter. But it was designed for different purpose from different programming paradigm (C versus C++). F() is Serail.print()-friendly, while PSTR() is not. If you are getting PST() in a function and yet you want to send it to Serial.print(), you will have to explicitly cast it into __FlashStringHelper like this:

Serial.print((__FlashStringHelper*)PSTR("test"));

PGM_P

PGM_P is a macro defined as:

#define     PGM_P   const char *

Whether you want to use PGM_P or const char * is a personal preference, for example, this is copy from https://www.arduino.cc/reference/en/language/variables/utilities/progmem/:

const char *const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5};

can be written as:

PGM_P const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5};

This is a lengthy explanation, but I hope this will help on better understand the subject and therefore be able to use the PROGMEM and all the associated macros effectively.


Simulation of IoT based systems in Software Thank you for reading this.

Generally there are libraries for GSM and Ultrasound sensors for the software called Proteus and you can simulate them along with you MCU and the interfacing peripherals and simulate .

I have big problem at my hand , I want to simulate ESP8266 or any other relevant wifi module with my Arduino (Simulation Libraries for Arduino are available ) and get the data from sensor , all in software . Then , I want the wifi device (in software ) to show an ip address , so that I can log the data to an online cloud .

The software and module does not have to be specific , I want to know , If there are any professional software that let you simulate IoT based systems.

I'am new to IoT designing and I'am always comfortable with simulating everything.

If you have any other similar guide on how to design and simulate IoT systems , Let me know .

Have a great day

There are tools to simulate Arduino, but it's not meant for anything beyond basic (i.e. simple circuit). Support is limited, you can't just simulate any and every sensor and shields (e.g. LAN, Wireless). Furthermore, ESP8266 is so cheap that hardly anybody has actual use-case to simulate them. I suggest you work on a real device =)

If you need to simulate data stream into your cloud or IoT platform, I suggest you just spin up a machine and run some code to generate data.


Code for a rolling average Below is some code I wrote to find the rolling average of a temp sensor hooked up to an arduino and display it to an lcd display. My issue is that for the first minute it is running, the average is not correct. It starts at 0 and then progresses up to where it should be (~85F) in increments of approximately 3. After the first minute it is fine and works as it should.

What I want the code to do is to simply take the average of the sum of the values that have been recorded in the first minute.

My knowledge of C is fairly limited(I only had a semester long class on it) so that is why it is simple. I am a mechanical engineering student and this code is for project at my internship.

#include <Adafruit_MLX90614.h>
Adafruit_MLX90614 tempSensor;

#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

Adafruit_MLX90614 mlx = Adafruit_MLX90614();

double array[30];
double rollingaverage=0;
int i=0, j=0;
double sum=0;
double newreading;
void setup() {

  Serial.begin(9600);
  lcd.begin(20,4);
  mlx.begin();
  Wire.begin();

}

void loop() {
  if(j=0){
      newreading = mlx.readObjectTempF();
      array[i] = newreading;
      sum += array[i];
      if(i>0){
          rollingaverage = sum/(i+1);
      }
      j=1;
  }
  else{
      newreading = mlx.readObjectTempF();
      array[i] = newreading;
      if(i < 29){ //wraps i back around to 0 if it is at 29 to subtract the oldest value
          sum = sum + array[i] - array[i+1];
          rollingaverage = sum/30;
      }
      else{
          sum = sum + array[i] - array[0];
          rollingaverage = sum/30;
          i=0; //reset index to 0
      }
  }
  i++;

  lcd.clear();
  lcd.print("Belt: "); lcd.print(rollingaverage);
  lcd.setCursor(1,2);
  lcd.print("Air: "); lcd.print(mlx.readAmbientTempF());

delay(2000);
}

Its not a huge deal because it works fine after the first minute, it is just annoying that I can't figure out why it doesn't work as intended in the first minute. Thanks

Your problem stems from you starting out with 30 values of 0 which you include in your average.  You have to take that into account and ignore those values, dividing your total by only the number of actual values you have.

I have a library that does it all for you that would make things easier for you:

https://github.com/MajenkoLibraries/Average


Strange behavior from uint32_t, acting like signed int (Nano clone) I'm having trouble with these variables. As you can see they're uint32_t type, so they should have a maximum value of 4 million or so, but they're rolling over and going negative at 32,767 like a signed int. Here's the relevant code:
byte lPin = 7;
char buff[100];
uint32_t loAvg = 0;
uint32_t hiAvg = 0;

void setup() {
  pinMode(lPin, OUTPUT);
  digitalWrite(lPin, HIGH); // Active LOW, so this is off

  Serial.begin(9600);
  // Generate high/low averages
  for(int i = 0; i < 100; i++) {
    loAvg += analogRead(A0);
  }
  loAvg /= 100;

  digitalWrite(lPin, LOW);
  delay(500);

  for(int i = 0; i < 100; i++) {
    hiAvg += analogRead(A0);
  }
  hiAvg /= 100;

  digitalWrite(lPin, HIGH);
  delay(500);

  sprintf(buff, "loAvg=%d, hiAvg=%d", loAvg, hiAvg);
  Serial.println(buff);

  Serial.println(hiAvg);
  digitalWrite(lPin, LOW);
  hiAvg = 0;
}

void loop() {
  sprintf(buff, "test=%d", hiAvg);
  Serial.println(buff);
  hiAvg+=100;
}

I removed a bunch of stuff from the code to save posting the whole (much longer) thing. If it ends up being relevant I can though, I just think I narrowed the problem down to this. Observing the serial monitor I get this on startup:
loAvg=287, hiAvg=0
933
test=0
test=100
test=200
...

The test=# repeats until 32700, then continues at -32736. I'm confused by the hiAvg=0 followed by the 933, showing that it totally is getting a high average, because that's around what it should be. Even if it's the sprintf() messing with it, in the setup function the value should only be around the 900 range so it wouldn't overflow there. Any ideas anyone?

%d expects a signed int. %u expects an unsigned int. Insert the l modifier to expect a long in each of those cases. So you need a format code of %lu to print a uint32_t.
The following code:
#include <Arduino.h>

void setup()
{
    uint32_t x=110000;
    char buf[50];

   // Open console
   Serial.begin(115200);

    sprintf(buf, "%%d: %d\n", x);       Serial.print(buf);
    sprintf(buf, "%%u: %u\n", x);       Serial.print(buf);
    sprintf(buf, "%%ld: %ld\n", x); Serial.print(buf);
    sprintf(buf, "%%lu: %lu\n", x); Serial.print(buf);
}

void loop() {
   ;
}

prints this:
%d: -21072
%u: 44464
%ld: 110000
%lu: 110000


How to concatenate a part of a string and convert then to a int? Lets say I have

String myString="AR0236";

I wish to extract the number 236 and assign it to an int. How can this be done?

P.S: I'me new to programming and I tried searching the forums for similar problems but surprising none of them worked for me!

There's multiple ways.

The String class (which TBH you should avoid) has some useful methods:

substring - extract part of a string as a new string
toInt - convert a string to an integer

So you can join them together:

int val = myString.substring(3).toInt();

That's the easy way.  Grab the string content from the 4th character (it's zero-based, so 3 is the 4th character) onwards, and convert it to an integer.

If you are avoiding String, as you should, then you are working with pointers.  For instance:

char myString[10]; // This is where your data gets stored
strcpy(myString, "AR0236"); // Let's put in some dummy data

int val = atoi(myString + 3);

myString + 3 gives you a new string pointer to a location that is 3 bytes further up in memory from myString - which equates to where the start of your number is.  Then convert that portion of the string to an integer.

The "easy" way consumes and makes a mess of your heap, since it's having to make a new String object and copy data into it. The "better" (second) way uses no more memory. It just converts a subset of the existing string directly.


SIM800L GSM module is not working I'm testing SIM800L GSM module with Arduino UNO and module is blinking 3 times every 15 seconds or sometime every 45 seconds. Why this is happening?
In serial monitor it shows Message Sent Successfully! but I'm not getting any message.I tried with multiple numbers. Still not getting any message.

I have tested several codes which shows outputs of AT commands. Nothing was working. Power supply is 5V 5A.

/*
 *   Author@ExploreEmbedded
 *   Example to Send messages Interactively using GSM Sim800L
 *
 *   LIBRARY CREDITS:
 *   Thanks to Cristian Steib(steibkhriz@gmail.com) for the library.
 *
 *
 *
 *      PINOUT:
 *        _____________________________
 *       |  ARDUINO UNO >>>   Sim800L  |
 *        -----------------------------
 *            GND      >>>   GND
 *        RX  10       >>>   TX
 *        TX  11       >>>   RX
 *       RESET 2       >>>   RST
 *
 *
*/

#include <Sim800L.h>
#include <SoftwareSerial.h> //is necesary for the library!!
Sim800L Sim800L;  //to declare the library
char text[161]=""; //buffer to store message
char number[11]=""; //phone number to send message
int cnt;
bool error; //to catch the response of sendSms

void setup(){
    Sim800L.begin(); // initializate the library.
    Serial.begin(9600);
}

void loop(){

      //Read the Number
      Serial.print("\nEnter 10 digit Phone Number:");
      while(Serial.available()<=0);
      cnt = Serial.readBytesUntil('\n',number, 11);
      number[cnt] = '\0';
      Serial.println(number);

      //clear the serial input buffer so that no typed characters are pending

      delay(1000); //delay required before clearing the input buffer
      while(Serial.available()>0) //clear buffer
      {
        Serial.read();
      }

      //Read the Message to be sent
      Serial.print("Enter Message:");
      while(Serial.available()<=0);
      cnt = Serial.readBytesUntil('\n',text, 160);
      text[cnt] = '\0';
      Serial.println(text);
      delay(1000);

      while(Serial.available()>0) //clear buffer
      {
        Serial.read();
      }

      //Send the message and display the status
      error = Sim800L.sendSms(number,text);
      if(error)
      Serial.println("Error Sending Message");
      Serial.println("Message Sent Successfully!");

}

I found what's happening. Module was shutdown due to over voltage.


Can't upload to my Nano after updating to Arduino AVR Boards 1.6.21 I recently had the Arduino IDE notify me of available boards updates, so I updated. Since then when I try to upload to my Nanos it fails:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x01

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I installed Arduino IDE 1.0.6 and found that I can upload to all my Nanos with that IDE version.

How can I upload to my Nanos using Arduino AVR Boards 1.6.21?

Arduino recently changed the bootloader they ship on their official Nano boards. This required a change in the hardware definition for the Nano, which was the sole reason for the Arduino AVR Boards 1.6.21 release.

The new Nano hardware definition is not backwards compatible with Nanos that use the previous ATmegaBOOT bootloader. For this reason a new menu option was added: Tools > Processor > ATmega328P (Old Bootloader). If you select that option the uploads to your Nanos will work again.


I keep getting this error exit status 1 expected ';' before 'DigiKeyboard' \ here is my code
include "DigiKeyboard.h"
void setup() {
DigiKeyboard.sendKeyStroke(0);
DigiKeyboard.delay(100);
DigiKeyboard.sendKeyStroke(MOD_GUI_LEFT);
DigiKeyboard.delay(100);
DigiKeyboard.print("Camera")
DigiKeyboard.delay(100);
DigiKeyboard.sendKeyStroke(KEY_ENTER);
DigiKeyboard.delay(100);
DigiKeyboard.sendKeyStroke(KEY_ENTER);
DigiKeyboard.delay(100);
DigiKeyboard.sendKeyStroke(KEY_ENTER);
DigiKeyboard.delay(100);
DigiKeyboard.sendKeyStroke(KEY_R, MOD_GUI_LEFT);
DigiKeyboard.delay(100);
DigiKeyboard.print("cmd")
DigiKeyboard.delay(100);
DigiKeyboard.sendKeyStroke(KEY_ENTER);
DigiKeyboard.delay(100);
DigiKeyboard.print("REDACTED")
for(;;){ /empty/ }
}

You forgot the semi colon after

DigiKeyboard.print("Camera")

It should be:

DigiKeyboard.print("Camera");


Arduino Uno won't upload code and overheats We are using an Arduino Uno R3 connected via USB to a computer. The main problem is that we can't upload any code to the board. We get this error in the Arduino IDE console:

  avrdude: ser_open(): can't open device ".\COM1": The system cannot find the file specified
  Problem uploading to board. Visit http://www.arduino.cc/en/Guide/Troubleshooting#upload

My computer may not recognize the board, the IDE won't find any port (COM) and on the board I got the three LEDs turned on, they don't even blink, they stay turned on as long as I have connected the Arduino to the computer. Apart from that, the Arduino heats too much and too fast. I don't have anything connected to it yet. I've tried resetting the board with its built-in button, I've also tried changing the USB cable, even the computer, different system architecture and OS. I don't to want to mess up the board even more, so I don't know what to do. Could you point out what's the problem with my board?

If you need more information, I will try to post as much as you need to help me out.

The fact that it doesn't blink the LED when plugged in or reset indicates that the bootloader of the main microcontroller no longer works.
The fact that the computer no longer recognizes the board as a serial port means that the USB-to-Serial interface doesn't work.
The fact that it heats up tells you that at least one of the chips on the board is dead.

I'm afraid that you'll have to get yourself a new Arduino.


Arduino Uno and Raspberry Pi USB Serial Communication I am trying to get Arduino Uno with Raspberry Pi to communicate with each other. I want the python script to write a message and for my Arduino to read it. This was working before, but I came back a week later and it stopped. Essentially, I want the Raspberry Pi to write '3' and for my Arduino to recognize this 3 and light up some LEDs. Where do you think I am going wrong? The Arduino works when testing it through the IDE and Serial Monitor. There are no errors when running the python script, the LEDS just don't light up, so I assume there is some miscommunication.

Python Code

import serial
ser = serial.Serial('/dev/ttyACM0', 9600)
ser.write('3')

Arduino Code

String serialRead;
int val;
void setup() {
  Serial.begin(9600);
  strip.begin();
  strip.setBrightness(25);
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  serialRead = Serial.read();
  if (Serial.available() > 0) {
    val = Serial.read();

    if (val > '0' && val <= '9') {
      Serial.println(val);
      val = val - '0';
      Serial.println(val);

      if (val == 3)
      {
        //strip.setBrightness(100);
        colorWipe(strip.Color(127, 127, 127), 50);
        colorWipe(strip.Color(0, 0, 0), 50);
      }
    }
  }
}

Just at a glance:

Your loop consumes the byte and stores it in serialRead, so there is probably no available data at the outer if, so it is never entered.

Try deleting this line:

serialRead = Serial.read();


How to control a Nema 17 stepper motor with an arduino? (too much current / heat) I am trying to control a Nema 17 motor with a L298n dual bridge and an Arduino Mega.

My wiring is from this Instructable:

http://www.instructables.com/id/Control-DC-and-stepper-motors-with-L298N-Dual-Moto/?ALLSTEPS

When I connect it to my laboratory power supply the current limitation blinks. Normally when there is too much current needed the LED is all the time on and not blinking.

So I increase the current limit and the motor just starts moving on 3.1A @ 12V (doesn't move if less current) and in the description of the motor on amazon
they say "Rated Current/Phase:1.2A" so I am wondering what did I do wrong here?

From my understanding "Rated Current/Phase:1.2A" means that I should run this motor (it's a bipolar stepper motor with 2 phases) not higher than 2.4A?

These are the informations from amazon about this motor:

Specifications:

Led screw diameter: 8mm
Lead screw length: 300mm
Step angle :1.8 degree
Nut material: Brass
Holding Torque: 400mN*m
Thrust(full step): 12.5kg
Rated Current/Phase:1.2A
Rate Voltage: 3.3v
Rated Resistance/Phase:2.2±10%ohm

What would be a good voltage to run this motor? I thought 12V is a good idea with.

The motor L298n gets really hot when I run it at 3.2A or more so I think my setup will destroy the dual bridge and / or the motor.

I really appreciate help on this! :-)

The stepper motor does not directly control or limit its own current.  When using the L298n for stepper control, the motor current control is performed by a PWM signal to the L298n ENABLE pin.  If you have ENABLE high (100% duty), current will be a factor of only the DC resistance of the stepper winding and the power supply voltage.  Here you are trying to drive a 1.2A@3.3V-rated stepper from 12V, so naturally the current will be ~3 times greater.

To adjust the motor current to a safe range for the driver, use analogWrite() from a PWM-capable pin on the Arduino connected to the ENABLE pin on the L298n, and set it to something less than 255 (50% is usually a good starting point).  Even then, the instantaneous current draw on the L298n will likely be stressing it outside of its operating envelope.

EDIT: I reviewed the info at the link, and this is the relevant area of the code:

// set speed to 200 out of possible range 0~255
analogWrite(enA, 200);
// set speed to 200 out of possible range 0~255
analogWrite(enB, 200);

Here is where the code is setting PWM of the two ENABLE pins to 200 (~80% duty cycle).  Drop this to 50 (~20% duty cycle) and you would likely resolve your overcurrent issue.  Reading further still, even the author gives you your first hint at what is happening:

  This is not a speed value, instead power is applied for 200/255 of an
  amount of time at once.


How can a function/method determine if a const array passed in is PROGMEM (flash) or not (RAM)? Is it possible for a function/method to know if a constant array that has been passed in is in flash or RAM?

If I have a method or function that receives a constant array that is in RAM, the array is declared like this:  const uint8_t MY_ARRAY[] = { 1, 2, 3, 4 };

gets passed into a method or function like this:  MyFunction(MY_ARRAY);

and the method or function can handle it like this:

void MyFunction(const uint8_t *MY_ARRAY) {
     uint8_t secondElement = MY_ARRAY[1];
     ...

However, if the array is in Flash (because it's a constant array, so that's where it should go), then the declaration adds PROGMEM:   const uint8_t PROGMEM MY_ARRAY[] = { 1, 2, 3, 4 };

The pass looks the same:  MyFunction(MY_ARRAY);

And the function declaration looks the same but it needs to use pgm_read_byte_near to get the correct values back:

void MyFunction(const uint8_t *MY_ARRAY) {
     uint8_t secondElement = pgm_read_byte_near(MY_ARRAY+1);
     ...

How can the receiving method know if the array is in flash (PROGMEM) or RAM (no PROGMEM) so it knows to use pgm_read_byte_near or not?  Ideally I'd like a compiler error, but the type is the same (both are const arrays of uint8_t).

If pgm_read_byte_near is used when it shouldn't be, or it's not used when it should be, the results are garbage.

Some relevant questions:
How to pass a static const (progmem) array to a function

RAM usage question: PROGMEM vs const vs #define

Storing array in PROGMEM

PROGMEM: do I have to copy data from flash to RAM for reading?

UPDATE:
It looks like what I want to do is not possible.  The responses below are very interesting options though:  using __flash in plain C, using OOP to make PROGMEM and non-PROGMEM data holders or trying to (somehow?) use non-deprecated progmem specific data types from avr/gpmspace.h.

The best answer to my original question is that the method can not make this determination.  The best solution, from a comment by Delta_G, is to create regular (ram) and "_P" (flash/ progmem) versions of the functions and to be as obvious as possible in the naming of those functions.

I am afraid there is no good solution to this problem. One option I do
like is to use the __flash qualifier instead of PROGMEM:

const uint8_t ram_array[] = { 1, 2, 3, 4 };
__flash const uint8_t flash_array[] = { 5, 6, 7, 8 };

void function_reading_ram(const uint8_t *array)
{
    uint8_t secondElement = array[1];
    // ...
}

void function_reading_flash(__flash const uint8_t *array)
{
    uint8_t secondElement = array[1];
    // ...
}

int main(void)
{
    function_reading_ram(ram_array);      // OK
    function_reading_flash(flash_array);  // OK
    function_reading_ram(flash_array);    // Warning
    function_reading_flash(ram_array);    // Warning
}

Note that, with __flash, you don't need pgm_read_byte_near() or
anything similar. You just use the array like you would use any regular
array, and the compiler is smart enough to generate the code required to
access the Flash memory.

The warnings generated by gcc are:

warning: conversion from address space ‘__flash’ to address space ‘generic’ [-Waddr-space-convert]
     function_reading_ram(flash_array);
     ^
warning: conversion from address space ‘generic’ to address space ‘__flash’ [-Waddr-space-convert]
     function_reading_flash(ram_array);
     ^

Given how nice this solution is, you may wonder why I wrote “there is no
good solution”. Well, this comes with two caveats, one small and one
huge. The small caveat is that you need to explicitly pass the option
-Waddr-space-convert to the compiler if you want it to generate the warnings.
It is not implied even with
-Wall -Wextra. The huge caveat is that this only works in plain C.
If you try to use this trick in C++ you get:

error: ‘__flash’ does not name a type

This is an implementation of the “named address spaces” extension to the
standard C. Since nothing like this is standardized in C++, the authors
of gcc assumed it would not be useful to users of C++. :-( You can mix C
and C++ sources in Arduino, but you can't call class methods from C.


Controlling image display on LED matrix by buttons Building a 9x9 LED matrix and facing following 2 problems in Arduino code,

The current code displays 2 images (using byte arrays and then using bitRead) one by one, each for a certain duration of seconds. Persistence of vision is obtained by a delay of 300ms. There is a subroutine called upon in the main loop function with arguments of desired byte array and duration. I want to control the images by using 2 push buttons (push button1 and it displays 1st image until button2 is pressed, push button2 and second image is displayed until button1 is pressed). But the scanning algorithm exits the scan routine upon completion of the given input duration and restarts the routine with new argument (byte array of image2). I WANT THE IMAGE TO BE RETAINED ON THE MATRIX UNTIL BUTTON IS PRESSED. Can't figure out how to accomplish this.

If i nest the routine in a DO WHILE loop, then my problem is that how will the buttons be read from the main loop? Because I believe as long as the subroutine is being executed, main loop will be halted. (or I am totally wrong in this assumption?)

Reference code which I intend to manipulate. (Here its for an 8x8 Matrix. Thats not an issue)

byte bigHeart[] = {
    B01100110,
    B11111111,
    B11111111,
    B11111111,
    B01111110,
    B00111100,
    B00011000,
    B00000000};

byte smallHeart[] = {
    B00000000,
    B00000000,
    B00010100,
    B00111110,
    B00111110,
    B00011100,
    B00001000,
    B00000000};

const int columnPins[] = { 2, 3, 4, 5, 6, 7, 8, 9};
const int rowPins[] = { 10,11,12,15,16,17,18,19};

void setup() {
    for (int i = 0; i < 8; i++)
    {
        pinMode(rowPins[i], OUTPUT); // make all the LED pins outputs
        pinMode(columnPins[i], OUTPUT);
        digitalWrite(columnPins[i], HIGH); // disconnect column pins from Ground
    }
}

void loop() {
    int pulseDelay = 800 ; // milliseconds to wait between beats
    show(smallHeart, 80); // show the small heart image for 100 ms
    show(bigHeart, 160); // followed by the big heart for 200ms
    delay(pulseDelay); // show nothing between beats
}

// routine to show a frame of an image stored in the array pointed to by the
// image parameter.
// the frame is repeated for the given duration in milliseconds
void show( byte * image, unsigned long duration)
{
    unsigned long start = millis(); // begin timing the animation
    while (start + duration > millis()) // loop until the duration period has passed
    {
        for(int row = 0; row < 8; row++)
        {
            digitalWrite(rowPins[row], HIGH); // connect row to +5 volts
            for(int column = 0; column < 8; column++)
            {
                boolean pixel = bitRead(image[row],column);
                if(pixel == 1)
                {
                    digitalWrite(columnPins[column], LOW); // connect column to Gnd
                }
                delayMicroseconds(300); // a small delay for each LED
                digitalWrite(columnPins[column], HIGH); // disconnect column from Gnd
            }

            digitalWrite(rowPins[row], LOW); // disconnect LEDs
        }
    }
}

OK. Figured out a solution which is working for me. Upon reading a forum on Arduino.cc. That stated a nice analogy to handle this issue.

You have something to heat up on stove while also waiting for an important email which you have to respond to immediately. (You only have a PC in the farthest corner of house at which you have to monitor your outlook :D) How will you do both tasks simultaneously? Run the stove for 10seconds, go to PC to check email, return to stove, run it again for 10 seconds, then again go to PC to check email. Do this until you get the email or your food gets hot enough.

To implement this in our program. I read the states of 2 buttons at start of the main loop. Store their values in 2 variables. Then check the values to check if some button is pressed. if value A is 1 and B is 0, call function A, if A is 0 and B is 1 call function B. The called function comprises of the scan routine. So when called, it performs 1 scan and comes back to the main loop. If no button was pressed meanwhile, the variables have same values, so the same function is called again and it performs the 2nd scan. if a button was pressed meanwhile, then 2nd function is called instead of the 1st one. The speed of all this is enough so that the user does not experience any delays, neither Arduino misses a button pressed while executing the scan.

The LEDs started to flicker when I implemented this code. So I further reduced the delay in the scan routine (time for which each LED is lit before turning it off and lighting the next one) from 300 microsecond to 100 and all went fine. My matrix of 64 LEDs is working fine however I assume that if matrix goes beyond some 100 LEDs then problems like delay or flickering or reduced brightness may arise.

Here is the complete code

byte img1[] = {
    B01100110,
    B11111111,
    B11111111,
    B11111111,
    B01111110,
    B00111100,
    B00011000,
    B00000000
};

byte img2[] = {
    B00000000,
    B01100110,
    B01100110,
    B00000000,
    B00011000,
    B10000001,
    B01000010,
    B00111100
};

const int rowPins[] = {13,12,11,10,9,8,7,6};
const int columnPins[] = {5,4,3,2,14,15,16,17};

const int but1 = 18;
const int but2 = 19;

int but1State = 0;
int but2State = 0;
int but1Now;
int but2Now;

int value1;
int value2;

void setup() {

    for (int i = 0; i<8; i++){
        pinMode(rowPins[i], OUTPUT);
        pinMode(columnPins[i], OUTPUT);
        digitalWrite(columnPins[i], HIGH);
    }

    pinMode(but1, INPUT);
    pinMode(but2, INPUT);

    but1State = digitalRead(but1);
    but2State = digitalRead(but2);
}

void loop() {

    but1Now = digitalRead(but1);
    delay(5);
    int but1Now1 = digitalRead(but1);

    if(but1Now == but1Now1)
    {
        if(but1Now != but1State)
        {
            value1 = 1;
            value2 = 0;
            //show(img2);
        }

        but1State = but1Now;
    }

    but2Now = digitalRead(but2);
    delay(5);
    int but2Now1 = digitalRead(but2);

    if(but2Now == but2Now1)
    {
        if(but2Now != but2State)
        {
            value1 = 0;
            value2 = 1;
            //show(img2);
        }

        but2State = but2Now;
    }

    if(value1 == 1)
    {
        show(img1);
    }

    if(value2 == 1)
    {
        show(img2);
    }
}

void show(byte*image) {

    for(int row = 0; row<8; row++)
    {
        digitalWrite(rowPins[row], HIGH);

        for(int col=0; col<8; col++)
        {
            boolean pixel = bitRead(image[row],col);

            if(pixel == 1)
            {
                digitalWrite(columnPins[col], LOW);
            }

            delayMicroseconds(150);
            digitalWrite(columnPins[col], HIGH);
        }

        digitalWrite(rowPins[row], LOW);
    }
}


Arduino app hangs on upload for all boards I'm at a loss. I have many boards and have not had much trouble in the past uploading to feather, uno, light blue bean and others. I have a lot of boards loaded in the board manager and I'd rather not delete everything just yet.

But, after taking a month off of arduino programming I've come back to the app to discover that I can't upload anything to any board. I've tried a brand new uno, an adafruit feather and the light blue bean. In each case I can see the port, but the upload just hangs like this:

On the board the light that normally blinks during upload never blinks. It's like the upload just isn't happening. But there is no error in the app.

I tried reinstalling the app, but that didn't help. My next thought is to delete everything, and do a fresh install. Which will be annoying. Is that my only hope?

UPDATE:

Here are the settings from the tools menu as requested:

I tried that once. A very common reason for this problem is a different cable. Some USB cables are not suited for uploading the data to the Uno board.

Have you brought a new cable? If so, switch back to the old one. It may not look like it makes a difference, but it requires attention.


How to map sensor analog output voltage My sensor output voltage values ranges from 0.6 V - 3 V. How can I convert this voltage values to ppm in the range 0-1000? Upon exposure to CO gas: 0 ppm = 0.6 V , 500 ppm = 1.52 V and 1000 ppm = 3.01 V. Which means that the sensor cannot detect under 214 ppm (approx). Can you please help with mapping the sensor output values as ppm in the serial monitor? thnk u

// the setup routine runs once when you press reset:
    void setup() {
      // initialize serial communication at 9600 bits per second:
      Serial.begin(9600);
    }

    // the loop routine runs over and over again forever:
    void loop() {
      // read the input on analog pin 0:
      int sensorValue = analogRead(A0);
      // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
      float voltage = sensorValue * (5.0 / 1023.0);

      // print out the value you read:
      Serial.println(voltage);

    }

On page 4 of the datasheet,

  Left side value of detection range (zero point) is corresponding to left side value of voltage output range,but right side value of detection(max detection value) is not corresponding to the right side value of voltage output range.

Thus, 0ppm would correspond to 0.6V, for CO. And 1000ppm does not necessarily correspond to 3V.

Assuming that 500ppm = 1.52V was obtained from the "inspection report", you now have two reference points, (0, 0.6) and (500, 1.52).

Further below on the same page, a formula for N is given, which, points towards a linear response of Vo with respect to ppm. Thus, you can use the map() function to do the linear mapping from voltage to ppm.

Note that map() only works with integers, so instead of mapping voltage (0.6 - 1.52) to ppm, you should directly map the analogRead value (123 - 311) to ppm to get better accuracy. Other wise, implement your own mapping using floats.


ATtiny serial.print() crash with INTs I'm trying to print some data to and from an ATtiny85 via serial, using the SoftwareSerial library.  So far I've tried these setups with no results:

1/8MHz clock
baud rates from 9600 to 57600 (library doesn't seem to support higher rates)
printing to a newline or a single one
packing up a char array just as much as a String and then printing it
Txing/Rxing through an Arduino Nano/Uno/Mega or a cheap USB-Serial port

Reading up on the subject seemed to suggest that some values I was passing (such as '1000') might have been erroneously interpreted as EOL characters breaking the code, but attempts with different values (i.e. 845) returned the same failures.

As you might have guessed I'm writing code with the ArduinoIDE, and no errors are returned when compiling and uploading. Many other parts of the project involving serial work just fine, and I can communicate with the ATtiny on pretty much any of the above setups (actually packing up the String or char[] crash the whole thing).
The 'Ready' at the end of the setup is also printed fine, and the loop runs as long as it won't encounter any of the above issues.

Here's the code:

int VALUE = 1000;
int ANOTHER = 12;

#include <SoftwareSerial.h>
SoftwareSerial tSerial(3,4);

void _serialEvent() {
  if (tSerial.available()) {
    char mode = tSerial.read();
    if (mode == '?') {
      tSerial.println("someTextHere 1.23moreText");
      tSerial.print("value:");
      tSerial.print(VALUE);
      tSerial.print(";another:");
      tSerial.println(ANOTHER);
    }
    else if ...
  }
}

void setup() {
  tSerial.begin(57600);
  ...
  tSerial.println("Ready");
}

void loop() {
  ...
  _serialEvent();
}

It is much better to store string literals in the FLASH only. In Arduino there is __FlashStringHelper class and F() macro ensures that correct version of print method is used and that the string literal is not copied into the ram before it's printed.

Basically if you don't have enough memory, using lots of string literals results in stack overflows, coruption and/or returning to random adresses and it looks like crashes/resets.


Project structure to build for PC and Arduino Recently I have started developing for Arduino Uno. I have 10 years experience in software development (C#, Delphi), but not much with C/C++.
Compiling the Arduino sketches seems a little slow, and debugging isn't as convenient as it could be on a PC (compile, upload, watch the serial monitor, modify code, start over.... way too slow with lots of unnecessary steps)
So what I would like to achieve is to organize my code in a way to be able to compile my code either to Arduino, or to PC for debugging purposes (to a small console app). I know that there are libraries that cannot be used on a PC, but those can be abstracted away (hidden behind a facade or something like that). Unfortunately I could not find any tutorials, or articles how to do this. So I hope you can help me out.

BTW I'm using Visual Studio (with Visual Micro) on a Windows 10 computer.

I haven't done it yet, but you could do the following things to get a somewhat close approximation:

Make three different projects, one for the PC (only), e.g. Visual Studio, and one for Arduino (with the default Arduino IDE or e.g. Visual Micro). The last will be a generic library to be used for both the PC and Arduino.
Use the Arduino specific libraries only for the Arduino project.
Create facade/wrapper classes for each Arduino library.
Use a mock/stub for the Arduino libraries in the PC only project.
Put all non-hardware related code in separate classes, to be used by both projects.
Write unit tests for the PC only project.
The PC project will be tested by unit tests, and can be debugged on a PC
Only the specific Arduino libraries/interfaces have to be tested using the 'hard way', e.g. with Serial.

So the projects (including testing) will look like:

PC Project

References common code
Stubs for Arduino libraries, stubs can possibly be reused by PC Unit tests

PC Unit Tests

Unit tests
References common code

Arduino Project

Containing Arduino libraries
References common code

Common Code

All domain specific classes


Starting With An Arduino Uno Alright, so I just recently got an Arduino Uno and I'm really not sure what to do/where to start with it. So far I've only made a light blink on it, but I was wondering if it is possible to have it do more complicated things like run programs or, say, a keylogger. How would I be able to do this and is this even possible on an Uno?

If you need inspiration what to do with the Arduino, google Simple Arduino projects and search a bit. You will find a lot of interesting things.

If you want to build a keylogger for a normal computer keyboard, then you can start with an old PS2 keyboard and this library: PS2Keyboard Library

From a quick glance on the PS2 protocol, it seem to have the same electrical functionality as the I2C protocol (both lines have a pullup resistor to 5V and the connected controllers are open collector, so that an inactive device doesn't disturb communication on the bus). With this I would say, you have to tap the Data and Clock lines with the library. Maybe you can also power the arduino directly over the bus power lines.

Maybe this video is also interesting in this context: Hardware Keylogger with Arduino UNO

As the USB protocol is far more complex than PS2, I wouldn't recommend a USB keylogger as a starter project. (Though it seems possible when using the right shield for the UNO). You can also use an USB to PS2 Adapter for your USB keyboard to get it working without buying a new keyboard. If you still want to make a USB keylogger, I think other Arduino variants can also work as USB hosts, which would make things easier.


Classes and objects: how many and which file types do I actually need to use them? I have no previous experience with C++ or C, but know how to program C# and am learning Arduino. I just want to organize my sketches and am quite comfortable with the Arduino language even with its limitations, but I really would like to have an object-oriented approach to my Arduino programming.

So I have seen that you can have the following ways (not exhaustive list) to organize code:

A single .ino file;
Multiple .ino files in the same folder (what the IDE calls and displays like "tabs");
An .ino file with an included .h and .cpp file in the same folder;
Same as above, but the files are an installed library inside Arduino program folder.

I have also heard of the following ways, but have not got them working yet:

Declaring a C++-style class in the same, single .ino file (have heard of, but never seen working - is that even possible?);
[preferred approach] Including a .cpp file where a class is declared, but without using a .h file (would like this approach, should that work?);

Note that I only want to use classes so that code is more partitioned, my applications should be very simple, only involving buttons, leds and buzzers mostly.

How the IDE organizes things

First thing, this is how the IDE organizes your "sketch":

The main .ino file is the one of the same name as the folder it is in. So, for foobar.ino in foobar folder - the main file is foobar.ino.
Any other .ino files in that folder are concatenated together, in alphabetic order, at the end of the main file (regardless of where the main file is, alphabetically).
This concatenated file becomes a .cpp file (eg. foobar.cpp) - it is placed in a temporary compilation folder.
The preprocessor "helpfully" generates function prototypes for functions it finds in that file.
The main file is scanned for #include <libraryname> directives. This triggers the IDE to also copy all relevant files from each (mentioned) library into the temporary folder, and generate instructions to compile them.
Any .c, .cpp or .asm files in the sketch folder are added to the build process as separate compilation units (that is, they are compiled in the usual way as separate files)
Any .h files are also copied into the temporary compilation folder, so they can be referred to by your .c or .cpp files.
The compiler adds into the build process standard files (like main.cpp)
The build process then compiles all the above files into object files.
If the compilation phase succeeds they are linked together along with the AVR standard libraries (eg. giving you strcpy etc.)

A side-effect of all this is that you can consider the main sketch (the .ino files) to be C++ to all intents and purposes. The function prototype generation however can lead to obscure error messages if you are not careful.

Avoiding the pre-processor quirks

The simplest way of avoiding these idiosyncrasies is to leave your main sketch blank (and not use any other .ino files). Then make another tab (a .cpp file) and put your stuff into it like this:

#include <Arduino.h>

// put your sketch here ...

void setup ()
  {

  }  // end of setup

void loop ()
  {

  }  // end of loop

Note that you need to include Arduino.h. The IDE does that automatically for the main sketch, but for other compilation units, you have to do it. Otherwise it won't know about things like String, the hardware registers, etc.

Avoiding the setup/main paradigm

You don't have to run with the setup/loop concept. For example, your .cpp file can be:

#include <Arduino.h>

int main ()
  {
  init ();  // initialize timers
  Serial.begin (115200);
  Serial.println ("Hello, world");
  Serial.flush (); // let serial printing finish
  }  // end of main

Force library inclusion

If you run with the "empty sketch" concept you still need to include libraries used elsewhere in the project, for example in your main .ino file:

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

This is because the IDE only scans the main file for library usage. Effectively you can consider the main file as a "project" file which nominates which external libraries are in use.

Naming issues

Don't name your main sketch "main.cpp" - the IDE includes its own main.cpp so you will have a duplicate if you do that.
Don't name your .cpp file with the same name as your main .ino file. Since the .ino file effectively becomes a .cpp file this also would give you a name clash.

  Declaring a C++-style class in the same, single .ino file (have heard of, but never seen working - is that even possible?);

Yes, this compiles OK:

class foo {
  public:
};

foo bar;

void setup () { }
void loop () { }

However you are probably best off to follow normal practice: Put your declarations in .h files and your definitions (implementations) in .cpp (or .c) files.

Why "probably"?

As my example shows you can put everything together in one file. For larger projects it is better to be more organized. Eventually you get to the stage in a medium to large-size project where you want to separate out things into "black boxes" - that is, a class that does one thing, does it well, is tested, and is self-contained (as far as possible).

If this class is then used in multiple other files in your project this is where the separate .h and .cpp files come into play.

The .h file declares the class - that is, it provides enough detail for other files to know what it does, what functions it has, and how they are called.
The .cpp file defines (implements) the class - that is, it actually provides the functions, and static class members, that make the class do its thing. Since you only want to implement it once, this is in a separate file.
The .h file is what gets included into other files. The .cpp file is compiled once by the IDE to implement the class functions.

Libraries

If you follow this paradigm, then you are ready to move the entire class (the .h and .cpp files) into a library very easily. Then it can be shared between multiple projects. All that is required is to make a folder (eg. myLibrary) and put the .h and .cpp files into it (eg. myLibrary.h and myLibrary.cpp) and then put this folder inside your libraries folder in the folder where your sketches are kept (the sketchbook folder).

Restart the IDE and it now knows about this library. This is really trivially simple, and now you can share this library over multiple projects. I do this a lot.

A bit more detail here.


NRF24L01+ (TMRH20 library): Receiver gets blank data I am working on sample Arduino project for communication over NRF24L01+ (TMRH20 library), everything is working fine with my example except one issue my Receiver gets message but that message is blank. Now i am not sure how do i debug as per serial monitor data is getting transmitted, as per receiver serial monitor it receives data but its blank.

Transmitter code -

// SimpleTx - the master or the transmitter

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

const byte slaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

char dataToSend[12] = "Msg AKSHAY";
//int dataToSend = 1;
char txNum = '0';

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000; // send once per second

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleTx Starting");

    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.setRetries(3,5); // delay, count
    radio.openWritingPipe(slaveAddress);
}

//====================

void loop() {
    currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {
        send();
        prevMillis = millis();
    }
}

//====================

void send() {

    bool rslt;
    rslt = radio.write( &dataToSend, sizeof(dataToSend) );
        // Always use sizeof() as it gives the size as the number of bytes.
        // For example if dataToSend was an int sizeof() would correctly return 2

    Serial.print("Data Sent ");
    Serial.print(dataToSend);
    if (rslt) {
        Serial.println("  Acknowledge received");
        updateMessage();
    }
    else {
        Serial.println("  Tx failed");
    }
}

//================

void updateMessage() {
        // so you can see that new data is being sent
    txNum += 1;
    if (txNum > '9') {
        txNum = '0';
    }
    dataToSend[10] = txNum;
}

Receiver code -

// SimpleRx - the slave or the receiver

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

const byte thisSlaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN);

char dataReceived[10]; // this must match dataToSend in the TX
bool newData = false;

//===========

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleRx Starting");
    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.openReadingPipe(1, thisSlaveAddress);
    radio.startListening();
}

//=============

void loop() {
    getData();
    showData();
}

//==============

void getData() {
  if ( radio.available() ) {

       radio.read( &dataReceived, sizeof(dataReceived) );
      Serial.println(dataReceived);
       newData = true;
   } else {
       Serial.println("No radio available");
   }
   delay(100);
}

void showData() {
    if (newData == true) {
        Serial.print("Data received ");
        Serial.println(dataReceived);
        newData = false;
    }
}

Below is the output TX1 (Transmitter ) and RX1 is Receiver. You can see that Transmitter even gets acknowledgment also..

Both of my devices are arduino nano and below is wiring diagram between arduino and nrf24l01.

I also saw few post where people suggested using 100uf capacitor in NRF24L01 (GND & VCC), this helped me with accuracy in connection but data is still missing.

A couple of clarifications first

At the time instant 22:38, the receiver isn't detecting any available radio devices but at the transmitter side, an acknowledge is received. How is that possible? How is your tx getting an ack without the rx getting connected.
I have not seen slave adresses being set as - const byte slaveAddress[5] = {'R','x','A','A','A'}; For the record, NRF24L01 adresses are 5 bytes long by default and not 1 byte long as you have defined. While defining the pipe addresses, the first 4 bytes of the adresses should be same among all the pipe addresses. Only the last byte should be unique. Pipe addresses can be 0xF0F0F0F0A1, 0XF0F0F0F0B1, 0XF0F0F0F0C1, 0XF0F0F0F0D1, 0XF0F0F0F0E1 Try setting the pipe addresses as uint_64t address[5] = {0xF0F0F0F0A1LL, 0XF0F0F0F0B1LL, 0XF0F0F0F0C1LL, 0XF0F0F0F0D1LL, 0XF0F0F0F0E1LL};Do the same declaration at the receiver end too. And btw, you can specify any byte you want in the last byte of the address. Here I have defined the last bytes as A1, B1, C1, D1, E1.
To make sure that communication is successful, set some custom ack byte and compare it with the received ack. If both match, you can be sure that the rx did get the data. Sometimes, the NRF24L01 can pickup garbage values from stray signals present around and it can consider it as data sent by the receiver. So to avoid false triggering, its better to make a fool-proof ACK mechanism.


Clearing string buffer with memset after a serial read In using the SerialTransfer.h / pySerialTransfer libraries to send commands between my laptop and an Arduino Mega, I am sending multiple sequential strings between the devices. However, I'm having trouble "clearing" the receiving buffer on the Arduino side - it never shrinks, despite a few different attempts to clear the string (memset; a for loop).

I'm sending a string to the Arduino of the format , where there are anywhere from 1 to 5 asterisks.  Then the Arduino is simply sending the exact same string back, without any processing (as of yet).  And in the python terminal, I'm printing it all out; this is what I get:

SENT (17 bytes): <rand_len_str=**>
RECD (17 bytes): <rand_len_str=**>

SENT (18 bytes): <rand_len_str=***>
RECD (18 bytes): <rand_len_str=***>

SENT (19 bytes): <rand_len_str=****>
RECD (19 bytes): <rand_len_str=****>

SENT (17 bytes): <rand_len_str=**>
RECD (19 bytes): <rand_len_str=**>*>

SENT (18 bytes): <rand_len_str=***>
RECD (19 bytes): <rand_len_str=***>>

SENT (18 bytes): <rand_len_str=***>
RECD (19 bytes): <rand_len_str=***>>

As long as the string is growing, all is well - but see the error in the 4th pair, with the extra *> characters, etc.

The following is my Arduino code; I've tried to reset the receiving string using memset, but this seems not to be working.

#include "SerialTransfer.h"

SerialTransfer myTransfer;

const int CMD_LEN = 200;
char buff[CMD_LEN];
char received_str[CMD_LEN];

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

void loop()
{
  if(myTransfer.available())
  {
    //////////////////////////////////////////////
    // handle call from Python

    memset(received_str, '\0', CMD_LEN*sizeof(char));
    myTransfer.rxObj(received_str, CMD_LEN);

    sprintf(buff, "%s", received_str);
    //////////////////////////////////////////////

    //////////////////////////////////////////////
    // send response
    myTransfer.txObj(buff, strlen(buff));
    myTransfer.sendData(strlen(buff));
    //////////////////////////////////////////////
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");

    if(myTransfer.status == -1)
      Serial.println(F("CRC_ERROR"));
    else if(myTransfer.status == -2)
      Serial.println(F("PAYLOAD_ERROR"));
    else if(myTransfer.status == -3)
      Serial.println(F("STOP_BYTE_ERROR"));
  }
}

I didn't see anything in SerialTransfer.h about clearing the rxObj; I can always just use the first terminating > character to parse the command - but I imagine there is a cleaner / better solution in clearing the buffer, or at least, I'd like to understand what's going on! Thanks in advance.

Instead of clearing your buffers, make use of the bytesRead property.  Have a look at how they print the received string in the example code from the library using a for loop.  I don't know that it is null terminated or anything.

Example from the library's github page:

#include "SerialTransfer.h"

SerialTransfer myTransfer;

void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  myTransfer.begin(Serial1);
}

void loop()
{
  if(myTransfer.available())
  {
    Serial.println("New Data");
    for(byte i = 0; i < myTransfer.bytesRead; i++)
      Serial.write(myTransfer.rxBuff[i]);
    Serial.println();
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");

    if(myTransfer.status == -1)
      Serial.println(F("CRC_ERROR"));
    else if(myTransfer.status == -2)
      Serial.println(F("PAYLOAD_ERROR"));
    else if(myTransfer.status == -3)
      Serial.println(F("STOP_BYTE_ERROR"));
  }


Can two LEDs attached to different pins share their resistor? I'm designing an Arduino style board with built-in LEDs for several of the pins. To simplify assembly of the board and save on components, I was wondering whether it would be safe for those LEDs to share a single resistor, as in this diagram:

Obviously, the power dissipated through the resistor (3mA per pin @ 3V) is not a real problem. The reason I was hesitating is that LEDs in a parallel configuration should not share resistors, but is it safe to think that separate microcontroller pins don't count as a common anode, even if both pins are high?

Your circuit is safe from the electronic viewpoint, so long as the LEDs used can withstand a back-emf of 4v or so.

If only one LED is on at a time, all will be sweet. But if two or more are on, the brightness will drop and the brightness between LEDS will probably be inconsistent. The forward voltage drop of individual LEDS tend to vary a little, so one is likely to hog most of the available current.

A separate resistor per LED is probably best.


How would I give an Arduino-based product WiFi credentials? Let's imagine I create this cool little Arduino-based (replace Arduino with any embedded system that's not a Raspberry Pi) object that does some interesting things but it needs an internet connection to retrieve some information. The object doesn't have an input interface for the user because it would be meaningless if not for the WiFi credentials insertion procedure. In my testing instance, I can just hardcode the credentials before flashing the firmware, but what if I wanted to make it a product and have every user set it up on his own network?

How was such a task handled in some commercial products with similar challenges? Or what would the best way of handling it be?

Most WiFi chips/modules these days worth paying for can function both as a WiFi client or as an AP.

So, what you would do is when the device is unconfigured, put your WiFi module into AP mode, and serve up a lightweight webpage hosted from your device. The owner connects to the devices WiFi network, and accessing the device through that webpage, they can setup their wifi information. Once configured, you switch the WiFi back to client mode, and connect to the provided Wi-Fi network.


Delay in displaying data received from UART when used with PCINT on PIN0 I have been trying to find a solution for UART receive interrupt for my UNO board and I came across a possible solution in : PCInt

I did a small editing in the following portion of the code to make it work for UART.(code works like a loop-back test)

void RXint(void) {
char k;
if(Serial.available()>0)
{
k=Serial.read();
Serial.print(k);
}}
void setup()
{
Serial.begin(9600);
PCattachInterrupt(0, RXint, FALLING);
}
void loop()
{}

The code works pretty well with one big drawback.
The character displayed is having one char delay, what i mean is that for the following input

  qwerty

output is

  qwert

That means if I enter the 5th char,the output will be 4th one.
When the first input is given, it doesn't show output till the second input is entered.

Can someone help me out with this

(This is only a test code, the interrupt part is to be used in a larger code where the loop() carries out different tasks and interrupt is to be raised when data is received via UART)  .

Your interrupt is happening at the same time the START bit of the next frame is arriving in the hardware. As a result you don't have that data yet, because it's still to arrive. All you have is what has gone before. You won't get the new character until the frame has finished arriving and the UART RX interrupt fires and the byte gets copied out of the RX FIFO and placed into the Arduino receive buffer.

The way you are doing it is completely wrong. The data is already being captured using an interrupt and placed in a buffer for you to deal with as you see fit at a time that suits you (as long as it is before the buffer overflows).

If you can't read it fast enough using your main loop (or variations thereon) then you need to rethink how you are doing your main loop.


is it possible to program an arduino with usb/ttl adapter i want to upload sketch into arduino uno using usb/ttl adapter.i tried searching for it, but found about programming arduino using another. can anyone help me.

The Arduino onboard USB to serial is connected to D0 (Rx) and D1 (Tx).

And without a USB connected to the Arduino you can use a USB/TTL adapter connected to D0 and D1 like this;

Arduino  - USB/TTL
Tx       - Rx
Rx       - Tx

And to get the Arduino inte "programming" mode:

Automatic way, if the USB/TTL have CTS, connect it to Arduinos reset pin.
Manual way, press the reset button when the Arduino IDE starts to upload the code.


Arrays, and for loops... faster to use together, or not to use? I'm a 4th year EE undergrad, so I'm more of a hardware guy than software. But concerning best programming techniques, is it "better" (more efficient/and/or equally effective) to use for loops when trying to change several items in an array by the same mathematical operation?

--OR--

Is it best to list each item out and have each operation performed by the rate at which the primary "void loop" cycles?

I'm using a Teensy 3.2 board and trying to get a DSP reverb effect working. I have an array of 8 delay tap lines, each with a different time multiplier. I'm trying to determine if it will take more time to process a for loop for each delay-tap line, versus multiplying each element in my array without the additional loop. I need to minimize processing time at all costs to avoid additional system lag.

Sample code:

  //Set delay times
  for(int i = 0; i < 8; i++)
  {
    delay1.delay(i, pot1*pauses[i]);
  }

versus

  delay1.delay(0, pot1*pauses[0]);
  delay1.delay(1, pot1*pauses[1]);
  delay1.delay(2, pot1*pauses[2]);
  .
  .
  .

EDIT
Added sample code.

Have a look at the compiler output.

The Loop option

The first alternative produce a preface (setting things) and the loop itself.

Preface

40201803:   21c9        s32i.n  a12, a1, 8
40201805:   3109        s32i.n  a0, a1, 12
40201807:   00a0c2          movi    a12, 0

loop

4020180a:   202cc0          or  a2, a12, a12
4020180d:   01ccc2          addi    a12, a12, 1
40201810:   ff8585          call0   4020106c <delay>
40201813:   f38c66          bnei    a12, 8, 4020180a <_Z6XYtestv+0xa>

The unfolded option

While the unfolded version is:

40201823:   020c        movi.n  a2, 0
40201825:   3109        s32i.n  a0, a1, 12
40201827:   ff8445          call0   4020106c <delay>
4020182a:   120c        movi.n  a2, 1
4020182c:   ff83c5          call0   4020106c <delay>
4020182f:   220c        movi.n  a2, 2
40201831:   ff8385          call0   4020106c <delay>
40201834:   320c        movi.n  a2, 3
40201836:   ff8345          call0   4020106c <delay>
40201839:   420c        movi.n  a2, 4
4020183b:   ff8305          call0   4020106c <delay>
4020183e:   520c        movi.n  a2, 5
40201840:   ff8285          call0   4020106c <delay>
40201843:   620c        movi.n  a2, 6
40201845:   ff8245          call0   4020106c <delay>
40201848:   720c        movi.n  a2, 7
4020184a:   ff8205          call0   4020106c <delay>

So, the loop execute 4 instructions per each array element, while the unfolded version had only 2 instructions per array element.

But you are trading speed for space and and risking an error while coding the same repetitive thing.

However, GCC (the 'Arduino' compiler) can unfold the loop by itself, so you still can write a loop but execute a sequence. Look at Tell gcc to specifically unroll a loop

Real numbers

I run a sketch (Arduino UNO) to time loop vs unfolded. The times for 1,000 execution of each method are:

loop:     6524us
unfolded: 3808us

Quit a difference!

Sketch

int pause[8] = {1, 2, 3, 4, 5, 6, 7, 8};
typedef int (*fn)(void);

void setup() {
  Serial.begin(9600);
  while(!Serial);
  Serial.println();

  Serial.print("Timing loop: ");
  Serial.print(time(met1));
  Serial.println(" us");

  Serial.print("Timing unfolded: ");
  Serial.print(time(met2));
  Serial.println(" us");
}

void loop() {

}

int time(fn f) {
  unsigned long start = micros();
  int x = 0;
  for (int i = 0; i < 1000; i++) {
    x = f();
  }
  unsigned long dif = micros() - start;
  return dif;
}

int met1() {
  int sum = 0;
  for (int i=0; i < 8; i++) {
    sum += pause[i];
  }
  return sum;
}

int met2() {
  int sum = 0;
  sum += pause[0];
  sum += pause[1];
  sum += pause[2];
  sum += pause[3];
  sum += pause[4];
  sum += pause[5];
  sum += pause[6];
  sum += pause[7];
  return sum;
}


How to scroll data in LED dot matrix through multiple modules? I've been struggling in this issue for a long time, I know there are people who have done it.

But, I don't have much experience in C to have the skills to design or develop such complicated functions.

I want to scroll data, e.g. text, chars or numbers just like the nice projects in YouTube about the dot matrix.

Like this one: How to Make a SCROLLING TEXT Display at Home

I know how to display a char, but I don't know how to scroll it. If I try I don't get the results I want.

This is my function for displaying chars:

void draw(void)
{
  s=0;
  uint8_t data_shift_buf;
  for (l=0;l<26;l++)            // to print 26 letters
  {
    for (row=1;row<9;row++)     // for 8 matrix rows
    {

        SPI_TX_m16(data = (row<<8) | (Alphabet[s]),4);// trying set data by column
        s++;_delay_ms(300);
    }
  }
}

This is the function for my problem.

void draw(void)
{
uint32_t map_buffer=0;int8_t i,k;
uint8_t data_reg[4] = {0xaa,0xbb,0xff,0xff};      // random data to write
uint8_t dis_buf[4],no_device,no_col;s=0;l=3;

for (i=0;i<4;i++)
map_buffer |= data_reg[i] << i*8;                 // loading data into map_buffer

for (col=0;col<32;col++)                          // for 8 matrix columns
{
    map_buffer >>= 1;                            // start shifting the data by 1 pixel
    for (i=0;i<4;i++)
    dis_buf[i] = map_buffer >> i*8;              // loading shifted data into display buffers
    for (i=0;i<4;i++)
    {
        for (row=1;row<9;row++)                 // for 8 matrix rows
        {
            SPI_TX_m(data = (row<<8) | (dis_buf[i]),i);
        }
    }_delay_ms(1000);
}

}


listing sd card files on a tft screen I'm currently working on a Arduino project that plays audio files from SD card through a speaker.

First Arduino sends the list of all music files, and when I send it a file name, the music is played.

The project is working well but there's no GUI. Everything has to be done via serial, and now I want to add a TFT screen that will list the music files on the screen, so that whenever I touch a file name  it should be played.

I haven't bought the TFT yet, and that's because I have a little question for which I need an answer.

If I start listing the files, can I scroll up and down ? Because at some point the TFT screen will become full of text, and I don't want the text to be overwritten.

Any help would be appreciated.

If I start listing the files, can I scroll up and down ? Because at some point the TFT screen will become full of text, and I don't want the text to be overwritten.

If you program that kind of facility, yes.

A TFT screen is like a blank piece of paper, and you have a set of crayons. You draw on the screen (sometimes with pre-defined shapes, called "letters"). If you want to change what is on the screen you can either throw away your piece or paper and start with a new blank page, or you can get some Tip-Ex® and cover up parts that were there already so you can draw over them.

If you want scrolling you will have to work out for yourself how best to do that given the limited resources you have available.

The simplest method is just to retain a list of the filenames in memory and print just a subset of them on the screen. "Scrolling" then just means displaying a different subset of names.