text:
RFID access system with PN532 reader
I have a PN532, so it's capable of both reading and writing. I've used it for a few perfectly functional things, but I want it to authenticate based on the contents (for example 1024 bytes) of a tag.
I'd generate some pseudorandom data, possibly on my PC, and write that into each card, and use a checksum of that as the key.
Should I just stick with the standard authentication of tokens, or is this a worthwhile alternative method? The UIDs of the tokens are not interesting for authentication.
If worthwhile, what checksumming algorithms should I use? If not, would someone care to explain how I can program the memory of tokens, and how to use that in addition to UID for auth?
Thanks in advance.

First off, you don't want to use a checksum for authentication.
A checksum can be thought of as a hash with a very small size. The smaller the size of a hash the less unique it is. The less unique it is the more likely it is that incorrect data will generate the same hash and authenticate someone it shouldn't.
For instance, a 32 bit checksum (hash) of 1kB data (8192 bits of information) is a 256-fold reduction in the uniqueness of the value. At 32 bits you get 232 unique values. With 8192 bits you get 28192 possible values. I can't calculate how many values that actually is, but as you can imagine there will be many billions of billions of combinations that would all equate to the same checksum.
If you must use a checksum then make it an actual recognised hash. For instance an MD5 (considered weak by today's standards) has 128 bits. SHA-256 has, as you would imagine, 256 bits.
However calculating these hashes on an Arduino is not a simple matter owing to a lack of memory. Not impossible, but not that easy.
If you're going as far as to use such large amounts of data for authentication and using heavy mathematical routines to create a hash you may as well go the whole hog and use a proper cryptographic key pair.
One method would be to encrypt the UUID of the card off-line and store the encrypted result on the card - that data would then be unique to that card and tied to it - you wouldn't be able to clone the card unless you could clone the UUID as well.
Then either the UUID is read by the Arduino and also encrypted using the same key and if the results match authentication succeeds. Or the encrypted value is decrypted by the Arduino and compared to the UUID to see if they match. Which you choose depends on if you have asymmetric or symmetric encryption (the former is more like a hash but requires the encryption key to replicate it whereas a hash doesn't).
You can also include other information with the UUID, such as the name of the card owner (for identification purposes), etc - as long as you are able to already know that data to create the cryptographic has to compare with what is on the card.

How should I go about reading the UUID, mangling it, and writing a new UUID to a token? A few google search phrases will suffice.

It is prudent to say that I used your uid-database-on-EEPROM idea, and it was excellent. Very sleek. Now you are the last hope for my precise control of the data on my RFID tags. You, gerben, gammon et al, but mostly you. Please answer:)


text:
Arduino Wire communication with MCP23008 GPIO pin expander to turn on an LED with a button press
I am using an Arduino Uno and an MCP23008 GPIO pin expander, I have a momentary button connected to GPIO 2 on the MCP23008 and an LED light connected to GPIO 1 on the MCP23008. What I want is for the LED to turn on when the button is pressed down, and off otherwise. The code I currently have is this:
   #include "Wire.h"       //import Wire library
   byte inVal;             //declare byte variable

   void setup() {

      Serial.begin(9600);
      Wire.begin();
      Wire.beginTransmission(0x20);   //MCP23008 i2c addr
      Wire.write(0x00);               //MCP23008 internal register addr for I.O.dir
      Wire.write(00000010);           //set all pins as output, except for #2 as input
      Wire.endTransmission();
    }

    void loop() {

      Wire.begin();
      Wire.beginTransmission(0x20);   //MCP23008 i2c addr
      Wire.write(0x09);               //MCP23008 internal register addr for GPIO access
      //Wire.write(0xFF);             //set all output pins to HIGH, commented out for now.
      Wire.endTransmission();
      Wire.requestFrom(0x20,1);       //get one byte of input input from MCP23008
      inVal=Wire.read();              //set pyte as variable

      //Serial.println(inVal,BIN);    //output byte to serial monitor, commented out for now

      Serial.println(bitRead(inVal, 1)); //output second bit from byte(1 or 0, for HIGH or LOW, depending on the press of the momentary button.
      if((bitRead(inVal, 1)==1))      //if the bit from the button is high,
      {
        Wire.beginTransmission(0x20);
        Wire.write(0x09);
        Wire.write(0xFF);             //then set all output pins as HIGH
        Wire.endTransmission();
      }

      else if((bitRead(inVal, 1)==0))  //if the bit from the button is low,
      {
        Wire.beginTransmission(0x20);
        Wire.write(0x09);
        Wire.write(0x00);             //then set all output pins as LOW
        Wire.endTransmission();
      }
    }

I don't know as much Arduino as I do Python, and I have even less experience with i2c connections and the Wire library, but this looks to me like it should be working.
The bit printed on the serial monitor is HIGH, until I press the button once, then it stays LOW forever until I modify and re-upload the code to the Arduino.
Not sure what's going wrong here. Anything helps, thanks.

I see one major thing wrong at first glance:
  Wire.write(00000010);           //set all pins as output, except for #2 as input

That doesn't set GPIO 1 (which you call number 2 - counting starts at 0 not 1) to be an input, that sets GPIO 3 (number 4) as an input.  Numbers starting with 0 are octal, not binary. For binary the prefix is 0b:
  Wire.write(0b00000010);           //set all pins as output, except for #2 as input

And then you read using:
bitRead(inVal, 1)

which would have read GPIO 1 which is configured as an output.
So you have a switch on GPIO 1 which is an output, which you then drive high (causing a short internally which can damage the pin), and as a result you drive the pin HIGH internally. Now it's always high, so a read of the pin sees the HIGH you are driving from it. Hence it gets stuck at 1.
Fixing your IODIR write should help solve that problem.

I changed the IODir to Binary, but it still isn't working, and in the same way. (At one point,  the led started blinking every second, I don't know why, and I have been unable to replicate this. What I want is to get high/low input from pin 1, if it is high, set pin 0 out as high, if it is low, set pin 0 out low. Been stuck on this for weeks now, and I don't get why. What am I missing? Thanks.

source: Stack Exchange

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

sort: votes


text:
How do I fix this error? It says "warning: invalid conversion from 'long int*' to 'long int' [-fpermissive]
I am working on an assignment that converts a reading of force into pounds and then finds the maximum and average of all the values received
This is my code:
void setup()
{

 // put your setup code here, to run once:

 Serial.begin(9600);

  // declare the outputs and inputs
  pinMode( 0 , INPUT);

  //figure out what pin the reading is going to be input to

  fsrReading = analogRead( 0 ) ;
  //the # is the same pin used to get input

  //or use analogRead ( # ), it depends if the pin input is on the analog side of the arduino

  // should this be under the while loop or here?

  //list functions here
  long ForceInPounds(long);
  long FindMax(long);
  long FindAvg(long);

  //declaring variables of functions
  FM = FindMax(new long);
  FA = FindAvg(new long);

        Serial.println("The max value is:");
        Serial.println(FM); //calls FindMax function

        Serial.println("The average value is:");
        Serial.println(FA); //calls FindAvg function

  }

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

 int counter1= 0;

  while (counter1< 100)
  //runs test 100 times

  //should I just make this a function? instead of embedding it in the void loop

 {
      Serial.print("Analog reading = ");

      Serial.println(fsrReading);

      //declaring variable of function used in this segment
      FiP = ForceInPounds(new long);

      Serial.print("Force in Newtons:");
      Serial.println(FiP); //calls ForceinPounds function

      counter1 ++;
  }

}

//FUNCTIONS

long ForceInPounds(const long)
// converts recorded voltage to resistance to conductance to force to pounds
{
 fsrReading = fsrVoltage;

 if (fsrVoltage== 0)
 {
   Serial.print("No pressure");
 }
 else
 {
   fsrResistance = 5000.0 - fsrVoltage;
   //convert voltage to resistance
   fsrResistance *= 10000.0;
   fsrResistance /= fsrVoltage;
   fsrConductance = 1000000.0 ;

   //convert resistance to conductance
   fsrConductance /= fsrResistance;
   if (fsrConductance <=1000.0)
   //convert resistance to conductance
   {
     fsrForce = fsrConductance/80.0;
   }
   else
   {
     fsrForce = fsrConductance - 1000.0;
     fsrForce /= 30.0;
   }
   fsrPounds = fsrForce/4.45;

   //convert force to pounds
 }

 return fsrPounds;
}

long FindMax(long)
{
  int counter2 = 0;

  while (counter2 < 100);
  {
    if ( fsrPounds > maximum)
    {
          maximum = fsrPounds;
          counter2++;
    }
    else
    {
          maximum = maximum;
          counter2++;
    }

  }
  return maximum;

}

long FindAvg (long)
{
  long start = 0;
  //variable to begin avg function
  long avg;
  int counter3 = 0;

  while (counter3 < 100);
  {
    start = start + fsrPounds ;
    counter3 ++;
  }

  avg = start/100;
  return avg;
}

What am I doing wrong? This is my first time working with Arduino.
Thanks

There are several problems with the code, and I can't reproduce the errror you gave with the code you gave. Is this the actual/real code you are getting this error with? Are you using the Arduino IDE?

Please post your entire code, or at least a Small Self-Contained Compilable Example.

I just added the rest of the code. Thank you. And yes, I am using the Arduino IDE.

This is most likely not what you want to be doing
//declaring variables of functions
FM = FindMax(new long);
FA = FindAvg(new long);

And it is entirely incompatible with these definitions
//list functions here
long ForceInPounds(long);
long FindMax(long);
long FindAvg(long);

With the result that you pass a pointer to a long (ie, its address in memory), to a function which is instead expecting the value of a long.
However, it's going to be hard to propose a solution until you edit the body of the functions into your question.
There's probably no reason to use new here at all - let the functions allocate their own temporary variables on the stack, since they seem to return a value rather than a pointer.  Most likely even if this worked, the new long you create would be abandoned - ie, a memory leak.

Thank you Chris, I just added the rest of the code for review. Thank you.

There are several fundamental problems with the code. It appears your understanding of function declaration, definition, and usage are not accurate.
This part:
  //list functions here
  long ForceInPounds(long);
  long FindMax(long);
  long FindAvg(long);

Is unneccesary.
setup() is not the place to declare function variables:
  //declaring variables of functions
  FM = FindMax(new long);
  FA = FindAvg(new long);

If your functions use variables internally, the place to declare them is within the function definition.
In your FUNCTIONS section, you start off defining this function:
long ForceInPounds(const long)

The first long declares that the function will return a long, and the (const long) would normally declare what variable types your function accepts as parameters, as well as the name(s) of said parameters. You have only provided a type long, and a modifier const, but no name. It doesn't make sense to pass in a const variable anyway, as the const indicates the content of the variable will never change from the initial value. In your code, not only is the variable not named, it is not given an initial value.
Within that ForceInPounds() function, you start with:
  fsrReading = fsrVoltage;

which overwrites your initial fsrReading = analogRead(0); with an undefined value, as you have neither declared a type for fsrVoltage, nor given it an initial value.
Also, you call analogRead(0) once in setup, so it only captures the value once. The fsrReading variable is not continually updated with the analog reading. You have to keep calling analogRead(0) and storing it in a variable each time through your loop.
There are other problems with the code, but these are a few of the fundamental problems. There is no simple/quick fix to your code.
If you don't come from a C or C++ background, you may want to read a quick overview of them, at a minimum. Start with some of the Arduino example sketches and get a good understanding of how functions are defined and how they work.

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


text:
Communication with ESP, HTTP requests or WebSocket?
Here is my problem. I'm working on making a wifi addressable RGB LED (like WS2812b) controller, I'm using an ESP8266 as the hardware. I'm also creating a phone application for controlling the device and setting different modes. What I'm doing right now is that I communicate with the module by sending GET commands from my phone app. For example to change the brightness I send http://192.168.4.1/I125I Then on the ESP side the code is as follows:
WiFiClient client = server.available();
  if (client) {
  String inData= client.readStringUntil('\r');
  if (inData.indexOf("I")!=-1){
 BRIGHTNESS=str2int(inData.substring(inData.indexOf("I")+1,inData.lastIndexOf("I")));
}}

It works, but I'm not sure if this way of sending data is efficient at all. if change colors too rapidly the ESP resets. I recently found another code that uses GET and POST commands but different methods are used, like the following
server.on("/brightness", HTTP_POST, []() {
    adjustBrightness();
  });

Then inside adjustBrightness function brightness is adjusted. This way it looks more professional but Is it more efficient?
I recently bought a commercial RGB LED controller that uses ESP8266 as its core. I tried to see what the phone app sends to the controller using the Drony app. For my app I could see all the get command the app was sending
192.168.4.1/I255I

192.168.4.1/R200RG90GB76B

...

but for the commercial controller I just saw one connection, something like "157.10.12.10:5172"
Is this using websockets?
Is using websocket a better way? is it more robust?
I'm writing the code in Arduino IDE.

This way it looks more professional but Is it more efficient?

No, the differences are minuscule. It's only really the location of any parameters that are different - either as part of the URL (GET) or as part of the body (POST).

Is this using websockets? Is using websocket a better way? is it more robust?

No, it's just a TCP connection (or maybe UDP connection, it's hard to tell from your description) sending unknown data. It's impossible to tell what the data us from the port number, you would have to actively sniff the data and work out what it is.
Yes, it is generally more efficient doing that kind of thing (though not necessarily more "robust") - HTTP is a very generic system that can transfer many different kinds of data in a request so needs large amounts of superfluous information that is not applicable to controlling an LED, whereas a simple TCP or UDP socket only transfers the minimal amount of data needed to get the job done.

So that's why I get slower responses when I use POST request instead of GET. I think I will get better results with websockets when I bombard the ESP whit color changing commands and hopefully get fewer restarts. Thanks for your answer.


text:
Connecting Arduino Uno to a smartwatch via bluetooth
I have a U80 Smartwatch from Bluetooth Watch International, which has bluetooth function. It is meant to be connected via to my smartphone (and it works perfectly).
I also have an Arduino Uno board and a corresponding BLE ZS-040 bluetooth chip.
I need for my smartphone to be able to detect my Arduino board, so I can send data from a simple circuit connected to the Arduino board to the smartphone.
Basically, my circuit is meant to be a simple push button. When the button is pushed, and the circuit is closed, the Arduino board will send a signal to the smartwatch. This will cause the smartwatch to ring and vibrate, as if it is receiving a call. Then to turn off the ringing and vibrating, the user can simply 'answer the phone call', and it will stop.
From what I understand, (I'm very new to Arduino) I have to connect the Arduino board to the smartwatch first, which means I have to somehow get the board to be detected by my watch, which it's not doing yet, eventhough the bluetooth module is connected to the board.
Then the push button needs to send a signal to the watch. Which means the command {if buttonpush='1', send (receiving call)}, so when the button is pushed, the signal is sent and the watch acts as if it is receiving a call. Basically showing all the physical signs (eg. vibrating and/or ringing based on the watch's setting, showing 'answer/deny call', etc.). Btw, the push button is not to be held down. As long is the button is pushed and released once, the signal should be sent, and the watch will buzz until the 'phone call' is answered or denied.

I have absolutely no idea how to get the board connected to the smartwatch via bluetooth.
And while I have a rough idea on the push button circuit I need, I also need to send the signal for the watch to act like it has received a call.

Mainly, I'm looking for any help with coding here. If anyone can help with the physical circuit connections, that would be awesome too.

What is your "corresponding bluetooth chip"?

Sorry, I have edited to add in the information. HC 05

Unless the watch has a developer API for bluetooth (master) you can not use anything else than the Android app to connect to it properly even assuming you have a BTLE module.

HC-05 is a Bluetooth 2.1 SPP only chip (BR/EDR). Your bluetooth watch will be Bluetooth Low Energy 4.x (BLE Single Mode).
The two are not compatible.
You will need a BLE module for the Arduino which is capable of running as a "Central Device".

Thank you. I was a bit confused between the two, but I managed to confirm that mine is ZS-040 which is the BLE chip I think ><?

This isn't exactly an answer but I will like to share my experience after attempting a similar project for the past week.
I have an Arduino UNO and a HM-10 Bluetooth module that is capable of functioning in central mode. I referred to http://www.martyncurrey.com/hm-10-bluetooth-4ble-modules to setup.
I am trying to connect the Arduino UNO/HM-10 with a Hexiwear (http://www.hexiwear.com) bluetooth IoT development smartwatch that is capable of sending sensor data such as steps, heartrate, temperature etc. via bluetooth to a BLE central device.
The Hexiwear will generate a random 6 digit pin when you attempt to connect to it. It works with its own companion Android app and reads sensor data perfectly. Someone managed to pull in the hexiwear's sensor data to a Raspberri Pi via BLE here: https://mcuoneclipse.com/2016/12/19/tutorial-ble-pairing-the-raspberry-pi-3-model-b-with-hexiwear/comment-page-1/#comment-97375.
With my Arduino UNO, I managed up to the point were I could connect the hexiwear and it pops up to ask for the random 6 digit pin so that it could pair to my Ardunio.
And then I am stuck, because I know nothing about the Arduino UNO and HM-10 that can send the pin code back to the Hexiwear.
Here's where I thought might be useful:
1) Do you have the U80's BLE specifications. This is how much hexiwear's BLE specification looks like https://github.com/MikroElektronika/HEXIWEAR/blob/master/documentation/HEXIWEAR%20Bluetooth%20Specifications.pdf.
My Hexiwear wearable comes with source code. If I try hard enough I can probably hack it to make what I want to do possible.
2) Does U80 require pairing with pin code? I am stuck here in my project.
3) Is the library for your BLE chip capable to sending said BLE requests and responses to communicate with the U80? This is where I believe I am going to be stuck further.
Hope this helps in some ways.


text:
RF receiver becomes weakened after motor turns on
I recently bought a simple SMAKN 315MHz RF receiver and transmitter, and I got everything working so that the transmitter transmits the value of a joystick, and the receiver receives that and uses it to set the analogWrite() of a motor on a PWM pin.
However, the moment the motor turns on, the receiver just weakens tremendously. At that point it only gets a message when I stick the receiver right against the transmitter. I’m powering the arduino and motor with a 3.7v LiPo battery btw.
Any help? I’ve tried with a 9V alkaline and a 9V adapter and nothing significantly changed.

What kind of motor? How is it wired?

@Majenko Just a simple brushed motor, it doesn’t even matter if the motor is on the transistor controlling the speed or just plugged into voltage and ground lines with a resistor, the receiver immediately will stop working

That behaviour is to be expected. Motors are very noisy and cause massive amounts of interference in radio signals.
The best thing you can do is to try and suppress that interference. For this you will need three 0.1µF (100nF) ceramic capacitors.
One capacitor is connected between the terminals of the motor to reduce noise transferred down the wires (wires make good antennae). The other two connect between each of the terminals and the metal body of the motor.
The metal body of the motor then becomes a shield to trap the noise.


text:
Unplanned behavior with two power sources
I'm trying to control this servo, and whenever I leave the Uno connected, via USB, to the PC, most of the time the servo barely moves, and sometimes jitters.

simulate this circuit – Schematic created using CircuitLab
I connected the oscilloscope to try to understand / solve my problem, and I see that the signal I send is the same whether or not the USB is connected. I measured the voltage over the 5V/GND and it's constant at 5V and doesn't dip/spikes. I tried with a pull-down resistor on the signal pin (don't know if it's a good idea) and it doesn't change anything.
If I unplug the battery, but keep the USB connected, the servo stays immobile, but I figure that's because the Arduino can't feed a servo, hence why I wanted to use an external power for it. The second power source is a PowerBoost 1000C with a LiPo battery.
As soon as I unplug the USB port, the servo just starts moving properly, so I figured it must be interference of some kind. I saw the accepted answer to this question and it has me doubt whether I should use a battery while it's plugged in, but surely there is a way. Would I kind of need to connect the GND of my circuit to the GND wire of the USB before it actually enters the Arduino?
I didn't post the code as it's basically just the swipe demo from the website, and because it works when on battery only.
Regards

Beginner error: As stated in the diagram, I connected the external source of power to the 5V pin, while it should have been connected to the Vin pin. /ashame

If that solved your issue please mark it as accepted.

I can't for the next 2 days. Should I just delete the question, since the likeliness of it helping anyone is slim?


text:
Arduino SDFat Libray overwrites last value
I'm trying to create a comma delimited file using this SDFat library
Calling this code creates my file
const char Header[24]="Desired RPM,Output RPM\n";
...
foo()
{
  SpeedCache.open("/Speed_Cache.txt",O_CREAT | O_RDWR | O_APPEND);
  SpeedCache.write(Header);
  SpeedCache.sync();
}
...

After running, I have a file containing

Desired RPM,Output RPM'\n'

When I call the following function, I want it to add int target and int reference to the bottom of the file.
bool SDClass::SetLine(SdFile Cache,int target, int reference)
{
  bool good = false;
  char NewLine[32];
  Cache.seekEnd();
  sprintf_P(NewLine,(PGM_P)F("%d,%d\n"),target,reference);
  Serial.println(good=Cache.write(NewLine));
  Cache.sync();
  return good;
}

On the first call, this works so for an input of SpeedCache,50,100 I get

Desired RPM,Output RPM'\n'
50,100'\n'

However, if I then write an input of SpeedCache,5,10 I get

Desired RPM,Output RPM'\n'
5,10'\n'

How do I adjust my function so that I will get:

Desired RPM,Output RPM'\n'
50,100'\n'
5,10'\n'

You just need to open the file in APPEND mode:
SpeedCache.open("/Speed_Cache.txt",O_CREAT | O_RDWR | O_APPEND);

O_APPEND
The  file  is  opened  in append mode.  Before each write, the file offset is positioned at the end of  the  file,  as  if  with               lseek.

You should also pass your file around by reference so it doesn't keep creating new copies of the internal structure:
bool SDClass::SetLine(SdFile &Cache,int target, int reference)

Adding | O_APPEND had no effect

Ok, passing the file by reference was the last thing needed for it to work.

How do you pass the file by reference?
SdFat sd;
SdFile DataFile;

isSD = DataFile.open(FileName, O_WRITE | O_CREAT | O_AT_END);

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


text:
Transfer serial data to struct variable in Arduino
I have declared a struct with some variables that right now are fixed, but one of the variables on the struct needs to be what the Arduino's serial port reads.
struct testing_var
{
    const char *name;
    byte key[32];
    byte pt[16];
};

static testing_var const test1 = {
    .name        = "Speck-128-ECB",
    .key         = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                    0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
    .pt   = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                    0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20},
};

As you can see for how I have declared it, I'm trying to get a plaintext from the serial port and the Arduino should encrypt that. I have a function that does this encryption, but I can't quite figure out how to pass what the serial port reads to the struct.
void loop() {

  if (Serial.available()>0) {
    var1 = Serial.read();
}

I need to pass this var1 as the variable pt in the struct. Any clues? I'm maybe missing something very obvious, but I don't usually work with structs.
EDIT:
I'm trying to assign the value read by the serial port to the struct by creating another function that goes like this:
void setPlain(struct PlainText *myPlain, const char* thePlain){
    myPlain -> plaintext = the Plain;
   }

Then, in the loop, I use:
  if (Serial.available()>0) {
    var1 = Serial.read();
    setPlain(&PlainText, var1)
}

I'm getting an error using this function, I guess that it has something to do with the type of variable I'm trying to assign, these values are in HEX, not in char. But I'm not really sure it that's it or what other workaround should I use.

You need to design and implement a protocol to encapsulate the data.

You read the serial port one char at time, and assign it to test1.pt[i], where i is an index varying from 0 to 15.
And test1 cannot be const, because you are going to modify it with the serial data.
Here is a test code showing how to do it.
struct testing_var
{
    const char *name;
    byte key[32];
    byte pt[16];
};

//  test1 cannot be 'const'
static testing_var test1 = {
    .name        = "Speck-128-ECB",
    .key         = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                    0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
    .pt   = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                    0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20},
};

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

void loop() {
  Serial.println("Enter 16 chars:");
  //  Read 16 chars from Serial
  for (int i=0; i < 16;) {
    if (Serial.available()) {
      test1.pt[i++] = Serial.read();
    }
  }
  // Do something with the data, like print it.
  for (int i = 0; i < 16; i++) {
    Serial.print(char((test1.pt[i])));
  }
  Serial.println();
}

Note to LuzA, the reason LookAlterno's example limits the plaintext to 16 chars is because your declaration, by providing 16 bytes of data initially, only reserved 16 bytes of memory.


text:
Changing Text Arduino inkShield
I have just received inkshield purchased from Nerd Creation Labs, I stacked inkshield on my Arduino Mega and uploaded THIS CODE provided by the creator of inkshield,and it works pretty well.
I can print text ;)
Questions :
1: The code given above can only print text in a single Font. Can i add multiple Fonts in a single code.?
2: How can i change the Font to something like Times New Roman, Arial,calibri or more stylish Fonts like snell RoundHand and Zapfino.?
Please help
Thank you

The fonts are the little bitmaps starting at line 50. Each 16 bit value is 1 column of the letter to be printed. There are 10 columns of pixels per character (the rowsPerChar value). The least significant bit is the bottom row.
So to change the font all you need to do is change those bitmaps.

Is there any software or online tool  to create such bitmaps?

1: The code given above can only print text in a single Font. Can i add multiple Fonts in a single code.?

Sure you can.

2: How can i change the Font to something like Times New Roman, Arial,calibri or more stylish Fonts like snell RoundHand and Zapfino.?

The top 700-odd lines of the code are the font. You just need to find a way of creating the same kind of data from your own chosen font.


text:
Alternative code for pinMode()?
In my code I need to set five pins to output mode. I have the pinMode() statements in my setup.
I am trying to make my Arduino code run a bit faster, and I came across a tutorial which swaps digitalWrite() for PORTB &= _BV(PB6) (high), and makes it run ~25 times faster.
I'm wondering if there's a similar type of substitution I can do for pinMode(), that will make it run faster as well? Or is pinMode() already a fast command, so I shouldn't worry about it?
Thanks

Things inside the setup are only done once, so optimizing those is rarely worth the trouble, replacing digital writes and reads (which are done often) will have more effect overall.

It isn't worth it for something done once, if you only do it in setup. However if you need to toggle the mode frequently yes it can be done. You sadly haven't said which pins, but assuming they are D2 to D6 (digital pins 2 to 6) on a Mega you can do this to set output mode:
  DDRE |= bit(PE3) | bit(PE4) | bit(PE5); // D5, D2, D3
  DDRG |= bit(PG5); // D4
  DDRH |= bit(PH3); // D6

For input mode you have to "and" in the ones-complement of the bits like this:
  DDRE &= ~(bit(PE3) | bit(PE4) | bit(PE5)); // D5, D2, D3
  DDRG &= ~(bit(PG5)); // D4
  DDRH &= ~(bit(PH3)); // D6

The exact register names are in the datasheet, and the mappings to the pins on your board are in the schematic (available from the Arduino site). The relevant part is this:

The bit numbers are in grey on the left (eg. PE4) and the board pin numbers are in green on the right (eg. 2 is digital pin 2).
The bit macro works similarly to the _BV one you mentioned in your question. It shifts 1 left the required number of bit positions to be in the right place.

A somewhat simpler and more portable solution is to use the digitalWriteFast library which you can download from:
https://github.com/NicksonYap/digitalWriteFast
This uses various compiler tricks to detect if you are using a constant for pinMode and digitalWrite and converts them into the appropriate register manipulation. You just install the library and add Fast to the function names, eg.
pinModeFast (2, OUTPUT);
digitalWriteFast (2, HIGH);

The Arduino reference manual has all you need to know:

https://www.arduino.cc/en/Reference/PortManipulation

The register you need is the DDRx register (Data DiRection X). Set a bit to 1 for output and 0 for input.

yeah. the corresponding registers are DDRx.
with a little bit of coding, you can easily convert pinMode() to your own, say, mypinMode() that operates on the DDRx directly.
the datasheet is your best friend, as always.


text:
Why is CLK_FLASH separate from CLK_CPU?
The ATmega328P has a separate clock signal for Flash and EEPROM (CLKFLASH) than it has for the RAM (CLKCPU). Why is this?

It's to do with programming the chip. When you are programming the chip using an external programmer you need the flash and EEPROM to be running. However you don't want the CPU to be running since you are doing things with the flash that it would normally access. By having the CPU (and RAM) on a separate clock you can clock the flash without clocking the CPU and all is well.


text:
STM8 Development Board with Arduino IDE
I got one of these cheap STM8 boards from China and was hoping to find a way to use this with arduino code.

Does anyone know of an arduino boot loader and board package that works with them ?

you get nothing with these links !!!!

Start the Arduino-IDE. In File->Preferences, Settings tab, enter
https://github.com/tenbaht/sduino/raw/master/package_sduino_stm8_index.json
Open Tools->Board:...->Boards Manager
Find Sduino by typing 'sd' into the search line
Click on the list entry
Click on Install.
This link is more comprehensive
https://tenbaht.github.io/sduino/

There is a bootloader on those chips to slow serial programming. A much easier way to to get a stlink debugger.
There are also some packages that allow Arduino styled programming on those chips. I wrote one myself that runs on iar and I think at least one on sdcc.
Those chips are really nice.

Hi, thanks for your reply. So how would I get started with programming this in the arduino IDE? There is a whole community around the STM32 and it's use with the arduino IDE, I followed some simple instructions from stm32duino.com to get going with the stm32. Is there an equivalent with this STM8 board?

Not to my knowledge, unfortunately. The stm32duino site has links to my stm8duino port on GitHub if you wish to try. It does require the iar workbench however .


text:
Is it possible to configure FRAM memory for use as stack and heap?
I'm using the Adafruit I2C FRAM breakout board with my Nano and it works as advertised, but every time I write a variable to this thing I have to use library function calls with addressing. This makes it run slower than I want it to, especially since I'm using the memory to keep camera pixel information and I need to process it quickly.
As user Majenko put it:

A write of a single byte requires 4 bytes in a transaction. That's 4 bytes, 1 start, 4 ack and 1 stop bit. So (4x8)+1+4+1 = 38 bits.
A read of a single byte, with "repeated start", requires 5 bytes per transaction, with 2 start, 4 acks, 1 nack and 1 stop. That's (5*8)+2+4+1+1 = 48 bits.
So for a read and write it's 38+48 = 86 bits.
Therefore you'd require 86*512 I2C clock cycles to transfer all 512 bytes in both directions - that's 44032 clock cycles.
At 400,000 bits per second it is 44032/400000 = 0.11 seconds, or 110ms of the time spend transferring data, not counting the time it takes to actually process and prepare the data, fill registers, look for status flags, etc.
If it is taking half a second then at 400,000 bits per second you have 44032 / (400000/2) * 100 = 22% of the time it's actually transmitting or receiving data over I2C.

It's much faster to write entire arrays at a time, but I need to write the data int-by-int as the data is encountered, since my whole reason for using the breakout board was to avoid needing local buffer space.
So is it possible to somehow configure this so that my I2C bus writes to the FRAM memory autonomously just like it does with the stack/heap in the onboard SRAM memory? Because then I could just declare my arrays as normal and let the processor take care of it, and then I would be so happy.

Have you looked into FRAM with an SPI interface, which may be capable of higher transfer speeds than I2C?

Thanks. Yes I have, but the small difference is only in write and read speed. 75% of the time I'm spending is actually taking care of the bookkeeping. Also, I'm already Using my SPI pins for an LCD screen.

No, you can't use SPI or I2C memories to store stack or heap data in AVR microcontrollers, as the AVR MCUs do not allow to map memories connected to the SPI or I2C buses. In other words, there is no way to tell the MCU that you connected a SPI or I2C memory, and how to use it, automatically. Therefore you can only use such memories to manually store/read data, by manually issuing all the correct command sequences, which will be very slow (as you wrote you are already doing by calling some libary functions).
Instead, you can use an external PARALLEL memory, connected to the external memory bus, which is present on SOME AVR microcontrollers (unfortunately, the ATMEGA328 has no external memory bus). Still you'll get a much slower performance with respect to the internal memory.
Finally, Arduino is not a  good platform to process (or store/read) pixel data from a camera, due to severe computing power and memory limits. Even if there are more powerful Arduino (or Arduino-compatible) boards, which feature much more powerful processors (e.g. Cortex M3 or M4), you would probably need to program them using a very optimized C (and not C++!) code, or even ASM. But at this point, there would no reasons to use an Arduino-compatible platform, instead of an another one, possibly much more powerful or even cheaper.

There's nothing wrong with using C++ for this application provided the C++ libraries used are non-terrible.

@IgnacioVazquez-Abrams for this application, using a powerful MCU with a good amount of RAM, yes. For a "tiny" MCU, you should save as many resources as possible. (besides, many - not all - Arduino C++ libraries are unfortunately terrible..)

Thanks, @next-hack. If I really have to, I'll just move up to a Mega and make my device larger (not happy about this). Arduino is fine for this particular camera application, since It's only a monochromatic linear CCD with just 128 pixels. It actually worked pretty great until I added more peripherals and started to run out of volatile memory.

Yes it is possible to have c variables use external RAM. The Atmel AVR FAQ discusses this. It's also possible to have the heap and stack (not recommended but possible), use external RAM.
Bear in mind that having this dealt with autonomously is still going to take roughly the same amount of time as it's going to have to execute similar functions to the ones you list above, albeit without having to code the transactions.
Have you considered a mega, and cache 1-6k of data then transfer that all at once. Using SPI would be faster, even more so with 1-6k. You can have an SPI LCD and RAM off the same pins, they just need an additional digital pin for the second device.

The "external RAM" discussed in that FAQ requires an actual external memory bus such as found on the ATmega64. There is no chance that it will work with a Nano, and certainly not over I2C.

Not even on SPI.

I don't have experience with FRAM, but below are some results with SRAM: 23LC1024 (128 KB SRAM with SPI). Tests have been performed with an Arduino Uno.
(I had to use an answer instead of a comment because of the (screenshot) table alignment.
As you can see, write/read of a page (32 bytes) is faster than other types, but it depends on the amount of bytes you have to write to use pages.
(Because I want to use reasonable complex structures, I decided to go for a microcontroller with more RAM because stack and heap space cannot be used from external SRAM).


text:
Combining 2 IF statements, getting nowhere and pulling hair out! ;)
I`m new here so just wanted to say hi!
I have been messing about with Arduino now for about 2 weeks, picking and trying different sketches for a greenhouse project I need.
Trying all sorts with LCD, temperature etc.
But what I actualy wanted was just a simple multiple timer say setting for every hour 9-6 activate for 2 mins to turn on a misting system for my plants, and that is now what I present in the following sketch, simple enough and it works, I have just removed some of the timings to keep the code compact on here.
Now the tricky bit, I want the misting system to come on in those hours chosen, but only if the Humidity is below a certain thresh hold, thats where I`m running into issues.
If anyone can look over the code and advise me where to put "if(h < humLowTrigger){"
I have tried before the times, included it in each line of the times and after the times and still not working.
So all help and knowledge greatly appreciated.
Cheers for now Alan
#include <Wire.h>
#include "RTClib.h"
#include "DHT.h"

#define humLowTrigger 70
#define DHTPIN 7
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

RTC_DS1307 rtc;

void setup () {

Serial.begin(9600);
dht.begin();
Wire.begin();
rtc.begin();

pinMode( A2, OUTPUT);
digitalWrite(A2, LOW);
}

void loop () {

float h = dht.readHumidity();
float t = dht.readTemperature();

DateTime now = rtc.now();

if (now.hour() == 15 && now.minute() == 5) {
digitalWrite(A2, HIGH);
}
if (now.hour() == 15 && now.minute() == 8) {
digitalWrite(A2, LOW);
}
if (now.hour() == 15 && now.minute() == 10) {
digitalWrite(A2, HIGH);
}
if (now.hour() == 15 && now.minute() == 12) {
digitalWrite(A2, LOW);
}

Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(' ');
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %");
Serial.println();
Serial.println();
delay(2000);

}

If you want to do something when two or more conditions meets , use an and operator (&&), like this:
if (h < humLowTrigger && now.hour() == 15 && now.minute() == 5) {
... do something ...
}

If you have a lot of conditional statements, you can simplify:
if (h < humLowTrigger) {
   if (... other conditions 1 ...) {
     do something 1
     }
   ...
  if (... other condition n ...) {
     do something n.
     }
}

In your specific case:
if(h < humLowTrigger) {
  if (now.hour() == 15 && now.minute() == 5) {
    digitalWrite(A2, HIGH);
  }
  if (now.hour() == 15 && now.minute() == 8) {
    digitalWrite(A2, LOW);
  }
  if (now.hour() == 15 && now.minute() == 10) {
    digitalWrite(A2, HIGH);
  }
  if (now.hour() == 15 && now.minute() == 12) {
    digitalWrite(A2, LOW);
  }
}

Better version
But there is a problem with the previous code, beacuse the mister must turn off no matter what the humidity level is.
// Turn on only if humidity below threshold.
if (h < humLowTrigger && now.hour() == 15 && (now.minute() == 5 || now.minute() == 10)) {
    digitalWrite(A2, HIGH);
  }
}
// Turn off always.
if (now.hour() == 15 && (now.minute() == 8 || now.minute() == 12) {
    digitalWrite(A2, LOW);
   }

Yes, but if the humidity has gone up (which is likely), then you won't turn the mister off. :) Turning it off has to be unconditional.

@NickGammon. Standard disclaimer: I just answered the question "I want the misting system to come on in those hours chosen, but only if the Humidity is below a certain thresh hold". There are other issues with the code, but adding to the answer will only confuse the novice. Other issues like: he is comparing for the exact minute to turn on the mister ... what if he turn on the Arduino at 15:06? What if he spent the full 15:08 minute doing something else? Mister keeps running!

Hi guys thank you very much for the quick response, I did try out the modded code and it works as you knew it would ;)
I also tried increasing the humidity whilst the output is high, and yes the output does not go low, that small issue is for another day when I have a better idea of what I`m doing ;)

There are other issues with the code ... - ah yes, I was anticipating the next question. :)

In addition to LookAlterno's answer (which I upvoted), the last part can be reduced to:
if ((h < humLowTrigger) && (now.hour() == 15)) {
  if (now.minute() == 5) {
    digitalWrite(A2, HIGH);
  }
  if (now.minute() == 8) {
    digitalWrite(A2, LOW);
  }
  if (now.minute() == 10) {
    digitalWrite(A2, HIGH);
  }
  if (now.minute() == 12) {
    digitalWrite(A2, LOW);
  }
}

See my comment under Look Alterno's answer. You need to turn the mister off at the designated time, even if the humidity has risen.

Note this was changed on the code of LookAlterno before he updated it.


text:
Sine wave PWM Arduino Micro
I'm trying to generate a sine wave on my Arduino micro.
I used this code.
int Pin = 9;

void setup()
{
 Serial.begin(9600);
 pinMode(Pin, INPUT);
}

void loop()
{
 float something = millis()/10000.0;
 int value = 128.0 + 128 * sin( something * 2.0 * PI  );
 analogWrite(Pin,value);
}

I have a low pass filter at the output of the pin to smooth the wave. The problem is : I get a nice square wave with a duty cycle from 0 to 100%, but not a sine wave. Ideally, I'd like to set a frequency of 10 Hz.
Can anyone tell me where I made a mistake ? Thanks a lot !!!

Maybe a bit of a delay? You will be changing the duty cycle very rapidly.

I tried it, the duty cycle of the square wave is changing according to the delay, but it's still not a sine wave.

then your low pass filter isn't enough

You can make a simple R-2R ladder DAC to create a sin wave. However it does require the use of many I/O pins, depending on the resolution you want in your sin wave.

it is how PWM works. digital pins can do only 1 and 0.

So it's not possible to do a sine wave?

Maybe use the PWM to charge a capacitor? You can balance charge and discharge with resistors to possibly get a pretty sinusoidal voltage on it.

I found you a tutorial that should help you to create a circuit that changes a square wave to sinusoidal wave. All you need to do is to output from your arduino 0 for 50ms and 1 for 50ms (to get 10Hz) and adjust the capacitor sizes to get a sin wave. (Tutorial shows circuit working for 10kHz square wave)
http://www.learningaboutelectronics.com/Articles/Square-to-sine-wave-converter-circuit.php

Can anyone tell me where I made a mistake ?

put a lpf on the pwm output.


text:
How do I program the Arduino Primo Core using the Arduino Primo?
the Arduino Primo Core website (https://store.arduino.cc/usa/arduino-primo-core) says that I can program the Arduino Primo Core using an Arduino Primo.
I have no idea how to do this!
Can you do it through the Arduino IDE? Which pins on the Arduino Primo Core should I connect to which pins on the Arduino Primo?
Thanks for your help!

instructions were on arduino.org. it is turned off now, but you can find them in Web Archive (without downloads)
Arduino.org pages in web archive

Juraj's answer answered my question, however I've gone back since and found the link to be broken. Fortunately I saved the file so I'll summarise here for others:

Download the nRF52 platform using the Boards Manager:

Connect the Arduino Primo Core to the Arduino Primo using a SWD connector (J2 on Arduino Primo Core and J9 on the Arduino Primo):

Plug the Arduino Primo into the PC using a USB data cable.
Select "Arduino Primo Core" from the Tools > Board menu:

Select the corresponding port of the Arduino Primo from the Tools > Port menu:

Select the Blink sketch from the File > Examples > 1. Basics menu.
Upload the sketch. If the light blinks on the Arduino Primo Core it has worked!


text:
How much power can a proto board handle?
I have been working on a project where I will be powering an Arduino and some LED light strips (2 x 3 Meter strips w/ 30 LEDs per meter). I am powering all of it from a 5v 10amp power supply.
Currently I have split the power cable and have it running to the board and the LED's in separate runs.
As I move from a breadboard to a more permanent proto-board, it would be great to add a barrel connector onto the proto-board and just have a single plugin for power so I can easily disconnect it.
Will this cause any issues if all of the power comes from the proto-board? Thanks!

Please provide information about how many LEDs, how long the light strips, and/or the measured current. Your supply can provide 10A, but that has little bearing on what is actually drawn by the system.

@Tyler Pearce What LED strip type are you using?

They are WS2812b/Neopixel strips. 2 x 3 Meter strips w/ 30 LEDs per meter

No, it's not practical do to that with protoboard of any form.
There are two reasons for this:

Barrel jacks are not rated for 10A - I think the most powerful I have seen is 3A.
To handle 10A over (for example) 6 inches of track you would require tracks roughly 8mm wide at 1oz copper. No protoboard provides such tracks.

Even if you're only using half the capacity of your power supply (5A) you still exceed a barrel jack, and would need traces about 3mm wide.

A common way to solve this is to solder a wire onto the tracks on the proto-board.

There is no problem to have your power source coming from your protoboard to supply your arduino since your protoboard can gives to your arduino one of these possibilities explained here.


text:
Problem with 16x2 LCD using Arduino
I've connected the circuit as shown in
https://www.arduino.cc/en/Tutorial/HelloWorld?from=Tutorial.LiquidCrystal
and I ran the program, but I can't fix this problem:
the LCD seems not to respond correctly: the first row is black and for what concerns the elements of the second, they all have three top lines of pixel high and the others low..
I checked over and over if I made some mistake connecting wires but I haven't found any error..
Is the LCD broken according to you? How can I fix?
Here the photos of the circuit:
https://drive.google.com/open?id=0B2h2zzEgtaqydElrRDVUNGVuWDA

Where's the sketch?

I looked the images you have on Google Drive. On the image called IMG_20170822_233722.jpg, I see you are using a 50k ohm potentiometer to control the display contrast. Normally you would use a 10k ohm potentiometer. Using the 50k will make the adjustment very sensitive and hard to adjust. If you are careful and adjust it slowly, it might work for you.
The other image, IMG_20170822_234242.jpg, clearly shows "poor solder joint" connections on the display. D4 - D6 (especially D5 to D6) look like they could be "shorted" together. I think you could fix them by using Desoldering braid or if you don't have any, you could heat up each connection with your soldering iron then quickly "flick" the display to remove the solder. After you have removed the excess solder from each connection, I strongly recommend applying soldering paste to the connections next. The soldering paste really helps the solder to flow into the connection. Now try re-soldering each connection. I'm not sure what kind of solder or iron you are using but I can tell you what works for me. 25 watt pencil tip soldering iron with 22 gauge / 0.71mm rosin core solder.
I can't tell for sure from the pictures if any of the display pins are shorted together and I don't know if shorting them together will damage the display, Arduino or both.

Yes the soldering look cold and there is too much solder on it. https://cdn-learn.adafruit.com/assets/assets/000/001/978/medium800/tools_Header_Joints.jpg?1396777967 look at this for reference, and practice practice practice.

Black first row suggests that the LCD is incorrectly initiated. That's often caused by wrong code or wrong hardware / connection.


text:
Is there a way to power off external devices during deep sleep
I am looking to work with deep sleeping, particularly with the ESP8266 but this question applies to most all micros. I am interested in running the device off of battery power for as long as possible. My solution would be something like a weather station where you know you only want to take a measurement every x minutes. So, I would like to sleep as much as possible in between measurements to extend battery life as much as possible. However, sleeping the microcontroller is one thing. How about when you have some sensors that piggyback off of the battery too. No need for those to be powered while the micro is sleeping and not taking a measurement.
Similar to this, I was thinking about reading the battery level. There are plenty of examples on how to do this online using a voltage divider (if necessary) and running the battery into analog input. This also draws from the battery while sleeping.
So, is there a way I can run all of these external sensors/devices through a transistor or something with low power draw when off and turn it all one when the device wakes up from sleep?
Thanks!

To answer your question, yes, you can use a transistor to stop excess power draw. Or do you want to know how to do it?

I made a temperature and humidity sensor which runs off 3 x AA batteries. It lasts a couple of years without changing the batteries, and writes to an SD card.
The power-control part of the circuit is here:

The general idea is that Q1 is used to turn on/off a "switched 5V" rail (5V_SW) to which are attached most of the peripherals. This is done in conjunction with power-down sleep mode on the processor. A watchdog timer wakes the processor every 8 seconds to check to see if it is time to take another reading.

The full schematic is:

I think I've changed the batteries once since making it in 2013.

Nick, excellent and detailed information. A couple of years would be nice but I am shooting for at least 6 months and am using a 2500mAh LiPo battery pack. The reason only six months? I am using a wifi (ESP8266) device to connect and send on wakeups and the sensors draw a fair amount when awake. I am okay with 6 months though. Do you think I can use a PNP (2N3906) instead of the FET to switch on and off?

The FET has much greater capacity to handle larger currents (47A compared to 200 mA). When you say the sensors draw "a fair amount" I would take that into consideration. I had another project that powered a transmitter just using solar power.

you don't have to send each wakeup; w/o wifi, the esp only uses about 15ma...

@NickGammon, is there anything specific about FQP47P06 transistor you used? I'm looking for something more common (and perhaps cheaper)?

@TomekCejner Not particularly, that just happened to be one I was able to get at the time, or already had to hand.


text:
How to read data from an NI DAQ?
I'm using an Arduino to control an experimental setup and read analogue signals from some sensors. But there are other sensors for which I need a DAQ for. I have a National Instrument USB-6259. On my PC I use LabView or NI SignalExpress to read data from DAQ connected via USB. Considering that I want the read data from different sensors to be synced, I was wondering if I could somehow read the DAQ directly on the Arduino?
Some other points:

I also have Arduino Ethernet Shield, if required.
The final goal is to have logged data synced so out of the box solutions are also acceptable for me.
If I'm not mistaken there are some versions of Arduino which you can install Linux on, just like a Rasppbery pi. There are even OSes for normal Arduino boards. There is a Low Cost USB DAQ Driver for use with Raspberry Pi for NI USB-6008/6009 devices. Is it possible to install this driver on Arduino?
I prefer not use a Raspberry pi because analogue/PWM read and write there is not as straight forward. So if there are other boards which are as easy as an Arduino with an OS compatible with current driver please suggest.

Unlikely.
First you would need a USB shield to be able to plug it in.
Second you would have to reverse engineer and then reimplement the proprietary protocols that device uses in order to get the Arduino to control the device.

I added more info to the post. How about Arduino boards which are more like a Rasperry pi and we can install a Linux on. and then install the driver offered by NI?

Those are compiled for arm and Debian. The Yun which is the only Arduino I know that runs Linux runs on MIPS And openwrt, so no, definitely not. Just use a pi.

Well, That's plan B, The issue with Pi is that as far as I know it doesn't have analogue or PWM data read and write which I use to read data from other sensors and control some valves.

It has PWM (it's fast enough to do it in software anyway, which is how I do it), and just add an external ADC over SPI or I2C. There's "hats" (what we call shields) that have ADC on them.

I asked my question on Rasperry py SO: https://raspberrypi.stackexchange.com/questions/71614/how-to-read-data-from-an-ni-daq-usb-6259

The main answer for your question is already given by Majenko, and is "no". These protocols are much more complicated than you can think, so no way.
However, if I correctly interpret your point 2 (which is The final goal is to have logged data synced so out of the box solutions are also acceptable for me), you don't need to do this. Just use your PC (or raspberry) to collect all the data and make a synchronization inside it. For instance, connect the arduino to the PC via bluetooth, add a serial connection in the labview program and then send all the data the arduino records to the serial peripheral; you will get all the infos in the labview program.
If for any reason this is not possible, you can use a common signal to sync the acquisitions. For instance, when you start the measurements you let the DAQ generate a long pulse (let's say 100ms), then every second or minute it will generate a shorter pulse (let's say 10ms); the arduino also records this signal, so you will have a way to sync acquisitions. Or you can do the opposite: the arduino generates and the DAQ records.
To sum up, the arduino is not capable of doing what you request, but maybe what you need is not what you asked for...

well,  unfortunately raspberry pi is not an option either. NI doesn't even support common linux distros! it is not easy for me to work on a windows machine, specially in the lab/workshop.  The main issue is the garbage sensor I'm using. I strongly discourage anybody from using the type of sensor I have.

@Foad I see your frustration here ;) in any case, if rPI is not supported then arduino, which is MUCH more limited, is totally unsuitable. Try syncing through other means (the signals I mentioned in the answer, or the serial interface). I think that you can implement everything in labview. Or, if you have the drivers for x86 linux, try putting linux on any x86 PC you have; if you succeed, search any x86 single board computer to replace the PC . For instance, wikipedia has a page with comparisons [...]

of SBCs; check the ones which have a x86 or x86-64 processor. Or, in the end, you can try to hijack the protocol between the sensor and the DAQ, and see if you can make a library in arduino to listen to that sensor..


text:
Sharing a Digital Pin / What to do when two components need a specific Digital Pin?
I am new to the world of Arduino and picked up an Uno R3. I have run into a situation where I have two components that specifically need digital pin 11, 12, 13 as specified by the libraries used to interact with them.
Each component also uses other pins that were able to be specified as different with the libraries but for those 3 the libraries say I cannot change them. What do you do in a situation like this? Is it somehow possible for two components to use the same pins? Any help is appreciated.
The two libraries I am trying to use are https://github.com/nRF24/RF24 (Wifi Receiver & Transmitter using component nrf24l01+) and https://github.com/steigeia/RFID_UNID_LOGGER/blob/master/libraries/AddicoreRFID/AddicoreRFID.h (RFID Reader/Writer using component RC522).

Which hardware (components)? Which libraries?

It seems probable that both libraries use SPI which connects to the SPI hardware on the chip via those pins. See How do you use SPI on an Arduino?
You haven't said what libraries, nor what hardware, but you possibly may be able to share those pins between the two devices. They would both need separate slave select pins. Often D10 (digital pin 10) is used as a default for slave select.
Another possible solution is to use "bit-banged" SPI for one device. I have a page on my forum about SPI which includes a bit-banged software implementation.
The library is at https://github.com/nickgammon/bitBangedSPI and is quite short.

Hey Nick first and foremost thanks for the time to help! I have added which libraries and components I am trying to use!


text:
How to record steps a stepper motor takes and how to rotate it backward and forward with analog input?
I am trying to control a stepper motor's movements with a pressure sensor input (0 to 5 V digital). For example, if the input is 4 V then the stepper motor should move forward 4 steps. If the input is 3 V then it should come backward 1 step. Please suggest a command in Arduino to keep record of the previous sensor value and steps taken by stepper motor.
This is the code I have written for simple rotation of the motor:
const int stepPin = 8;
const int dirPin = 9;
int sensorValue=A0;
int i;

void setup() {
  Serial.begin(9600);
  pinMode(sensorValue, INPUT);
  pinMode(stepPin, OUTPUT);
  pinMode(dirPin, OUTPUT);
}

void loop() {
  sensorValue = analogRead(A0);
  float voltage = sensorValue * (5.0 / 1023.0);
  if(voltage==1) {
    digitalWrite(dirPin, HIGH);
    for(int x = 0; x < 200; x++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(5000);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(5000);
    }
    delay(1000); // One second delay
  }
  digitalWrite(dirPin, LOW);
  for(int x = 0; x < 200; x++) {
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(500);
  }
  delay(1000);
  while(1);//only once
}

When the sensor is pressed constantly your algorithm moves some steps, waits a second and moves some steps and waits a second again. Is this your desired behavior or maybe you want the speed of the stepper depend on pressure?

No, i dont want the speed of the stepper depend on sensor ,speed would be constant.only  when the sensor gives some input stepper motor should move few steps and should stop there until it don't get another input .and if it gets input as previous input then it should return back to that position.

So if the sensor gives out constant value you just want to move some steps and then stop? If sensor gives 4V and after a second gives 3V you want the stepper to move 4 steps, wait and then move 1 step backward?

yes ,i wanted  the same.

Then use s global variable to save previous state of the sensor. Every cycle check if the new one is different. If it's not do nothing. If it is them move the motor and update the previous state of the sensor.

' #include <Stepper.h>
// change this to the number of steps on your motor
#define STEPS 200
Stepper stepper(STEPS, 8, 9);
int previous =0;
void setup() {
// set the speed of the motor to 30 RPMs
stepper.setSpeed(100);
}
void loop() {
// get the sensor value
float val = analogRead(A0);
stepper.step(val - previous);
previous = val;
}'

I have written above code but only problem is how to check  whether value   is new one or previous one.plz reply with code .thanks

I analyzed your code written in the comment and assuming that it works I prepared a modification that should prevent the motor from moving when the sensor is pressed the same way all the time. The noise values you have to adjust yourself. Make it as low as you can.
I cannot test this code, because I don't have your hardware. Treat it as pseudo code.
#include <Stepper.h>
// change this to the number of steps on your motor
#define STEPS 200
#define NOISE 0.1

Stepper stepper(STEPS, 8, 9);
int previous = 0;
void setup() {
  // set the speed of the motor to 30 RPMs
  stepper.setSpeed(100);
}

void loop() {
  // get the sensor value
  float val = analogRead(A0);

  float difference = previous - val;

  if(difference < -NOISE || difference > NOISE)
  {
    stepper.step(val - previous);
    previous = val;
  }
}

i have tested te code with hardware its working f9 now .thanks for the help :)


text:
upload.tool not used in custom boards.txt?
I've created a custom board in boards.txt and changed the upload.tool to a nonsense value, and yet when I do an upload the IDE still calls avrdude.
For example, In boards.txt I've changed the line...
tile.upload.tool=avrdude

...to...
tile.upload.tool=nogood

...and added these lines to platform.txt...
# NOGOOD programmer

tools.nogood.cmd="dir"
tools.nogood.program.pattern="dir"
tools.nogood.upload.pattern="dir"

...and reloaded the IDE and hit upload.. and it still runs AVRDUDE.
(Note that my board ID is tile)
I've verified that I am editing the correct boards.txt by changing the cores key to nogood and this does generate an error.
Is boardid.upload.tool not the right place to change the recipe called when upload is hit?
How/where does the boardid.upload.tool=toolname key in boards.txt get mapped to the tools.toolname.upload.pattern key in platforms.txt?
I am using Arduino IDE version 1.8.3.
The custom boards.txt is in the directory Arduino\hardware\Move38\avr.
This full custom platform package is here...
https://github.com/bigjosh/Move38-Arduino-Platform
Thanks!

If you leave the protocol unset in the boards.txt, then the current version of the Ardunio IDE (1.8.12) will then use the program recipe rather than the upload recipe in platform.txt. The program recipe can use the {protocol} key to get the programmer selected in the IDE menus.
Relevant source in Arduino IDE SerialUploader.java...
if (usingProgrammer || prefs.get("upload.protocol") == null) {
  return uploadUsingProgrammer(buildPath, className);
}

From https://github.com/bigjosh/Move38-Arduino-Platform#programmers:

Since there is no bootloader in a tile, all code must be programmed rather than downloaded.

When you do an "Upload Using Programmer", the tool is specified in the {programmerID}.program.tool property in programmers.txt. The {boardID}.upload.tool value is only used for a standard upload.
Since programmers.txt is not in your hardware package, this makes it very inconvenient to customize. What's worse is that the platform.txt associated with the selected programmer is used, rather than the one in your hardware package, for "Upload Using Programmer". For this reason, some popular hardware packages include their own copies of all standard programmers. The downside of this is it really clutters up the Tools > Programmer menu if you have multiple of these packages installed.

Ugg. So ugly. Thanks for the authoritative answer - these are hard to come by in Arduino land! :)

For future lookers, it does not seem like the {boardID}.upload.tool in platform.txt is always used for a standard upload. For example, it does not seem to be used if an upload.speed is not specified in boards.txt (even if the specified tool does not have a baudrate). It also does not seem to be used on OSX sometimes.

Custom tools for the Arduino build process are documented in the Boards Manager Package Index spec here...
https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.6.x-package_index.json-format-specification#tools-definitions
So it would seem that it i not possible to use custom tools with a manually installed board since there is no package index file.

This problem does not appear to be limited to only custom tools, it also seems to happen with built in tools like avrdude. :/


text:
How to compare two string?
I meet a terrible problem. I can't compare two string!
My job is simple, every 1ms use SoftwareSerial read_card(2, 3);to check if i read a id card.And don't read a card twice.Here are my code:
bool CardReader::check()
{
    String str= read_card.readString();
    if (str.length() == 0 ) return false;
    //Log("card:%s", str);
    Serial.println("card_id");
    Serial.println(str);
    Serial.println(card);
    Serial.print("cmp:"); Serial.println(str == card);
    if (str.length() == card.length())
    {
        uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)str.c_str();
        for (int i = 0; i < card.length(); i++)
            if (p1[i] != p2[i])
                break;
        return false;
    }
    card = str;
    return true;
}

Let's see output:
card_id
 Rq
 僐R
cmp:1

The hex are:
00 01 52 71 02
00 83 52 52 00

Why the two string is equal?
Bugs are fixed.If string begin with '\0',== can't work and = can't work either.
bool CardReader::check()
{
    String str = read_card.readString();
    if (str.length() == 0) return false;
    if (str.length() == card.length())
    {
        uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)card.c_str();
        for (int i=0; i < card.length(); i++)
        {
            Log("%d:%d", p1[i],p2[i]);
            if (p1[i] != p2[i])
                goto find_card;
        }
        return false;
    }
find_card:
    for(int i=0;i<5;i++)
        card[i]=str[i];
    return true;
}

Your question has been answered. Please, accept the best one to close this question.

Because both strings are empty. In fact, calling the method c_str() will give a an array, which has at its first position ([0]) the null terminator (0x00 or '\0'). What follows the 0x00, is just rubbish.
In fact, check the card length, it will be 0.
(btw, there are some bugs in the code too. It always return false if the string have the same length, and it will always return true otherwise. EDIT: following the Nick Gammon's answer I also noticed that you get the pointer of the same string :). I corrected also this).
I think the code should be rewritten to:
if (str.length() == card.length())
{
    uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)card.c_str();
    for (int i = 0; i < card.length(); i++)
        if (p1[i] != p2[i])
            return false;
}
else
    return false;
return true;

EDIT:
I add there what I wrote in the comments, for future reference, and explained in details.
The problem lies on the String class, which on one hand, it allows adding '\0' characters, through the method concat(char*), but on the other, it uses the strcmp (and other C standard functions) to perform compare between strings. This leads to unpredictable results. Maybe this is a bug in the String class.
In particular, SoftwareSerial extends Stream. Stream::readString() (which is used in the program to get str), is implemented as follows:
String Stream::readString()
{
  String ret;
  int c = timedRead();
  while (c >= 0)
  {
    ret += (char)c;
    c = timedRead();
  }
  return ret;
}

The line ret += (char)c; uses operator +=, which is implemented in WString.h as:
String & operator += (char c)           {concat(c); return (*this);}

Note that readString() also allows adding any non negative value of c, including 0, i.e. '\0' - see while (c >= 0) in its code above
In turn, concat(char c) is implemented in WString.cpp as:
unsigned char String::concat(char c)
{
    char buf[2];
    buf[0] = c;
    buf[1] = 0;
    return concat(buf, 1);
}

And concat(const char *cstr, unsigned int length) is implemented as:
unsigned char String::concat(const char *cstr, unsigned int length)
{
    unsigned int newlen = len + length;
    if (!cstr) return 0;
    if (length == 0) return 1;
    if (!reserve(newlen)) return 0;
    strcpy(buffer + len, cstr);
    len = newlen;
    return 1;
}

In the above method, length (instead of strlen) is used to determine the length of the string to add, and the new length is calculated using it:
newlen = len + length;

That's the bug: you can add a '\0' char to the string, and this will also result in an increased length of the string. They should have checked if length <= strlen(cstr), before performing this concat operation.
Now, if you call the method String::equals or use the operator == (it is the same, as it is defined in WString.h as     unsigned char operator == (const String &rhs) const {return equals(rhs);}), you call this code:
unsigned char String::equals(const String &s2) const
{
    return (len == s2.len && compareTo(s2) == 0);
}

Which, in turn, calls:
int String::compareTo(const String &s) const
{
    if (!buffer || !s.buffer) {
        if (s.buffer && s.len > 0) return 0 - *(unsigned char *)s.buffer;
        if (buffer && len > 0) return *(unsigned char *)buffer;
        return 0;
    }
    return strcmp(buffer, s.buffer);
}

And strcmp ends its compare operation if it first encounters a null operator (or when a compare mismatch occurs).
Therefore in your case, readString() added a null character to the "ret" String at first, and then some other characters. This created a String which begins with '\0'. Such string is equal to any other string beginning with a '\0', regardless what follows '\0'. But if you call length(), you'll get "len" (which String::concat() does not correctly calculate, and it will be non 0), as you can find in WString.h:
inline unsigned int length(void) const {return len;}

Disclaimer: future versions of WString.h and WString.cpp could have fixed this bug.

I had a think of the problem of '\0'.So how to get the real length of string?

No, length is right.It returns 5 when str begin with '\0'.And it should return true when str!=card because I find a new card.So I don't think there are bugs about condition.@next-hack.In addition,I found some strange things.Is it relative to memory?I have used 65%.

That's strange indeed, as in fact your first check for str.length() should make your function returning false immediately. Can you update your question writing also the code of read_card.readString() ?
Strange things could happen also due to misused pointers or buffer overflows...

.read_card isSoftwareSerial.And I already print str and card.

Ok, I got it. SoftwareSerial extends Stream. Stream::readString() simply adds characters, regardless their value, i.e. it concats also '\0' (i think it's a bug, they just check for >=0 instead of >0. Then String::concat(char c) also allows adding \0 chars, see WString.cpp. This lead to a malformed String, which can actually start with a \0, which is a null terminator. String class uses conventional C string functions (such as strcmp for operator == and for compareTo() method), therefore having a String with a \0 char will generate unpredicted results...

Thank you.I have solved it.But it's hard to create a dynamic length string.

More strange thing is that the operator= of string would alloc the right length memory, but wouldn't assign every value.

it's simple. The operator = creates a new string, whose length is determined calling oldString.length(), which just return the miscalulated "len" value (see my answer). However, it copies oldstring into newstring, using strcpy, which ends prematurely as the first null terminator is reached. ( http://www.cplusplus.com/reference/cstring/strcpy/ ). The remaining chars remain uninitialized ("random" value).

Why the two string is equal?

        uchar *p1 = (uchar*)str.c_str(), *p2 = (uchar*)str.c_str();

Both p1 and p2 point to the same string so of course they will always compare equal.

Do you mean:
if (str == card)
   // do something

Sorry, I write the compare function because  str == card didn't work.

Try strcmp()
See if  it works.

it wont even compile, str and card are String objects, while strcmp() works with char*.

Not a bad idea to use c-style strings this time maybe?

@dannyf maybe include instructions how to use char * instead of String?


text:
RFID does not respond after Ethernet.begin(mac, ip) initialization
Good day, I have this problem with my simple project. I have a database with all RFID number of employee. What I want to do is to use an rfID to check if it is registered in the database. If it is, it would return a value of 1 else would be a value of 0.
I tried with arduino HanRun Ethernet shield. I was able to get a response from the php web server to the serial monitor. Tried the seeedrfid it successfully get the rfcard number. However, when i tried to combine the two, it would hang on Ethernet.begin(mac, ip) initialization. My code is below.
#include <Ethernet.h>
#include <SoftwareSerial.h>
#include <SeeedRFID.h>

#define RFID_RX_PIN 10
#define RFID_TX_PIN 11

SeeedRFID RFID(RFID_RX_PIN, RFID_TX_PIN);

char state = '0';
char c;
byte mac[] = {0x60, 0xF8, 0x1D, 0xBA, 0x1D, 0x52};
IPAddress ip(192, 168, 20, 228);

EthernetClient client;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Serial set up");

  Ethernet.begin(mac, ip);
  Serial.print("My IP Address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {

  long rfID;
  // put your main code here, to run repeatedly:

  if (RFID.isAvailable()) {
    rfID = RFID.cardNumber();
    Serial.println(rfID);
  }
}

Serial.println(rfID) is not executed unless I remove the Ethernet.begin(mac, ip). Can anybody point me to the right direction?

It's NOT a HanRun Ethernet Shield! It's an unbranded Ethernet Shield happens to use a HanRun HR911105A RJ45 Socket with Integrated Magnetics on it. http://www.kosmodrom.com.ua/pdf/HR911105A.pdf

What pins did you connect the RFIC board to?

The Arduino Ethernet shield uses pins 4, 10,11,12,13. You have a conflict with the RFID pins.

SPI pins can overlap, SS should be independent. There's not too much info about the chipset used though.

can they overlap with software serial RX/TX?

SPI can't overlap with softserial.


text:
lcd not display
is it my coding wrong or my board have problem because my lcd does not display anything.
here my coding
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// set the LCD address to 0x27 for a 20 chars 4 line display
// Set the pins on the I2C chip used for LCD connections:
//                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x27, 6, 2, 3, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C add 27 / 3F

void setup()   /*----( SETUP: RUNS ONCE )----*/
{
  Serial.begin(9600); //
  lcd.begin(16,2);         // initialize the lcd for 16 chars 2 lines, turn on backlight
  lcd.backlight();

}

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{

  lcd.setCursor(0, 0);
  lcd.print("HELLO");

  delay(200);

  lcd.setCursor(0, 1);
  lcd.print ("HI");

  delay(2000);

  lcd.clear();

  delay(2000);

  lcd.setCursor(0, 0);
  lcd.print("NICE");

  delay(200);

  lcd.setCursor(0, 1);
  lcd.print ("GOOD ");

  delay(2000);

  lcd.clear();

  delay(2000);
}

this is how i wirring it. what should i do?

You should add some Serial.println() to know if the program is running (or at least make a LED blinking in the loop). Looking at the dispay, it seems to me that either the iniialization is not correct, or the contrast is not set properly (I can't see the external potentiometer/resistor, but that particular display might not require it).

but when i compile and upload in arduino it did not show any error. can you tell me where should i add Serial.println(). because this is my first time using this.

Well, put some lines after each time you call an lcd method. For instance, after lcd.begin(16,2); you could write Serial.println("After lcd.begin()"); Etc. If, on the serial monitor, you don't see "After Begin", then even the begin method does not succeed. This might be due to incorrect wirings.

the black bars indicate that the lcd isn't correctly initialized.
check the hardware / connection and make sure that your software initializes it correctly.

Well, I have the hardware, so I tested OP's configuration. It didn't work for me either. Same OP's problem.
The cause is the I2C address we are using (0x27). That's not my LCD address, probably neither your address. It's 0x3F in my case.
I discovered it I2CScanner, a short sketch that lists all I2C devices connected at that moment. So, run it (with the LCD connected) and watch with Serial Monitor for the address of your LCD.
Then replace all references to 0x27 (like lcd(0x27, 16, 2)) with your real address. Just change one value for the other.

This is I2CScanner
//
// Version 1
//    This program (or code that looks like it)
//    can be found in many places.
//    For example on the Arduino.cc forum.
//    The original author is not know.
// Version 2, Juni 2012, Using Arduino 1.0.1
//     Adapted to be as simple as possible by Arduino.cc user Krodal
// Version 3, Feb 26  2013
//    V3 by louarnold
// Version 4, March 3, 2013, Using Arduino 1.0.3
//    by Arduino.cc user Krodal.
//    Changes by louarnold removed.
//    Scanning addresses changed from 0...127 to 1...119,
//    according to the i2c scanner by Nick Gammon
//    http://www.gammon.com.au/forum/?id=10896
// Version 5, March 28, 2013
//    As version 4, but address scans now to 127.
//    A sensor seems to use address 120.
// Version 6, November 27, 2015.
//    Added waiting for the Leonardo serial communication.
//
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
  while (!Serial);             // Leonardo: wait for serial monitor
  Serial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print("Unknown error at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(5000);           // wait 5 seconds for next scan
}

the serial monitor show that my lcd address is 0x3F. but when i change my address in my coding and i start run the program the lcd start blinking but any of the word does not display.

Well, you also have to change that lcd.begin(16,2); with lcd.init(); I tested your code and it runs OK with that change. You are using old API calls. Study the examples that comes under **LiquidCrystal I2C" and learn how to properly use this LCD.

thank you for helping me. my lcd  already display. can you help me how to active the lcd using push button?

Google "arduino push button lcd" and you will find lot of examples.

i cannot find any examples that suitable. i dont know how to wiring it.can you help me?

@AINMIMI. You have to learn! Do the button examples that comes with Arduino IDE.

Thank you for showing me the i2c scanner! That's genius!

The first thing you have to do is run the examples from the library. If that doesn't works, check your connections and components.
If example works, it have to be your sketch (programing problem).
Good practice: write short sketchs that test only one component in your project. Example: your project use a LCD, a temp sensor, and a button, you wrote three short tests. If something goes wrong with your project, you can use the test sketchs to identify where the problem is

when i compile and upload this coding it didn't show any error. but lcd still cannot display anything. i already run the examples, but lcd still cannot display. what should i do? i just used lcd because i just need lcd to display. but it failed. Thank you for answering my question.

@AINMIMI. I think your LCD initialization is wrong. Your are using an I2C LCD, so initialization must looks like this: LiquidCrystal_I2C lcd(0x27, 16, 2);

i already change it into that but it still didn't work


text:
How is interaction with CDC device with no interface endpoints working?
I'm working on uploading to Digispark board. It uses micronucleus bootloader and i can see uploader code. I've modified it a bit to see interfaces and endpoints count:
    nucleus->device = usb_open(dev);

    // added by me - start
    int interfaces, endpoints, j;
    struct usb_interface_descriptor *interface = NULL;

    interfaces = dev->config->bNumInterfaces;
    fprintf(stderr, "Found interfaces: %i\n", interfaces);

    interface = &(dev->config->interface[0].altsetting[0]);
    fprintf(stderr, "Endpoints: %i\n", interface->bNumEndpoints);
    // added by me - end

    // get nucleus info
    unsigned char buffer[4];
    int res = usb_control_msg(nucleus->device, USB_ENDPOINT_IN| USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, 0, (char *)buffer, 4, MICRONUCLEUS_USB_TIMEOUT);

I wonder how it's working because interface #0 has no endpoints:
$./micronucleus --type intel-hex /tmp/Start.ino.hex
> Please plug in the device ...
> Press CTRL+C to terminate the program.
Found interfaces: 1
Endpoints: 0
> Device is found!
connecting: 40% complete
> Device has firmware version 1.6
> Available space for user applications: 6012 bytes
> Suggested sleep time between sending pages: 8ms
> Whole page count: 94  page size: 64
> Erase function sleep duration: 752ms
parsing: 60% complete
> Erasing the memory ...
erasing: 80% complete
> Starting to upload ...
writing: 100% complete
>> Micronucleus done. Thank you!

Usually i expect interface to have 2 endpoints (in & out from usb.h):
#define USB_ENDPOINT_IN         0x80
#define USB_ENDPOINT_OUT        0x00

Can anyone explain me how usb_control_msg(nucleus->device, USB_ENDPOINT_IN| USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0, 0, 0, (char *)buffer, 4, MICRONUCLEUS_USB_TIMEOUT); is working without endpoint?

Micronucleus uses control transfers to upload code (it's not a CDC device). You don't need an endpoint for control transfers - they use the implicit endpoint 0 that is always present whether you define one or not.
You only need to define endpoints for interfaces that want to communicate using bulk, interrupt or isochronous transfers.
Bus 003 Device 073: ID 16d0:0753 MCS Digistump DigiSpark
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               1.10
  bDeviceClass          255 Vendor Specific Class
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0         8
  idVendor           0x16d0 MCS
  idProduct          0x0753 Digistump DigiSpark
  bcdDevice            1.02
  iManufacturer           0
  iProduct                0
  iSerial                 0
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           18
    bNumInterfaces          1
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0x80
      (Bus Powered)
    MaxPower              100mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           0
      bInterfaceClass         0 (Defined at Interface level)
      bInterfaceSubClass      0
      bInterfaceProtocol      0
      iInterface              0
Device Status:     0x18c0
  (Bus Powered)
  Debug Mode


text:
Serial.println cuts off first digit
I'm trying to perform a simple analogRead() and print out the result, as below:

void getVoltMeter() {

  readValue = analogRead(A2);
  readByte = readValue/4;
  Serial.println(readValue);
  Serial.println(readByte);

}

But the output is:
023
255

The voltage input is 5V, so I would expect it to read:
1023
255

Why is the first digit being cut off?

What board are you using?

What does it look like if you swap order of the println() commands?

What happens if you add a Serial.println() first?

josecanuc: if I swap the print commands, it reads "4, 1024"
@Majenko I'm using an Uno. If I put a blank print statement first, it prints the values as expected without truncation, so this is a solution. I mostly just want to understand what's going on that would make this happen.

What are you viewing the output in?

In the serial monitor

You must share your full sketch here.

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


text:
Arduino and Optoisolators
I am looking for an efficient (and safe) way to use the Arduino to switch a higher voltage device off and on. The first option would be a relay, but they are fairly bulky. I was wondering if I should use an Optoisolator instead ?
Here is a link to the Data sheet for the Optoisolator I am using..
http://www.everlight.com/file/productfile/el817.pdf
I think (if I am reading it correctly) it expects an input voltage of 1V at about 20mA ?
However, I think it may be more involved than I originally thought. Here is a sort of simulation of what I am trying to achieve.
http://tinyurl.com/y9xd7lzb
As you can maybe tell, I am using a voltage divider to reduce the output from the arduino (from 5V to 1V).
My concerns are ..

Is this the best approach ?
Is it efficient ?
are there any problems I should be aware of ? Precautions I need to take ?
Is the voltage divider a good approach to feed the input to the Optoisolator ?

Also, efficiency is an issue as the Arduino (probably a Nano) will be running off batteries.
The target device is a 20V DC motor. I am a novice when it comes to electronics, so I would be grateful of any help or advice you can give.
Many thanks..
Dave.

How much current does the motor need ? An opto-isolator is always a safe solution. Often a opto-isolator is used to control a mosfet, but there are also opto-mosfets. The EL817 is 1 mA to 60 mA with 20 mA as normal. It is no problem to use 10 mA. For 10 mA, you need ( 5V - 1.2V ) / 20 mA = 380 ohm. Just one resistor of about 330 ohm to pin 1 is okay (and pin 2 to GND).

Is this the best approach ?

Not really, no.

Is it efficient ?

No, far from it.

are there any problems I should be aware of ? Precautions I need to take ?

You don't want a voltage divider to power an opto-isolator. An opto-isolator won't be powerful enough to cope with the motor current. You need flyback protection.

Is the voltage divider a good approach to feed the input to the Optoisolator ?

No, definitely not.
Unless you require galvanic isolation all you need is a simple NPN transistor or N-channel MOSFET circuit:

simulate this circuit – Schematic created using CircuitLab

your optocoupler's 2ndary side isn't powerful enough to switch a load.
use the 2ndary side to switch a switcher, instead.


text:
Yet another display 16x2 not working with arduino
I found hundreds of questions about display not working with arduino.
However, no matter how trivial this looks like I am having the same problem I cannot understand by reading the other posts.
I have an Arduino micro connected to a display from the adafruit kit
RGB LCD SHIELD KIT W/ 16X2 CHARACTER DISPLAY
I haven't been able to understand whether positive or negative, but I think from the picture is RGB positive.
I have connected everything as shown in the diagram in this page:
LCD "Hello World!"

Obviously changing the pins as I have
RS at 8
E at 7
d4 = 12
d5 = 11
d6 = 10
d7 = 9;

The potentiometer changes the contrast, if I saturate it I can see the black boxes.
In the code put this as
const int rs = 8, en = 7, d4 = 12, d5 = 11, d6 = 10, d7 = 9;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

I checked with the multimeter whether the soldering is good and it carries the signal at the end of the wires.
and the rest as the example in the link,
This is my mess (please ignore the other arduino and the thermocople which is not connected, the other orange wire goes to GND of the Arduino).

Any ideas that might help?

If you also have an Arduino Uno, I would try exactly the example on your link, to see if at least you haven't a bad display.

Agreed.  Whether or not you use Nano or Uno, wire it up precisely according to the instructions with no changes.  Test it that way first.  Then you can make changes as you like.

disconnect the E line, power up the system and adjust the contrast so you see 1 black bar on the first line;
reconnect the E line and see if your code is working.
go from there.


text:
Storing a counter to EEPROM - how to extend the life?
I am building a circuit that has a button, which when pressed, should increment a counter. I want to store this counter so that when I power off my circuit, it can be read when I power it back on. However, I am worried about the lifetime of the EEPROM - apparently it is only rated to handle 100k writes.
I am using an Adafruit Trinket Pro. Should I cycle my writes through different addresses so as not to write to a single cell over and over? What other strategies are there? I don't expect to be pressing the button many times in a short period of time - maybe at most one press per minute.
Is there some other external storage option I should look at? I really don't want my little project to die randomly one day because I've exceeded ~100k button presses!

Welcome to Arduino Stack Exchange.  Please take the tour at https://arduino.stackexchange.com/Tour to get the most out of this site.

There is an excellent application note on this subject. Please see AVR101 http://www.atmel.com/images/doc2526.pdf

Why not have a second button you push before powering off and have that trigger the write to EEPROM?  I have a sketch that modifies data once a second and need to be able to switch off without losing data, and this is how I am handling it.

Or have a storage cap and a circuit to trigger storing the counter into the eeprom on power loss suing the cap as a temp powersource.

If possible use a combination of wear-leveling like algorithm (as pointed out by Mikael Patel) and an power-down driven interrupt, to save onto EEPROM only when needed. At reset, load the last keypress count into a variable in RAM. Increment that variable in RAM on keypress, and save it to EEPROM only when a power down occurs (i.e. the interrupt is triggered). Optionally, when power down occurs, make sure to save the variable only if the new counter actually differs from the old value (i.e. if there actually were keypresses).
To implement the power-down driven interrupt use the built-in comparator to monitor a Vin (use a resistor divider!) against the internal Vref, and use the analog comparator interrupt to save the value. Remember to put enough capacitance between +5V and gnd, to make sure your arduino has enough time to save the state.
Alternatively, if you can afford errors (which might accumulate over time, and lead to a huge underestimation), save the value to EEPROM only every n keypresses.

maybe at most one press per minute.
That's great! You can just make some sort of timer to save every 2 or 3 minutes automatically. You said at most, so that should work. Here is example of code that can allow you to do so!
int cycleCnt = 0;    //Counter to count cycles
int cnt = EEPROM.read(0);         //Your press counter
bool currentlyCounting = false;   //Boolean to store if we are counting now or not
bool pressedBefore = false;

void loop() {
  if (digitalRead(button_pin) == HIGH) {    //You are holding the button
    if (!pressedBefore) {                   //And you didn't press it before
      //Here you do something you need with button
      currentlyCounting = true;       //After you pressed the button, we are starting to count time
      cycleCnt = 0;                        //and reset current counter (which would save us EEPROM writes!)
      cnt++;

      pressedBefore = true;                 //Mark button to be pressed so you don't do same code more then one time
    }
  }
  else pressedBefore = false;               //Mark, that you've unpressed the button

  delay(50);      //Delay in 50 mil won't affect speed of your button press, but it will allow us to count time
  if (currentlyCounting) cycleCnt++;          //Count cycles (every 50 mil)

  if (cycleCnt == 20 * 120) { //20 - amount of loop cycles to wait for one second. 120 - seconds in 2 minutes
    cycleCnt = 0;
    EEPROM.write(0, cnt);
    currentlyCounting = false;
  }
}

This might help you as well!
In case I misunderstood you and you meant "1 minute is the highest delay time beetween presses" then you should save automatically every half of minute or so

Cycling through the EEPROM is possible.
Is that button capable to last more than 100k presses ?
A button press every minute ? Really ? Is that during working hours ? That would take about year to get near the 100k writes (5 days per week, 8 hours per day, every minute).
If you want to count more than 100k key presses, then you probably store it in a 32-bit integer. That is 4 bytes. That means that when the Arduino is turned off while in the middle of writing that number to the EEPROM, that number is corrupted and lost forever.
With 1k EEPROM, you have 256 positions for the 32-bit integer. That means you can handle 25 million key presses.
My suggestion would be to store each new value of the 32-bit integer to the next location (circular). At startup you need code that interprets the numbers to find the last one and ignores a bad one and can handle a new Arduino with cleared EEPROM and even an Arduino that was used by you to develop the code. That means you need a command to clear the EEPROM.

Use brown out detection. Keep the count in ram until the mcu is losing power - only then save it to eeprom. Read the datasheet on bor.


text:
How can i change by esp8266 baudrate, as I accidentally changed the baudrate to something else(which I dont remember)?
//In order to connect,

SoftwareSerial esp8266(2,3);

// the TX pin of esp8266 is connected to pin 3 of
// arduino uno and RX pin is connected to 2
// we need to pass baud rate to begin function

void setup()
{
  Serial.begin(115200);
  esp8266.begin(???); // what should i do in order to make it work?
}

What should i do in order to make it work?

Simplest to just re-flash the AT firmware. Follow one of the many thousands of tutorials, or find all the answers here telling you how.

I tried to flash, everywhere it is asking for baud rate to communicate to esp8266,i tried 9600 which is configured for my arduino, it doesnt work.

You need the bootloader baud rate. Try 57600.

Hi Majenko, i tried all the possible standard baud rates(including 57600), did not work :/

I couldn't find a solution, So, bought new esp8266 and worked with it default baudrate (115200).

I encountered a similar situation where I accidentally set the baudrate to 8000 with the AT commands.
Thankfully I remembered the baud rate I set, so I used PuttY to create a serial communication with the port with the weird 8000 baud rate and changed the baud rate back to 9600.
The method can be found here: http://flower-platform.com/2015/12/16/esp8266-with-at-commands-connect-from-pc-with-putty/
The AT command I used to change the baud rate:
AT+UART_DEF=9600,8,1,0,0

I'm not going to vote this down, but you know "which I dont remember)" in the question title is probably designed to discourage this answer.