Arduino fingerprint verification from server I am thinking to do a hobby project related to fingerprint verification. The flow which I wanted to implement is something like below:

A user can register a fingerprint using an Arduino device
This fingerprint will be saved on a remote server so that user can be verified on some other Arduino devices
When a user tries to verify, the fingerprint will be matched against the fingerprint stored on the server

For this, I am thinking to use the Go language on the server side as an API server, MySQL/SQLite as a database system. Further, in the future, I will build a mobile application to perform some query with the server like running devices, the number of registered users, revoke users etc.

For now, I am planning to buy the following devices:

Arduino UNO
A wifi shield
A fingerprint sensor
An LCD screen

Now the question is, will the devices mentioned above will work for my setup, or I need to buy something else (Are they compatible?)

Also, is there a way to store the fingerprint on a server? I am thinking to store some kind of hash (probably RSA encrypted) of a fingerprint on a server, will it work?

Any relevant example of storing fingerprint on a server?

According to the adafruit driver's code, it is capable of loading and storing fingerprint templates (256byte each) from and to its flash

  uint8_t emptyDatabase(void);
  uint8_t storeModel(uint16_t id);
  uint8_t loadModel(uint16_t id);
  uint8_t getModel(void);

These functions would allow you to sync the local database of each device with a server for example or even download and test for each template individually, which would obviously be pretty slow and only viable, if you had to store more templates than the flash itself can.

You can encrypt this data before transmitting in whatever way you wish but that is a topic on its own.

Other than that your components seem to be compatible.

An idea for syncing:

Every unit should check on a fixed interval of 1 second for instance, whether the online database has changed. This may be represented by a simple counter i.e. version that increments with each change and is copied to local storage after downloading the latest changes.

So whenever an Arduino uploads a new fingerprint model or your mobile app removes a fingerprint, the counter on the server is incremented and every other device knows to update its database in case the local version is lower.

Another tip if changes happen very frequently:

Every flash memory just has so many write cycles before it dies.
If you happen to update the database a lot, you should try to minimize the stress on each fingerprint sensor's memory by assigning an arbitrary, unique id to each fingerprint and storing a local 'map' where you have stored which id on this specific device.
This way you can update only the fingerprint(s) that have actually changed.

Good luck.


ESP8266 Aes encryption using Arduino IDE I'm trying to implement an AES encryption function on my ESP8266 controller, using Arduino ide and this aes library.
I finally made it work after many attempts but the output i get from the encryption function is only numerical and it doesn't correspond to other encryptions made by other softwares.

This is the code part relative to the AES encryption:

 #include <AES.h>

AES aes ;
byte *key = (unsigned char*)"0123456789010123";
unsigned long long int my_iv = 36753562;
 tempToken = RANDOM_REG32 % 10000;
    randomstr = String(tempToken);
    //answer = "{\"token\":\"" + randomstr + "\"}";
    byte plain[4];
    randomstr.getBytes(plain, 4);
    Serial.println(randomstr);
    Serial.println(plain[0]);
    Serial.println(plain[1]);
    Serial.println(plain[2]);
    Serial.println(plain[3]);
    byte cipher [48];
  //  aes.iv_inc();
    byte iv [N_BLOCK] ;
    aes.set_IV(my_iv);
    aes.do_aes_encrypt(plain, 48, cipher, key, 128, iv);
    String ciphertoken = "";
    for (int i = 0; i < 48; i++) {
      ciphertoken += cipher[i];
    }
    answer = "{\"token\":\"" + ciphertoken + "\"}";

It basically generates a random number between 0 - 9999, then converts it in a byte array (because aes function needs a byte array as input), then encrypt this byte array and prints the output, written in cipher byte array.

This is the output I get from it

6188
54
49
56
0
{"token":"521111513725521540120674957151112223103194250224197251261938514437131212302201813929189123134524113912554682501508415421130220"}

I can't understand if I did something wrong of if it is formatted in a strange way and if I can get the right encryption from it

I don't know whether this is the only problem, but the way you are building up the string is bad: you are appending the decimal value of each byte of the cipher - so if your cipher array were, say, { 0x52, 0x11, 0x115, 0x137, 0x255, 0x215, 0x40, 0x1, 0x20 .... } you'd get the string you're getting: 521111513725521540120...  That's probably not what you want.

Probably what you want for that part is to base64-encode cipher, which you can find out how to do, for example, here.  (If you see encrypted stuff in printable format, usually it's base64 encoded.)


Integration of signal In my house, I have a low voltage AC signal (0-10V) that is proportional to the amount of current that is drawn at any moment (or as it is presented: kW) (europe, 50Hz). Presently, it is just shown as a dial in my kitchen, of course I would to log this. I want to rectify and integrate this singnal over an appropriate time span (maybe on minute) As far as I can see, I basically have two ways of doing this:

The pure arduino approach: Using a voltage divider to get it down to 0-5 V (after rectification) (and maybe throw in a zener diode as an extra protection) Then using an adc in the arduino and measure the voltage directly. The problem I foresee with this approach is that I will need a pretty high sampling rate to make sure I get the peak values. If I managed to sample at exactly the same frequency as my mains,I could just calibrate the measured value (unless I managed to hit the cross overs) but I do not think that would be feasible So I think I need to maybe sample on approx 500 Hz and pick out the highest value from each 1/50 second.
Using an opamp, a few resistors and a capasitor to set up an analog integration circuit, then use the arduino to read out and reset that at appropriate times. Setting up the integration circuit is no problem for me, but I need some feedback on the reset circuit. I have been looking around a bit, but I have not found any standard way to reset an integrator circuit, it seems like the idea is that it should be integrating for as long as it is running.. As far as I can see, as long as it running on <= 5V, I could use an input on the arduino to drain it? - I would then need to make the dimensions such that the low current the arduino input draws will allow the integrator to be reset fast enough.

Any comments? Have I overlooked something? is there a third approach that I have not been thinking about? Is the 1st approach easier that what I think?

Sorry, but.. Why integration? Just use a peak detector like this one:

The output will "float" to the peak value of the input signal, minus the voltage drop across the diode:

The output oscillates between 9.7V and 9.2V, which is a 5% maximum error. If you want to reduce it, sample with a sample rate not multiple of 50Hz and average the measures.

The RC constant is 500ms. This means that it will require less than a second to pass from a value to a lower one:

Here in almost 500ms it will go from 10V to 5V.

If you want to reduce the diode effect (9.7V instead of 10V) use a schottky diode. This, however, will not reduce the 9.2V effect.

You should divide by 2 the voltage; you can either

divide it before the diode (but then the diode effect will be more evident - you can however correct it in software
divide it after the circuit (In this case, replace the 500k resistor with two 250k resistors and take the voltage in the middle)

Of course 500k and 250k are not standard values, but you can use any nearby value without affecting the behavior


SIM800L starts sending garbage values to Arduino after random interval I have a SIM800L module connected to Arduino Mega's Serial3. SIM800L is powered by 4.2V power supply and I have put a voltage divider between Arduino's TX3 and SIM800L's RX so that the voltage in the line stays about 2V. The TX line of the module is directly connected to Arduino's RX3.

The problem is that when I try to communicate with the module it responds fine but after some AT commands the module starts panicking and start sending random garbage. The code I'm using is a simple Serial to Serial code :

#include<SoftwareSerial.h>

#define mySerial Serial3
//SoftwareSerial mySerial(10, 11);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  mySerial.begin(38400);

}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

Output :

[This is with serial monitor set to 115200 baud rate]

[The garbage values with serial monitor set to 9600 baud rate]

The solutions I have tried so far are :

Put a 220uF cap between SIM800L's VCC and GND. (a 470uF tantalum cap is already included on the module but still to be safe)
Tried various baud rates from 9600 to 115200 (the baud rate setting on the module is set to auto baud rate) but only 38400 works reliably.
Tried to pull the RX3 line up on Arduino with a 100k resistor so that it doesn't float.
Tried to put up to 5s delay between AT commands given to the module but it still goes into panic.

The thing I noticed is that if we enter some wrong command like ATD74xxxxxxxx (which calls a phone number) instead of with proper ending like ATD74xxxxxxxx; the module does the same thing which is spitting garbage values.

Can anybody help me with what is wrong with the module?

I believe GSM modules needs about 2A current for few operations. One of them is calling. Are you providing proer current?


Right way to convert 120VAC to 5V? I am currently using a Particle Photon to control a relay that turns a lamp on and off. I would like to power the Photon and the lamp from the same power cord.

Currently, I have a power cord for the lamp and I am also using a usb cable to power the Photon.

I found this (Enclosed AC DC Converter) and I am wondering if this will work if I split the 120V power cord to go to the relay and the converter. Will I need anything else? Are there any other concerns I should worry about? Do I need to worry about polarity?

Thanks for your help in advance.

I highly recommend reading the datasheets for any electronics because they have an incredible amount of information.

Short Answer, No

If you read the datasheet for the Particle Photon, it recommends no less than a 1A power supply. Unfortunately, the datasheet for the AC/DC Converter you found shows it has a maximum output current of 30mA, which is nearly 30x smaller than you would want for the Photon.

How to Make This Work

Because you're trying to get ~1A @ 5V and you're working with 120VAC, you don't have to reinvent the wheel--or in this case, the USB Charger Brick!

Literally any off-the-shelf USB charging brick for a phone or tablet will work. I can't think of any that are less than 1A-rated anymore, but if you want a hobbyist-level supply, something like this one may be right for you (not to plug for Adafruit, though they are a great learning resource).

Basically, you'll have a box that houses the Photon and the relay. You simply put this in the box with it, and voila! you have 5V power for the Photon.

Bonus Points

You can even go nuts and remove the device from its housing (DISCLAIMER: This may void the UL listing and any warranty) and just grab the innards to package neatly in a nice enclosure.

EDIT:

Easiest Solution
Just install one of these at the receptacle you intend to use.


How to make the motor car move left-forward / left-backward/ right-forward/ right-backward I'm using an Arduino Uno to make a motor car. And I successfully made it move forward / backward / left / right.

void forward(void) {
  analogWrite(EA, 254); //speed 0 - 255
  analogWrite(EB, 255); //speed 0 - 255
  digitalWrite(EN2, LOW);
  digitalWrite(EN3, HIGH);
  digitalWrite(EN4, LOW);
  digitalWrite(EN5, HIGH);
}

void backward(void) {
  analogWrite(EA, 255); //speed 0 - 255
  analogWrite(EB, 255); //speed 0 - 255
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, LOW);
  digitalWrite(EN4, HIGH);
  digitalWrite(EN5, LOW);
}

void left(void) {
  analogWrite(EA, 180); //speed 0 - 255
  analogWrite(EB, 180); //speed 0 - 255
  digitalWrite(EN2, LOW);
  digitalWrite(EN3, HIGH);
  digitalWrite(EN4, HIGH);
  digitalWrite(EN5, LOW);
}

void right(void) {
  analogWrite(EA, 180); //speed 0 - 255
  analogWrite(EB, 180); //speed 0 - 255
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, LOW);
  digitalWrite(EN4, LOW);
  digitalWrite(EN5, HIGH);
}

The problem is, I found it is quite strange if I need to first press left/ right and press forward to turn around. I would like to make 4 extra buttons for left-forward / left-backward/ right-forward/ right-backward. Any ideas to create 4 extra functions for that?

Thanks for helping.

Update: Connection

int EN2 = 14;
int EN3 = 15;
int EN4 = 16;
int EN5 = 17;
int EA = 3;
int EB = 5;

Update: Attempted code and hardware connection

void left_top(void) {
  analogWrite(EA, 128); //speed 0 - 255
  analogWrite(EB, 255); //speed 0 - 255
  digitalWrite(EN2, LOW);
  digitalWrite(EN3, HIGH);
  digitalWrite(EN4, LOW);
  digitalWrite(EN5, HIGH);
}

void right_top(void) {
  analogWrite(EA, 255); //speed 0 - 255
  analogWrite(EB, 128); //speed 0 - 255
  digitalWrite(EN2, LOW);
  digitalWrite(EN3, HIGH);
  digitalWrite(EN4, LOW);
  digitalWrite(EN5, HIGH);
}

void left_down(void) {
  analogWrite(EA, 128); //speed 0 - 255
  analogWrite(EB, 255); //speed 0 - 255
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, LOW);
  digitalWrite(EN4, HIGH);
  digitalWrite(EN5, LOW);
}

void right_down(void) {
  analogWrite(EA, 255); //speed 0 - 255
  analogWrite(EB, 128); //speed 0 - 255
  digitalWrite(EN2, HIGH);
  digitalWrite(EN3, LOW);
  digitalWrite(EN4, HIGH);
  digitalWrite(EN5, LOW);
}

Left top / right top seem not to move at all, and right top / down is just similar to right / left.

And for hardware, I am using

Arduino  AR 293d

For the motor connection, it's like this:

Regarding the pins - I wanted to find out the physical (hardware) connections.

Pending an updated answer I presume the EA and EB will set the speed for two motors and EN2/EN3 and EN4/EN5 control the direction of the motors. If that's the case you could make the car turn sideways but changing the speed of only one of the motors. For example:

void forwardLeft(void) {
  analogWrite(EA,128); //speed 0 - 255
  analogWrite(EB,255); //speed 0 - 255
  digitalWrite(EN2,LOW);
  digitalWrite(EN3,HIGH);
  digitalWrite(EN4,LOW);
  digitalWrite(EN5,HIGH);
}

I assume that EA is the left motor and EB is the right motor. This will make the right one rotate twice as fast as the left one so the car should go forward, but also turn left. If you keep this running the car should end up going in a circle. By making the 128 lower you will change how fast the car is turning.

The other functions should be similar.

Caveat emptor - of course this will mean nothing if the beginning assumptions are incorrect.

EDIT
Can't figure out why it doesn't work without having the thing in my hands. Have not found a schematic for that board, but intuitively it should work as described above.

Things you can do to try to figure out - try different numbers instead of 128, the speed of the motors might not vary linearly with the voltage. What you need to obtain is to have one motor go twice as fast as the other one and in the same direction. That should turn the car around.


trigger a function of a Arduino Uno from signal received by LoRa module I have two sx1278 Lora transceivers where both are connected to two Arduino Uno boards. I want to trigger a function in the Arduino Uno board where receiver side of LoRa connected using the signal received by Lora receiver.

I'm assuming you have read the datasheet for the SX1278.  If not, please refer to it at:
SX1278 Datasheet
On page 69 you will see a couple of tables regarding the functions possible on the digital I/O (i.e. DIO) pins:

I'm not clear what exactly you are looking for or which mode you are operating in (you have provided almost no information about your project) but all the information you might need is available on these DIO pins.
You can connect the appropriate pin or pins to some of the edge sensitive lines on your Arduino and define and enable an INTERRUPT in your code.  So when the event you are waiting for happens, an interrupt will occur, you can go and read the data and do whatever with it.


Smaller version of the Mega I'm currently working on a Arduino Mega (GPS + IMU + SD card logging + BT). I need the Mega for extra memory and serial port.
I would like to transition to something with a smaller form factor now. I need help with suggestions for a smaller form factor board/version of Mega.

Any suggestions?
I can't really find anything.

The only small size yet meeting requirements (in terms of memory) option seems to be a Microduino -
but I'm not whether all the libraries (SDfat etc.) will work on this.

The ATmega1284P provides 128kB of flash, 16kB of SRAM, 4kB of EEPROM, and 2 USARTs in a 40/44/49-pin package. Mighty 1284P provides Arduino support for the '1284P.

There aren't too many actual boards that feature it, but it can be used very easily on a breadboard or custom PCB with a programmer.


Is it possible to make an arbitrary lake bottom generator? I'm trying to generate an arbitrary lake bottom sonar returns using my Arduino.

I would like to seed a function with a "depth." This would be the starting depth. I would then like to randomize a set of parameters each time the function is called. The output would look something like a time-truncated sine wave. The parameters would include:

Randomized Amplitude of waveform (which wouldn't vary too much)
Randomized Period (or frequency) of waveform (also wouldn't vary too much)
Randomized exit point. Say the period is 10 seconds but function ends at 7 seconds. This would allow for a changing in depth over time even if random.
If possible, I would like to low pass filter the output to smooth any hard transitions.

Any suggestions on where to get started?

A common method of generating realistic-ish 3d terrain is as follows:

Start with a square (as seen top-down), described by the lengths of it's side (all the same), and the height of each of the corners.

Divide each edge in half; for example, add a new point halfway between the north-west point and the north-east point; it's altitude will be the average of the altitude of the two existing points, plus or minus a random number.

Now add a point in the center of the existing square; it's altitude being the average of the north, east, west and south points you've just created, plus or minus a random number.

You now have 4 smaller squares. Repeat this process on the four smaller squares, then the smaller squares within that, and so forth.

You might want to manually do the first few points, tweaking it to get the shape you want, then leave the details to the algorithm. Your random number for the adjustments of the "middle point" heights should be proportionate to the length of the sides; for example, the random altitude adjustment might be a random number up to X% the length; then subtract half of X% of the length. Adjusting X% will give you an area that is more or less "pointy".


Connect GPS module (WeeBee) to Arduino Uno This is my very first Arduino project. I want to learn about GPS navigation by exploring the NMEA protocol!

Therefore, I bought a WeeBee GPS module. After reading the datasheet, I have two questions:

The official Arduino website states

  Note: if you are using an Arduino Uno, keep in mind that you can't use the GPS module at the same time as your computer is connected on the USB port.

But I you go to the end of his tutorial, you will see he can transmit the GPS data to his computer. I don't understand why it would not be possible...
The GPS module datasheet (download link here) states that the maximum voltage is 5V. But it also states

  serial connections are 3.3V CMOS Logic Levels

and

  Suitable decoupling must be provided by external decoupling circuitry.

So, does it mean I need a logic level converter to prevent damage to the GPS module?

The article on the Arduino website means that you can't upload sketches from your PC to the Arduino or receive any sort of data, through the serial monitor or otherwise, from your PC, while the GPS module uses the RX pin. Any attempt to send data from PC to Uno in this condition would cause the Arduino to receive only corrupted data, since 2 devices (GPS module and PC) would be trying to send data at the same time, with the same line. This limitation is easily resolved by connecting the GPS module to a SoftwareSerial port instead; this keeps the HardwareSerial port (pins 0 & 1) free for bidirectional PC-Arduino communication.
The datasheet says that the maximum power supply voltage is 5 V. However, the serial connections are 3.3 V logic, so yes, you will need logic level shifters. A simple voltage divider will serve. However, 'external decoupling' refers to circuitry used in decoupling/smoothing out any spikes or dips that may occur in the supply voltage. An untamed spike could damage the device, while a dip (perhaps from large current draw) could cause the device to stop working, if the voltage falls low enough to be considered under-voltage. A 10uF electrolytic capacitor, connected from Vcc to GND close to the GPS module, should be okay.


How to calculate step delay? I'm struggling with get suitable step delay while driving a stepper motor.

How to calculate exact step delay for 1.8deg/step stepper motor?
Give some example calculation.

Convert the RPM of the motor to RPS.
Take reciprocal to get seconds per revolution.
Divide it by 360 to get seconds per degree.
Multiply by 1.8 to get seconds per step.


Keyboard.h not found I keep getting this error message:

"'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?"

... when I have already included Keyboard.h.

#include <Keyboard.h>

void setup() {
  pinMode(3,INPUT_PULLUP);
  pinMode(4,INPUT_PULLUP);

 Serial.begin(9600);    //begin seral comms for debugging
}

void loop() {
  Keyboard.begin();
  if (digitalRead(3) == 0) //if button 3 is pushed
   {
Keyboard.write('z');
delay(200);
}
   else if (digitalRead(4) == 0) //if button 3 is pushed
{
  Keyboard.write('x');
  delay(200);
}
  Keyboard.end();
}

Keyboard.h is already included as a default library in Arduino so I'm not sure what's wrong

If you have Arduino/Genuino Uno selected as your board in the Tools ► Board ► menu, then you get the error. If you select Arduino Leonardo it compiles correctly.

From Can't seem to be able use Keyboard.h library, this post states:

  Keyboard.h (and Mouse.h) only works on devices that use the ATmega32u4 processor, like the Leonardo or Micro.  See: https://www.arduino.cc/en/Reference/MouseKeyboard

This solution might help though

  I had the same problem using Flora

  This worked for me:

  Tools > Boards > Boards Manager
  Install TeeOnArdu (Then select that board from Boards Manager)
  Tools > USB Type > Serial, Keyboard, Mouse < Joypad
  Upload and run code again (might need to restart IDE)


Selecting different arrays using a list of pointers I have different arrays of different sizes, and a list of pointers to the addresses of each array. How do I select each array using the list of pointers, and access it's elements. On Teensy 3.2 board.

int * arr_list[3];
const int arr_sizes[3] = {3,4,5};  // array of the array sizes
const int ar1[3] = {12,2,8};       // arrays of  different sizes
const int ar2[4] = {41,3,6,47};
const int ar3[5] = {9,32,1,5,7};

void map_arrays(){          // list of pointers with the addresses of the
                            // arrays
arr_list[0] = (int*) &ar1;
arr_list[1] = (int*) &ar2;
arr_list[2] = (int*) &ar3;
};

int arr_number = 1;          // select array
int a = arr_sizes[arr_number];    // the size of the selected array
int *b = arr_list[arr_number];
int test = 0;

void setup() {

Serial.begin(57600);  //serial monitor

}

void loop() {

for (int i=0; i<a; i++) {     // for the selected arr_number iterate and
test = b[i];                  // return the index elements

}

Serial.println("size =");
Serial.println(a);
Serial.println();
delay(1000);
Serial.println("index =");
Serial.println(test);
Serial.println();
delay(500);

 }

You have it right, only fix initialization of test variables:

you do not call map_arrays() in setup()
you assign uninitialized arr_list item to b

const int* arr_list[3];
const int arr_sizes[3] = { 3, 4, 5 };  // array of the array sizes
const int ar1[3] = { 12, 2, 8 };       // arrays of  different sizes
const int ar2[4] = { 41, 3, 6, 47 };
const int ar3[5] = { 9, 32, 1, 5, 7 };

void map_arrays() {          // list of pointers with the addresses of the
// arrays
  arr_list[0] = ar1;
  arr_list[1] = ar2;
  arr_list[2] = ar3;
}

int arr_number = 1;          // select array
int a = arr_sizes[arr_number];    // the size of the selected array
const int *b;
int test = 0;

void setup() {

  Serial.begin(57600);  //serial monitor

  map_arrays();

  b = arr_list[arr_number];

  for (int i = 0; i < a; i++) {     // for the selected arr_number iterate and
    test = b[i];                 // return the index elements
    Serial.println(test);
  }

  Serial.println("size =");
  Serial.println(a);
  Serial.println();
  delay(1000);
  Serial.println("index =");
  Serial.println(test);
  Serial.println();
  delay(500);

}

void loop() {
}


4 digit 7 segments display wrong number I'm an Arduino newbie having problems with 4 digit 7 segments display.
I want to display some thousands to 4 digit 7 segments display but it display only 0000.
I want to receive data from serial with string. And display the data to 4 digit 7 segments display... So test make String = '2575'... but it's not work.
What's wrong in my codes?
Any suggestions here will be a great help. thanks

int segments[] = {A0, A1, A2, A3};

byte digits[10][7] =
{
  { 1,1,1,1,1,1,0 }, // 0
  { 0,1,1,0,0,0,0 }, // 1
  { 1,1,0,1,1,0,1 }, // 2
  { 1,1,1,1,0,0,1 }, // 3
  { 0,1,1,0,0,1,1 }, // 4
  { 1,0,1,1,0,1,1 }, // 5
  { 1,0,1,1,1,1,1 }, // 6
  { 1,1,1,0,0,0,0 }, // 7
  { 1,1,1,1,1,1,1 }, // 8
  { 1,1,1,0,0,1,1 }  // 9
};

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

  for(int i=2;i<10; i++) {
    pinMode(i, OUTPUT);
  }

  for(int i=0; i<4; i++) {
    pinMode(segments[i], OUTPUT);
  }
}

void loop() {
  String IncomingData = "2575";

  for(int i=0; i<4; i++) {
    digitalWrite(segments[i], LOW);
    int digit = atoi(IncomingData[i]);
    displayDigit(digit);
    delay(5);
    digitalWrite(segments[i], HIGH);
  }
}

void displayDigit(int num){
  int pin = 2;
  for(int i=0;i<7;i++){
    digitalWrite(pin+i, digits[num][i]);
  }
}

You call atoi() with a char. Parameter of atoi is const char*. To convert ASCII code of digit to the digit use

int digit = IncomingData[i] - '0'


FastLed LED Strip Output Checksum I am wondering if anyone has ever connected the output of their LED strip back to the Arduino to read and make sure the strip is functioning correctly, kinda like checksum functionality.

I am using the FastLed library and it doesn't appear that this has been done.

The reason why I want to do this is because when an LED breaks on the strip, it causes all of the following LEDs to flicker wildly. I need to be able to shut the LED strip off immediately if it starts flickering because my device is being used as a visual therapy aid in a school.

I am using an Arduino Due with WS2812B LED strip.

Look at timing on sheet 4 of the datasheet, and the times on sheet 3

A Low bit is 400 +/- 150nS wide Low followed by a 800 +/- 150nS wide High

A High bit is 850 +/- 150nS wide High follow by a 450nS wide Low.

To do what you suggest with a checksum, you'd have to send the checksum (minimum of 3 bytes to fake the data for an extra WS2812B for example) first, and see if the 24 bits were received correctly while at the same time the last 3 bytes were being sent out.

A Due might be fast enough to do that. I don't think a 16 MHz Arduino could.

Checking power level is not really feasible, as many strips get power attached to the beginning, middle, and end of a strip to ensure uniform brightness and to keep the strip's power traces from overheating from excess current flow.


Can someone help me with my arduino and relay and switch? This is my code. What i want to do is activate the relay when switchInNcPin is activate. I am using a switch (micro switch). It has COM NC and NO pins. Can you tell me what is wrong with my code?
PROBLEM:
The relay keeps clicking ON and OFF even though it is meant to wait 5000ms, activate, wait 3000ms, deactivate only once. Can you look at my code and help me?

Maybe it's not the only problem, but at least:

int val = ...

and

if (val == "FLUSH")

do not match.

I assume you mean a digit here (0 or 9 to flush)?

Also, you should put your circuit in your question. A reason because of the 'flipping' is that your switch is not pulled down, and it results in undefined behavior.

Another thing you could add is debouncing, when a switch is clicked, it results in multiple 0/1 and 1/0 transitions (although your delay might help too).


Quadrature Encoder:Interrupts: Reset Count I'm working on a quadrature encoder(with a 500ppr codewheel) with a Channel A, B and an Index pulse output.  Using an Arduino Mega I'm counting the number of pulses on Channel A on the rising edge. The code for counting pulses on channel A using an interrupt is straight forward enough with plenty of sources and examples out there to work with.

I've used the the code below to the count the pulses(in an increasing manner). What I'm trying to figure out is how I can reset the overall count using a second interrupt. The second interrupt is invoked when the Index channel pulses high.So in another words when the index channel pulses to indicate a full rotation on the code wheel the main count will reset to zero

#define CHA 2
#define CHB 3
#define CHI 19

volatile int count = 0;
volatile byte INTFLAG1 = 0;

void setup()
{
  pinMode(CHA, INPUT);
  pinMode(CHB, INPUT);
  pinMode(CHI,INPUT);

  Serial.begin(9600);
  Serial.println(count);

  attachInterrupt(0, flag, RISING);

 }

void loop()
   {

       if (INTFLAG1)
             {
               Serial.println(count);
               INTFLAG1 = 0; // clear flag
             }

    }

void flag()
    {
       INTFLAG1 = 1;
       if (digitalRead(CHA) && !digitalRead(CHB))
               {
                count++ ;
               }
     }

Is it possible to implement the reset of the main pulse count with a second interrupt as described?

From what I've read interrupts work at the same level of priority- so I'm thinking there might be a problem here to implement this approach as the interrupts would have to be nested

Any help is appreciated if anyone has done anything like this using interrupts or can point me in  the right direction.

Is it possible to implement the reset of the main pulse count with a
  second interrupt as described?

Yes, and it's quite straightforward. Your index signal goes to pin 19,
which is interrupt 4 on the Mega, so you can simply

attachInterrupt(4, reset, RISING);

in setup(), where reset() is a function that resets the counter:

void reset()
{
    count = 0;
}

  I'm thinking there might be a problem here to implement this approach
  as the interrupts would have to be nested

In general you do not want to nest interrupts. If an interrupt is being
serviced when a second interrupt fires, the second one will just wait
for the first one to finish. This approach works fine as long as you do
not have interrupt handlers that take too long to execute.


ESP8266 Webserver ESP8266WebServer move Handler-Function in separate .h .c file The plan is to create a bigger project and to split the ESP8266 webserver-code over several modules (.h .c files). The main problem is that the ESP8266WebServer server is not declared in the index.h and index.c files.

What I've been trying to do:

Content main.c

#include <ESP8266WiFi.h>
#include "ESP8266WebServer.h"
#include "index.h"

ESP8266WebServer server(80);
const char* ssid =     "test";
const char* password = "12345678";

void setup()
{
  WiFi.softAP(ssid, password);
  server.on("/", handleRoot(server));           // <-- use of deleted function 'esp8266webserver::ESP8266WebServerTemplate<WiFiServer>::ESP8266WebServerTemplate(const esp8266webserver::ESP8266WebServerTemplate<WiFiServer>&)'
  server.begin();
}

void loop()
{
  server1.handleClient();
}

Content index.h:

void handleRoot(ESP8266WebServer server);

const char htmlIndex[] PROGMEM = R"=====(

    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Test</title>

Hello World!

)=====";

Content index.c:

#include "webpages/index.h"

void handleRoot(ESP8266WebServer server)
{
  Serial.println("GET /");
  server.send(200, "text/html", htmlIndex);
}

How can I use the ESP8266WebServer server created in the main.c in index.c?

Move the webserver to index.c and include the webserver type:

ESP8266WebServer server(80);

Add an external reference in index.h and include it:

#include "ESP8266WebServer.h"

extern ESP8266WebServer server;

Index.h is included by both main.c and index.c so it will know about server being an ESP8266WebServer type, but does not allocate memory for it; that is done in index.c

This is called a forward reference.


What is the best way to assign pins to an LED Cube? I have made an LED cube that is a 3x3x3 design and was wondering if there is way to make a function in the Arduino IDE where each the layers of LEDs can be represented by a list with 1 being on and 0 being off:
{1, 0, 1, 0, 1, 0, 0, 1, 0} with the first number of the list being the first column, then the second column, etc. and the same for the rows which would be something like {0, 1, 0}. Does this make sense? If so, is there an idea for a function that could take these inputs and transform them into digitalWrite outputs? I am using an Arduino Nano for this, with pins 2, 3, 4, 5, 6, 7, 8, 9, and 11 used for the columns with A0, A1, and A2 being the rows of the cube.

Well, learning bit manipulations and using three uint16_t (as 9 bits won't fit into uint8_t) to store state for a whole cube is much better. Then you hust have to setup timer ISR and each time it fires just display one "floor". The multiplexing can be done even in loop, but it's usualy flickering as you can't do almost perfect timing as in the ISR.

And for example, I was using two 2x4x4 segments to build up 4x4x4 cube and single MAX7219 to drive it, so I don't have to handle whole multiplexing and so.

My another aproach was using individually addressable LEDs like WS2812B, so I needed only one pin to drive it all. Or by using ARM and DMA transfers, I could drive 8 or 16 lines simultaneously.


Serial monitor showing extra data I am trying to communicate NODEMCU and Arduino Uno using Serial Communication (RX,TX) using SoftwareSerial library.

Here is my code

int count;
char reqst[] = " ";

void setup() {

  Serial.begin(115200);
  Serial.println("Ready");

}

void loop() {

 while ( Serial.available() > 0 )  {

  char inChar = Serial.read();
  reqst[count] = inChar;
  count++;

     if (inChar == '\n') {

        Serial.print("String: ");
        Serial.println(reqst);
        count = 0;
        delay(1000);

     }

 }

}

here my output in serial monitor is showing ;

String: aj
779

String: am
779

I have checked that from NODEMCU i am sending correct string but in Arduino Uno
the number "779" is coming from nowhere.

So my problem is i am not be able to execute my function according to the desired string. Can anyone tell why the number is coming below the string ?.

char reqst[] = " ";

Here you created an array two chars in length. But one of those characters must be used for the null terminator so actually it can only hold a string that's a single character long. If you write past the end of the array that will cause undefined behavior. This is likely to be the cause of the strange results you encountered. You need to size reqst[] large enough to contain any string you may receive, including the null terminator. You should add code to ensure that you never write off the end of the array and that it will always end in a null terminator.

I realize it may only be a simplified minimal example, but in the code you posted there is no need to store the incoming characters. Instead you could just print them as they are received.


Adding a steering servo I got a Sparkfun Redbot Kit a while back. I ended up building it vanilla and it was a good introduction to the board (the board is basically Uno and a motor shield in one) and the toys that came with it. I figured if could scavenge an RC car, I'd get a more robust redbot. I found an old RC Rock Crawler, it has a basic suspension, two motors, and a steering servo.
Unfortunately, I encountered a problem. The steering servo only has two wires. I loaded the Servo -> Sweep example that is default in the Arduino IDE to see if I could make it work regardless. I tried all the different all the different wire/header combinations on the servo headers:

When I attach the wires to gnd and # I get a buzzing noise.
When I attach the wires to gnd and pow the servo turns left or, if I swap the wires, it turns right.
When I attach the wires to pow and # nothing happens.

I currently can't take advantage of the servo headers on the board (or at least I don't know how to). I was hoping that I could that there might be a work around, I just don't know what it is.
The obvious answer is that I could run both motors off of only one of the headers and use the other to control the steering (thats how the original board from the car was wired), but I can get a faster car if each motor has its own header, and I'm all about the vroom vroom...

I'm running the whole thing off the default 6v (4 AA) battery pack. I might be able to wire in the extra 2 AA's for the extra 3v but I don't want mess with the wiring on the pack unless I know it's going to work.

I have an accelerometer connected to the A4 A5 header block and the motors connected too (I checked w/o them connected but there was no difference).

Image courtesy of https://learn.sparkfun.com/tutorials/getting-started-with-the-redbot
More info on the redbot board https://www.sparkfun.com/products/12097

If the motor you are using has only two wires, and as you described it's response to the direct connection to the power, it can't be a servo. The motor is a normal dc motor.
If you want to control the amount of the turns on your rc car you should try to play with the pwm signal, I don't know if it will work or not but at least you will have tried. And remember not to connect the motor directly on the micro's pin if there no motor pins on your red board.


Extracting a substring from original string I am trying to extract a substring out of another string, but it doesn't seem to be working. I am new to programming in arduino and c++ in general. Here is my code:

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

char rfid;

void loop()
{
  while (Serial.available() > 0)
  {
    rfid = Serial.read();
    String cardnum(rfid);
    cardnum.replace("", "");
    cardnum.replace("", "");
    String id = cardnum.substring(0,2);
    Serial.print(id);
  }
}

The first argument in cardnum.replace("", ""); and cardnum.replace("", ""); replaces the start and end bit with nothing, but it somehow doesn't display it correctly here.
Now on to the problem at hand. The output for cardnum is 1F006B471F2C which it should be, but the ouput for id is the same, when i want it to be only the first two characters of cardnum. How would i go about achieving that.
Thanks in advance for any answers you can provide.

Let's dissect your program a moment and see why it's not doing what you want:

while (Serial.available() > 0)
{

So while there are characters available to read in the serial buffer

  rfid = Serial.read();

read one character into the rfid variable.

  String cardnum(rfid);

Convert that character into a string.

  cardnum.replace("", "");

Replace nothing ("") with nothing ("")

  cardnum.replace("", "");

Do the same again,

  String id = cardnum.substring(0,2);

Take the first two characters of the string that contains the single character that you have read.

  Serial.print(id);

Print it.

So basically you have read one character, made it into a string, done nothing to it, copied it to another string, then printed it.

Instead of this method, which does nothing useful, you should read the whole ID into a string (I'd use a C string [i.e., char array] rather than an Arduino String object) then perform operations on that string once you have read the whole ID code.

There's many methods of doing that, but how you do it is heavily influenced by exactly how the data is presented to you. Does it have a terminating CR or LF to indicate the end of the string? If not you will have to use some form of timeout to determine when the string has been completer.


use Nodemcu to program Attiny85 I have a dev board for my attiny85.
when connecting it to the computer I get "unknown USB device(device descriptor request failed)"
although I have the needed drivers, so I thought of trying using my nodemcu.
Tried connecting the SPI (to the nodemcu hmiso;hmosi;hcslk;hcs)and upload using "arduino as ISP" and compitable settings(https://www.hackster.io/arjun/programming-attiny85-with-arduino-uno-afb829).
pressing "burn bootloadre" using this way gives me errors:
"avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
......
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x03
Error while burning bootloader."
***EDIT:
After changing a line(#define USE_OLD_STYLE_WIRING) in ArduinoISP (from example)
the error code changed a bit and it shows up much faster:
"Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "ATtiny25/45/85, ATtiny85, Internal 8 MHz"
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x04
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x61
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x67
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xc1
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xc4
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xc5
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xa1
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xcc
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe2
Error while burning bootloader."
Any help on how to use nodemcu to program attiny85 will be great
thanks

Modifications to the ArduinoISP.ino sketch
I made the following changes to the ArduinoISP.ino file it exists in IDE version 1.8.13, and uploaded it to the NodeMCU board.
In short, I commented out (by way of #if 0) the heartbeat, err, etc LED related stuff.  Not doing this causes the board to reset for reasons that would probably be apparent if I researched it, but I haven't and since I don't plan on using the LEDs and that you may not, I figured I would get this to you sooner.
I changed RESET to be SS which on NodeMCU is D8.
Why LED related code causes resets
... Out of curiosity I just went and looked at the ESP-12F and ESP8266EX datasheets.  GPIO7, GPIO8, GPIO9 all go to the ESP-12F's SPI flash (program storage), so ostensibly monkeying with them interferes with the modules ability to keep executing from the SPI flash.  They're not routed to NodeMCU pins, probably for that reason.  So there's the answer to that.
Differences
@@ -70,7 +70,7 @@
 // The standard pin configuration.
 #ifndef ARDUINO_HOODLOADER2

-#define RESET     10 // Use pin 10 to reset the target rather than SS
+#define RESET     SS // Use pin 10 to reset the target rather than SS
 #define LED_HB    9
 #define LED_ERR   8
 #define LED_PMODE 7
@@ -216,15 +216,17 @@

 #endif

 void setup() {

   SERIAL.begin(BAUDRATE);

+#if 0
   pinMode(LED_PMODE, OUTPUT);
   pulse(LED_PMODE, 2);
   pinMode(LED_ERR, OUTPUT);
   pulse(LED_ERR, 2);
   pinMode(LED_HB, OUTPUT);
   pulse(LED_HB, 2);
+#endif

 }

@@ -276,6 +278,7 @@
 }

 void loop(void) {
+#if 0
   // is pmode active?
   if (pmode) {
     digitalWrite(LED_PMODE, HIGH);
@@ -291,6 +294,7 @@

   // light the heartbeat LED
   heartbeat();
+#endif
   if (SERIAL.available()) {
     avrisp();
   }

NodeMCU to ATTiny85 ISP Wiring
The board is wired to the ATTiny85 as follows:
NODEMCU 3.3V -> ATTINY85 PIN 8
NODEMCU GND  -> ATTINY85 PIN 4
NODEMCU D5   -> ATTINY85 PIN 7
NODEMCU D6   -> ATTINY85 PIN 6
NODEMCU D7   -> ATTINY85 PIN 5
NODEMCU D8   -> ATTINY85 PIN 1

On the NodeMCU you'll find all 6 of these together on the right.
Verifying AVRDUDE functioning
avrdude -P /dev/ttyUSB0 -c stk500v1 -b 19200 -p attiny85

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

avrdude: Device signature = 0x1e930b (probably t85)

avrdude: safemode: Fuses OK (E:FF, H:DF, L:71)

avrdude done.  Thank you.

I've been playing with this chip, so don't be surprised that I don't have the same fuse values you have.


Programming an ATMEGA2560 using FTDI I want to know how exactly do I program (upload arduino sketches) an ATMEGA2560 which is boot loaded with an Arduino Bootloader using a FTDI programmer and an Arduino IDE, is there any capacitors/resistors required?

If you have a bootloader, you just need to connect up four wires from the FTDI cable:

Pin 1 (black) -> Ground
Pin 2 (CTS)   -> not connected
Pin 3 (Vcc)   -> 5V
Pin 4 (TxD)   -> Rx (Mega pin D0)
Pin 5 (RxD) -> Tx (Mega pin D1)
Pin 6 (green) -> not connected

This will not auto-reset, so you will have to press (and release) the Reset button on the board at the moment that the sketch starts to upload.

  How to make it auto reset?

What you should be able to do is connect RTS to Reset on the board, using a 0.1 µF capacitor (in series). I found in practice that this did not bring Reset low enough to trigger it - I'm not sure why, except maybe the board has a stronger pull-up resistor on /RESET than expected. That technique works for me on breadboard Arduinos.

Since it didn't work for me, I did not put it in my original answer. You could try that, and if it works, well and good.


Digital Potentiometer not fading LED So I am trying to test what will eventually be a Arduino controlling 3 110V motors that are currently controlled by an analog pot. But more on that later.

I am trying to test out using a digital pot (never have before) and am running into some issues with tutorials I have found online. For now, I want to control a LED with the digital pot (Spec Sheet) so that the LED fades in and fades out in a continuos loop.

Here is the tutorial I followed. It uses a different chip model but it seems from the pot I am using that the pins are the same. (I could be wrong?)

I double and triple checked the wiring and it matches below.

Here is the code I am running (slightly modified from the tutorial, also tried the tutorial code)

#include <SPI.h>
byte address = 0x11;
int CS= 10;
int i=0;

void setup()
{
  pinMode (CS, OUTPUT);
  SPI.begin();
}

void loop()
{
    for (i = 0; i <= 128; i++)
    {
      digitalPotWrite(i);
      delay(10);
    }
    delay(500);
    for (i = 128; i >= 0; i--)
    {
      digitalPotWrite(i);
      delay(10);
    }
}

int digitalPotWrite(int value)
{
  digitalWrite(CS, LOW);
  SPI.transfer(address);
  SPI.transfer(value);
  digitalWrite(CS, HIGH);
}

As a result of the two above, I have an LED that stays lit (at about 50% it seems) and does not fade in/out at all.

Being relatively new to wiring and EE in general, is there a better way to replicate an analog pot without using a digital pot? Can I just use PWM to control it? Why would the LED be just staying lit?

Thanks!

After studying the datasheet differences between MCP41100 (digital pot used in the tutorial) and MCP4131 (the one you get), I found two major differences between both:

Difference in resolution:

MCP41100 has 257 steps resolution (8 bits + 1): you can see that at the beginning of its datasheet
MCP4131 has only 129 steps resolution (7 bits + 1): you can get this information on page 2 of its datasheet

Difference in commands formats sent through SPI; both use one "command byte" followed by a "data byte", but have a diffrent format for their command byte:

MCP41100 command byte is X X C1 C0 X X P1 P0 where X is unused, C1 C0 is one of 4 possible commands,  only 2 being valid commands actually: 01 (Write data), 10 (Shutdown), finally P1 P0 should be always 01 for an MCP41100
MCP4131 command byte is AD3 AD2 AD1 AD0 C1 C0 D9 D8, where AD3-AD0 is the address of the "register" on which to perfom a command. For the MCP4131, the most important address is 00 which means "volatile wiper 0" (this is what allows you to change the resistance value of the pot), C1 C0 is one of 4 possible commands (read data, write data, increment, decrement), in your example the command should be 00 (write data); finally D9 D8 are the high order bits of the value to write to the register, but D9 is unused and should always be 0. For 257-steps pots, D8is used to have the full resistance scale, otherwise it should be 0

Now that we know aht your MCP4131 expects as commands passed through SPI, we can take a look at what the tutorial program passes:

00010001 value

The first byte can be broken down as such:

0001 address of the pot wiper register 1 (not 0): this wiper does not exist on MCP4131 hecne writing to it will have no impact...
00 command bits meaning "Write to register specified in previous address"
01 high order bits (D9-D8) of the value to write to the wiper register.

Although I don't have an MCP4131 at hand, I think you should adapt the program as follows:

byte address = 0x00;

And that should be fine! Indeed, now your program passes:

00000000 value

Which means "write value (between 0 and 128 which matches exactly the 129 steps resolution) to the wiper register 0 of the port".

Note that the MCP4131 has more features than the MCP41100 in terms of commands, for instance you could use the special commands "increment" and "decrement", with the advantage they need only one byte (the command byte), e.g.

void loop()
{
    for (i = 0; i <= 128; i++)
    {
      digitalPotIncrement();
      delay(10);
    }
    delay(500);
    for (i = 128; i >= 0; i--)
    {
      digitalPotDecrement();
      delay(10);
    }
}

void digitalPotIncrement()
{
  digitalWrite(CS, LOW);
  SPI.transfer(0x04);
  digitalWrite(CS, HIGH);
}

void digitalPotDecrement()
{
  digitalWrite(CS, LOW);
  SPI.transfer(0x08);
  digitalWrite(CS, HIGH);
}


Will Arduino Pro Mini 3.3V run at half the speed of 5V version? Provided a very simple sketch like this:

void loop() {
  digitalWrite(1, !digitalRead(1));
}

... should I expect 5V Arduino to run twice as fast as 3.3V, or are there some internal adjustments in place?

Specifically, I'm wondering about Pro Mini and/or Nano boards. The "speed" here is simply the frequency measured on pin 1.

edit:

To clarify, I'm wondering if there might be some behind-the-scenes frequency divider that makes sure Arduino code always run at the same physical speed, even if the actual MCUs run on different clocks.

Possibly the simplest way of forming this same question: Can the sketch above be used to identify 3.3V Pro Mini boards from 5V versions, with the help of a frequency meter?

If the board is running at half the speed (8MHz instead of 16MHz) then everything that isn't based on real time (i.e., millis(), delay() etc) will run at half the speed. It will all take twice as long to do everything.


Arduino/Genuino 101 5 volts pin Still trying to understand the nomenclature of the pins, I am confused of what's the function of the +5V pin, as I read that the 101 should not operate at that tension.

What's it for?

In Genuino 5V pin is a DC regulated pin. That means when you supply Power (9 to 12 V) to Vin or through the DC Jack, a 5V voltage regulator regulates to give constant output at 5 V. The purpose of that pin is to provide 5V output for other use- as a power supply to some sensor you are interfacing or anything.

However, you can power up the Genuino 101 via the 5V pin. But that is not advisable because in that case it will bypass the regulator present in the board and can damage the circuit if improperly regulated.


Multiple connections on the same pin I want to connect an arduino uno both to a TGAM module: http://www.seeedstudio.com/document/pdf/TGAM%20Datasheet.pdf
and a bluetooth shield. The arduino is to receive data from the TGAM module and sent it to an android device. The problem is I should connect the bluetooth and the TGAM to the same pins on the arduino. Is that a problem (I am still a novice, doing my research)? If it is a problem what is the work around?

Arduino <> TGAM

Arduino RX (0) <> TGAM T (TX)

Arduino TX (1) <> TGAM R (RX)

Arduino 3.3V <> TGAM + (VCC)

Arduino GND <> TGAM - (GND)

Arduino <> HC-06

3.3v    <> VCC

GND     <> GND

TXD     <> RXD

RXD     <> TXD

No, you cannot use one pin (or set of pins) for two functions like that.

To communicate with two serial devices you will need two serial ports. It's possible to (just about) emulate one in software using the SoftwareSerial library. It's not wonderful though - personally I would use a chip that has multiple UARTs in it.


Power consumption in Arithmetic Operation in Arduino UNO I would like to know how much current is consumed by multiplication operation in Arduino (ATMega328P) microcontroller. As per ATMega328p datasheet, multiplication operation takes 2 cycles. I have to now convert it to current.

Please let me know how to calculate it. Attached is ATMega328p datasheet for frequency versus current graph.

The power consumed by the chip won't change much by multiplying (compared to, say, adding). The chip is always fetching and executing instructions, unless you have put it into one of its sleep modes.

The only power consumption change would be if the instruction had a side-effect on a peripheral. For example, turning on the ADC unit (for analog reading), or by setting an output pin high or low.

Having said that, I set up a couple of tests and measured the power consumption. I didn't use a Uno because the power used by the "power on" LED and the voltage regulator tend to swamp the power consumption of the chip itself. However it was tested on an Atmega328P.

Addition

Test sketch

volatile int foo = 100;
int main (void)
  {
  DDRB = 0b00111111;  // all ports to output
  DDRC = 0b00111111;
  DDRD = 0b11111111;
  PORTB = 0;          // write LOW
  PORTC = 0;
  PORTD = 0;

  while (true)
    foo += 42;
  }

Generated code

  a6:   80 91 00 01     lds r24, 0x0100
  aa:   90 91 01 01     lds r25, 0x0101
  ae:   8a 96           adiw    r24, 0x2a   ; 42
  b0:   90 93 01 01     sts 0x0101, r25
  b4:   80 93 00 01     sts 0x0100, r24
  b8:   f6 cf           rjmp    .-20        ; 0xa6 <main+0x10>

Measured consumption

I measured an average of 7.00 mA.

Multiplication

Test sketch

volatile int foo = 100;
int main (void)
  {
  DDRB = 0b00111111;  // all ports to output
  DDRC = 0b00111111;
  DDRD = 0b11111111;
  PORTB = 0;          // write LOW
  PORTC = 0;
  PORTD = 0;

  while (true)
    foo *= 42;
  }

Generated code

  a6:   4a e2           ldi r20, 0x2A   ; 42
  a8:   20 91 00 01     lds r18, 0x0100
  ac:   30 91 01 01     lds r19, 0x0101
  b0:   42 9f           mul r20, r18
  b2:   c0 01           movw    r24, r0
  b4:   43 9f           mul r20, r19
  b6:   90 0d           add r25, r0
  b8:   11 24           eor r1, r1
  ba:   90 93 01 01     sts 0x0101, r25
  be:   80 93 00 01     sts 0x0100, r24
  c2:   f2 cf           rjmp    .-28        ; 0xa8 <main+0x12>

Measured consumption

I measured an average of 6.32 mA.

Conclusion

I found this rather surprising, that it used less power doing a multiplication compared to an addition. Setting all ports to output and low was intended to remove any side-effects from spurious inputs on the input ports.

Still, as you can see from the generated code, most of the instructions are "helper" instructions (like loading from registers, storing to registers, looping etc.).

I'm still not sure I believe the results, perhaps someone else would like to try to reproduce them?

Update

As Edgar Bonet pointed out, the multiplication test became zero after 14 iterations and thus it gave the processor the simpler task of multiplying by zero. I changed the multiplier to 41 which does not become zero. This time the average consumption was 7.34 mA which was higher than the addition test.


Can I power a Wemos D1 R2 via the VIN and GND pins? Can I power a Wemos D1 R2 via the VIN and GND pins?
If so, at what voltage?

Wemos D1 R2 has on-board regulator with input from power jack and Vin pin. The regulator is for 9 to 24 V.


What sensor would I use to get the speed or velocity of my Arduino based nav system? I'm building a Arduino Nano based underwater navigation system using an IMU and various sensors. The only problem with this is that I cannot get the speed or velocity(at least reliably) and it would help the accuracy of my navigation system immensely if I had accurate speed to go off of.

Does anyone have any ideas on how I could measure the speed of my Arduino underwater? I've seen some people recommend paddle wheel like sensors but this needs to be accurate for slow movement.

On small recreational sailboats there is a small propeller on the bottom, when it turns it dials a speedometer, the faster it turns the faster the ship goes, a similar setup should be possible. With a small propeller and 2 ball bearings and an optocoupler, (same principle you got in the scroll button on your mouse, you should be able to pull it off with minimal resistance since there is no physical parts.


How to show the distance in decimal use sensor TF-Luna Lidar or more specific value I want to ask about TF-Lunar Lidar, I've written code to know the distance in cm by reading the array data, right now I need some help about how to read the data so it can be showing the more specific value (float or in decimal)
Or do you guys know what is the speed of the waves transmitted and captured by the lidar sensor, so that I can calculate it in a more specific form, such as using the method of calculating the distance on the Hc-srf04 sensor
I also have used this format to read the distance in mm, but It never works (image about array data)

so if i inputting the duration of the light travel from trigger to echo, i can find the distance?. will it work?

That's the basic working principle, but you cannot do that with an Arduino. Light is too fast, resulting in incredibly small travel times. You need specialized hardware for that. And thats, what a Lidar sensor (or other Time Of Flight sensor) are.

The TF-Lunar Lidar sensor supports different output formats. The distance in cm is just the default. There is also the format, that you showed in your question (9 byte mm), which gives you the distance in mm. The manual of the TF-Lunar also explains how to change the used output format (look at page 22: "5.Output format setting ID_OUTPUT_FORMAT=0x05"). How exactly this is done depends on your actual code and the used communication interface (Serial or I2C).


Assigning formatted value to variable Look at this snippet of code (from TinyGPS++ library):

Serial.print(gps.location.lat(), 6);

It prints the latitude location with 6 decimal points.
I want, instead of printing that value, to have it assigned to a variable.

But i want it assigned just like above, with six decimal points. Is there a way to do this?

Merely expanding on what ConnorWolf has said (which I saw yesterday), look at the link he gave you, it gives you a run down on the command you're after.

  The dtostrf() function returns the pointer to the converted string s.

  char* dtostrf ( double          __val,
                signed char     __width,
                unsigned char   __prec,
                char *          __s
  )
  The dtostrf() function converts the double value passed in val into an ASCII representationthat will be stored under s. The caller is responsible for providing sufficient storage in s.

  Conversion is done in the format "[-]d.ddd". The minimum field width of the output string (including the '.' and the possible sign for negative values) is given in width, and prec determines the number of digits after the decimal sign. width is signed value, negative for left adjustment.

From that, I wrote a short sketch that divides millis() by 1000 and saves this in a float, we then use this float as a source for dtostrf() to do it's work and store the result in a char array.

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

void loop(){
  char c[12];
  float f = millis()/1000.0;
  dtostrf(f,11,3,c);
  Serial.println(c);
  delay(111);
}

I have picked arbitrary values, you're going to have to do the calculations on the size of the array to create (don't forget the leading negative sign, the digits before the decimal, the decimal and your precision digits as well as the null terminator!


Proximity sensor without proximity sensor; is my hand magic, my competency crap, or my arduino fried? here is a very simple circuit, with a LED between pin 2 and ground, and a loose wire in pin 8.

Here is the sketch that was intended for use with a small 4-contact switch like these in every arduino starter kit :

int yellowCIn = 8;
int yellowCOut = 2;

void setup() {
  pinMode(yellowCIn, INPUT);
  pinMode(yellowCOut, OUTPUT);
}

void loop() {
  if (digitalRead(yellowCIn) == HIGH) {
  digitalWrite(yellowCOut, HIGH);
  }
  else {
    digitalWrite(yellowCOut, LOW);
  }
}

However, simply moving my hand near the loose white wire is enough to light the LED, moving it away to put it off. As I am writing this, with the arduino connected by usb, rather than on the blue battery visible in the picture, I notice moving my hands away from the keyboard lights the led, moving them close to the keyboard powers it off...

So back to my title : are my hands magic, my electronics competency crap (well, it is, for sure) enough that I never heard of such a tremendous static electricity effect (and never fried one of the many computers I built from parts), or does this board have dire problems?

Thanks for your attention :)

Nothing's broken; you have discovered  the nature of a floating pin.  Unfortunately, that means that strange things happen...

A very small charge from your hand is triggering the logic because the state of the pin (high or low) is not set.  To fix this, you need to add a pull-up or pull-down resistor (or activate the internal input-pullup resistor).

You can read about how to accomplish this here.


4052 interfacaing with arduino uno I am trying to interface 4052 demux with arduino, but my program is not working as high is not displayed on serial monitor corresponding to select lines.

//output coming from demux pins
int sensorValue0=A0;
int sensorValue1=A1;
int sensorValue2=A2;
int sensorValue3=A3;

void setup() {
  Serial.begin(9600);
  Serial.println("start");
  //select pins connected A,B connected to 2 and 3
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
}

void loop() {
  digitalWrite(2,LOW);
  digitalWrite(3,LOW);
  analogRead(sensorValue0);
  //Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  int voltage0= sensorValue0 * (5.0 / 1023.0);
  Serial.println("volatge0");
  Serial.println(voltage0);
}

You are ignoring the value read by analogRead().  You are then using the value A0 (14) in your sum to calculate the voltage.

Instead:

int adcReading = analogRead(sensorValue0);
int voltage0 = adcReading * (5.0 / 1023.0);

Although I think what you really meant to write was, in total:

int sensorPin = A0;
int sensorValue0;//output coming from demux pins
int sensorValue1;
int sensorValue2;
int sensorValue3;

void setup() {
Serial.begin(9600);
  Serial.println("start");
  pinMode(2,OUTPUT);//selecr pins connected A,B connected to 2 and 3
  pinMode(3,OUTPUT);
}

void loop() {
  digitalWrite(2,LOW);
  digitalWrite(3,LOW);
  sensorValue0 = analogRead(sensorPin);
  float voltage0 = sensorValue0 * (5.0 / 1023.0);//Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  Serial.print("voltage0 = ");
  Serial.println(voltage0);
}

Note that the value sensorPin is where you read the voltage from, and sensorValue0 is where you store that reading. Also note the use of a float type to store the calculated voltage, since an int will give you only values of 0, 1, 2, 3, 4 or 5 in this situation (so, pretty meaningless really).


Need help with understanding the CapacitiveSensor circuit diagram Hey guys I need help with understanding the circuit diagram from this link: https://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense

As of now, this is the schematic I drew from what I understand:

I know it is wrong since they make use of 2 capacitors, but I do not know where should the other capacitor be connected to.

The other capacitor shown in the article is the ambient capacitance (that is, the capacitance between the pin and the things around it). There is no actual capacitor.

What it is saying is that there is a RC circuit (the supplied resistor and the capacitance in the air) which will change the charging time of the RC circuit as the capacitance changes, when you move your hand near it.

From a comment:

  and the other capacitor with a value of 20-400pF

Yes, it does say that:

  Adding small capacitor (20 - 400 pF) in parallel with the body capacitance, is highly desirable too, as it stabilizes the sensed readings.

However that doesn't make any sense to me. How do you add a capacitor in parallel with your body? Do you carry one around with really long wires? And how do you hold it? I would ignore that part.


If and while statements not working The second and third "while and "if" are not working but first "While" and "if" does work.. Am I doing something wrong?
#include <DFMiniMp3.h>

int sw1 = 3;
int sw2 = 4;
int sw3 = 5;

class Mp3Notify
{
  public:
    static void OnError(uint16_t errorCode)
    {
      // see DfMp3_Error for code meaning
      Serial.println();
      Serial.print("Com Error ");
      Serial.println(errorCode);
    }

    static void OnPlayFinished(uint16_t globalTrack)
    {
      Serial.println();
      Serial.print("Play finished for #");
      Serial.println(globalTrack);
    }

    static void OnCardOnline(uint16_t code)
    {
      Serial.println();
      Serial.print("Card online ");
      Serial.println(code);
    }

    static void OnCardInserted(uint16_t code)
    {
      Serial.println();
      Serial.print("Card inserted ");
      Serial.println(code);
    }

    static void OnCardRemoved(uint16_t code)
    {
      Serial.println();
      Serial.print("Card removed ");
      Serial.println(code);
    }
};
DFMiniMp3<HardwareSerial, Mp3Notify> mp3(Serial); //Create the UART connection to the module

void setup()
{

  //3 push buttons with pullups
  pinMode(sw1, INPUT); //Define each button as input with pullup
  pinMode(sw2, INPUT);
  pinMode(sw3, INPUT);

  digitalWrite (sw1, HIGH); //12 Votls supply set to off state
  digitalWrite (sw2, HIGH); //5 Votls supply set to off state
  digitalWrite (sw3, HIGH); //3 Votls supply set to off state

  Serial.begin(9600);
  mp3.begin(); //Start communication with the DFplayer module
  uint16_t volume = mp3.getVolume(); //Get actual volume
  mp3.setVolume(30); //Set new volum (max is 30)
  uint16_t count = mp3.getTotalTrackCount(); //Get the total tracks on the SD card in case we want to sue this later...
}

//just a fucntion that we use to create delays in "ms"
//without using the delay() function
void waitMilliseconds(uint16_t msWait)
{
  uint32_t start = millis();

  while ((millis() - start) < msWait)
  {
    // calling mp3.loop() periodically allows for notifications
    // to be handled without interrupts
    mp3.loop();
    delay(1);
  }
}

void loop()
{

  if (digitalRead(sw1) == LOW)
  {
    mp3.playMp3FolderTrack(1); // Play audio track 0001
    waitMilliseconds(5000); // 1s of delay
    while (digitalRead(sw1) == HIGH); // do nothing until state changes

  }

  if (digitalRead(sw2) == LOW)
  {
    mp3.playMp3FolderTrack(2); // Play audio track 0002
    waitMilliseconds(5000); // 1s of delay

    while (digitalRead(sw2) == HIGH); // do nothing until state changes

  }

  if (digitalRead(sw3) == LOW)
  {
    mp3.playMp3FolderTrack(3); // Play audio track 0002
    waitMilliseconds(5000); // 1s of delay

    while (digitalRead(sw3) == HIGH); // do nothing until state changes
  }

}

After pressing sw1, the first if works. After releasing sw1 (it's a pushbutton), the line while (digitalRead(sw1) == HIGH); will make the code just sit there forever without continuing with the rest of the code until you press sw1 again, which will be caught by the first if unless you release 'sw1' inhumanly fast.
So, once you have pressed and released sw1, the rest of the code with the next two ifs will never run.


NodeMCU - use flash button as input in loop() I couldn't find a proper answer on the net so I came here as a last resort.
So I want to use the FLASH button as an input in the loop() method.

Is there a way the check if it's pressed or not?

The Flash button on NodeMCU is connected between io 0 and ground.  You can use it as a button.  Set pinMode(0, INPUT_PULLUP) and you will read io 0 LOW if the button is pressed.

NodeMCU schema

To put the module in flashing mode, first the Flash button must be held and the Reset button pushed, only then should the Flash button be released. Normally, the reset to flashing mode is done automatically by esptool before uploading over USB. This uses the circuit connected to serial RST and DTS lines.


Arduino - Push Button State Problem My problem is I want the buzzer to stop after a certain amount of time, regardless if it is still pressed or not.

I have tried to implement a boolean statement to the code but to no avail(I'm not very good at this)

Can someone shed some light as to how I do this?

The code already times out after 1000ms when your finger is lifted off the buttin so I got that far but cant get any further.

Here is what I have.

Any other suggestions are also welcome as I know its not the prettiest or best implemented but i was just happy it worked for me.

// Setting The Pin Numbers
const int touchsensor = 2;                      // the number of the touchsensor pin
const int buzzer =  4;                          // the number of the LED pin

// variables:
int touchsensorState = 0;                       // variable for reading the
touchsensor status
unsigned long timestamp = 0;
unsigned long timeout = 1000;

void setup() {

  pinMode(buzzer, OUTPUT);                      // initialize the buzzer as an output
  pinMode(touchsensor, INPUT);                  // initialize the touchsensor as an input
 }
void loop() {

   touchsensorState = digitalRead(touchsensor);  // read state of the pushbutton value:

   if (touchsensorState == HIGH) {                 // check if the touch sensor is pressed. If it is, the touchsensorState is HIGH:
     digitalWrite(buzzer, HIGH);                 // buzzer will emit sound:
     timestamp = millis();                       // Timing button press
   }

   if(millis() - timestamp > timeout) {
   digitalWrite(buzzer, LOW);                  // buzzer will not sound:
   }
}

you will need to implement a edge sensor. Add a previousTouchsensorState to the globals and replace the if where you check the sensor state with:

if(previousTouchsensorState == LOW && touchsensorState == HIGH) {
     // check if the touch sensor is pressed and wasn't the last time though the loop.
     // If it is, the touchsensorState is HIGH and previousTouchsensorState is LOW:
     digitalWrite(buzzer, HIGH); // buzzer will emit sound:
     timestamp = millis();       // Timing button press
}
previousTouchsensorState  = touchsensorState;


Troubleshoot Arduino LCD 16 x 2 shield I tried to assemble Adafruit's Arduino LCD 16 x 2 using the instructions RGB LCD Shield: Control a 16x2 Character LCD using 2 pins - Assembly  without any success.

After assembly, I uploaded the HelloWorld example sketch on to the Arduino. The shield doesn't seem to be working. The LCD didn't turn on.

If I push back/press the LCD it turn on. Any idea on how to troubleshoot this?

By visually assessing the pictures, the issue seems to be due to poor soldering job.

You should try re-heating the soldering joints and make sure they are clean. There could be dry joints that may not be conducting signals.

Also you should upload pictures to your question post, not as an answer.


How to programmatically upload an Arduino sketch generated by node.js (electron) or from browser? We are trying to make an app that generates an Arduino sketch (.ino) using Google's Blockly and node.js, and uploads it to Arduino.

Even after searching a lot, I am unable to find how to build and upload the generated code to the board. Is there any tool or API available for node.js to do the same?

Or could I call some binary for this function. Please help.

There are two things you need to do:

Compile the sketch into a .HEX file
Upload the sketch to the board

The first part can be done with arduino-builder which is part of the IDE since 1.6.6, or you can use one of various Makefile projects on a platform that supports make, or you can manually script it yourself calling the correct avr-gcc and avr-g++ commands. You can check the output of the IDE for what those are.

The second part is done, usually, using avrdude - again see the output of the IDE for the correct command format.


Arduino program only works when run as root Uploading simple sketches seems to work when I run the Arduino program as root (sudo). I would like to run it as a regular user. Has anyone faced the same problem before and fixed it?

Here is what I obtained from lsusb:

$ lsusb
Bus 002 Device 022: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)

And the Arduino program identifies it as /dev/ttyACM0. Here are its permissions:

$ ls -l /dev/ttyACM0
crw-rw---T 1 root dialout 166, 0 Mar 14 22:03 /dev/ttyACM0

Here is the output from id

groups=1000(abhiram),20(dialout),24(cdrom),25(floppy),29(audio),
30(dip),44(video),46(plugdev),105(scanner),110(bluetooth),112(netdev)

When I upload an sketch from the examples, as a regular user, I encounter this error:

avrdude:stk500_recv(): programmer not responding

Any suggestions are welcome.

The easiest solution is to add yourself to the dialout group.

First make a note of the output from id. Save it in file (not in /tmp as that gets cleaned out on a reboot). If you look at the output, you'll notice that your user is signed up for several groups and those groups represent extra privileges on the system. By default your Arduino is assigned to the group dialout because it registers as a serial interface and in the old days these were often used to ... dial out, using a modem.

To add yourself to the dialout group, issue the following command:

sudo usermod -a -G dialout $USER

Don't forget the -a flag (for appending groups rather than replacing) or you will have entirely different problems. This is the reason for making a copy of the id output to a file, so in case you do mess up at least you know what your user was configured like before.

Then log out and log in and it should work from that point.

Optionally you can double check the output for id against the output you saved before.


I2C comunication, ESP->Nano on endTransmission no ACK fron nano i am trying to communicate between ESP(master) and arduino nano(slave). This is only a prototype and all works fine. But i want to  add multiple arduinos and therefor i need to detect if the arduino is connected.
I use the return function from wire.endTransmission as shown in i2c scanner to detect devices. But it doesnt work.
On the arduino i have this program:
#include <Wire.h>

const int16_t I2C_SLAVE = 0x22; // 0x22 = 34 cize izba 3(30)

void setup() {
  Wire.begin(I2C_SLAVE);

}

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

}

on the ESP i am trying this:
Wire.beginTransmission(I2C_adress[adress]);
int error = Wire.endTransmission();

Serial.println(error);

It returns only 2 (received NACK on transmit of address)
Why? When i have other code on the slave (with onRecive and onRequest all works and comunicates)
Thank you.

I'm a fool, I tried to detect other devices in the setup function before the Wire.begin(PIN_SDA, PIN_SCL,  I2C_MASTER);
I Found it only because of you. The rubber duck. I started to write the program down to post it here and bingo.
That was the reason why the master had the "NACK" answer. The master was not started yet.
Thank you


How to connect a SilentStepStick TMC2130 stepper driver? please excuse the noob question

Am connecting a SilentStepStick to arduino with a stepper, for bench testing.

It requires 5V power, plus I have a 24V power supply for the steppers.
+5V connected to Vio, and +24V connection to VM.

Question: how to connect the grounds?  The device has two GND pins.  Should I just connect one ground, from the 5V power supply, to avoid ground loops?

Or should grounds from both power supplies be connected?

Thankyou for any advice.

Answer: (from Electrical Engineering), yes both grounds must be connected.

In this example, +5V and GND from the arduino would connect to the two top left pins in the diagram (Vio & GND).

The two 24v power lines would connect to the bottom left two pins, Vm & GND


(just the IC, no resistors or capacitors)

  What might be wrong with my setup?

That's easy: You miss the capacitors ;-)
Check figure 5 of the datasheet and try again.


Function not successfully reading sensor registers I'm trying to write a library for an accelerometer/magnetometer sensor.  The sensor is a LSM303D chip (https://www.pololu.com/file/0J703/LSM303D.pdf).

I've written a function, readRegister() (below) that's supposed to get the data from the sensor.  However, I put in many different registers into the function into the function, but it always returns the same number.  That number changes every time I unplug my Arduino from my computer.

byte fp::readRegister(byte register_address, int numBytes) {
  Wire.requestFrom(register_address, numBytes);
  byte c;
  Serial.println(Wire.read());
  while (Wire.available()) {
    c = Wire.read();
  }
  Serial.print("0x");
  Serial.print(register_address, HEX);
  Serial.print("\t");
  Serial.print(c);
  Serial.print("\t");
  Serial.println(millis());
  return c;
}

Here's an example of the problem output:

0x8 190 2
0x9 190 3
0xA 190 11

And here is something more like what I'd expect:

0x8 193 [time]
0x9 189 [time]
0xA 195 [time]

Here is the Git repo with the rest of the code: https://github.com/fpdotmonkey/fp_accel

Thank you in advance for your help.

Wire.requestFrom(register_address, numBytes);
  byte c;
  Serial.println(Wire.read());
  while (Wire.available()) {
    c = Wire.read();
  }

This has a number of problems. For one thing your (I presume) debugging print consumes the data from Wire.read, so when you go to get it into c, you have already printed it. In other words, you are reading byte #1 and printing it, but using byte #2. This seems an odd thing to do.

Next, what is this doing?

  while (Wire.available()) {
    c = Wire.read();
  }

You are reading an indefinite number of bytes, and retaining the last one. Why?

Possible rework:

byte fp::readRegister(byte register_address, int numBytes) {
  Wire.requestFrom(register_address, numBytes);
  byte c = Wire.read()
  Serial.println(c);
  Serial.print("0x");
  Serial.print(register_address, HEX);
  Serial.print("\t");
  Serial.print(c);
  Serial.print("\t");
  Serial.println(millis());
  return c;
}

  Here is the Git repo with the rest of the code: https://github.com/fpdotmonkey/fp_accel

From your linked code:

  byte xlm = readRegister(fp::OUT_X_L_M, 1);
  byte xhm = readRegister(fp::OUT_X_H_M, 1);
  byte ylm = readRegister(fp::OUT_Y_L_M, 1);
  byte yhm = readRegister(fp::OUT_Y_H_M, 1);
  byte zlm = readRegister(fp::OUT_Z_L_M, 1);
  byte zhm = readRegister(fp::OUT_Z_H_M, 1);

You have the wrong end of the stick here.

  Wire.requestFrom(register_address, numBytes);

You request from the I2C address - that is the device address. The register is something else.

Judging by the datasheet you first have to send the register address, and then request the data. Something along the lines of:

byte fp::readRegister(byte register_address, int numBytes) {
  Wire.beginTransmission (DEVICE_ADDRESS);
  Wire.write (register_address);
  Wire.endTransmission (false);  // repeated start
  Wire.requestFrom(DEVICE_ADDRESS, 1);
  byte c = Wire.read()
  Serial.println(c);
  Serial.print("0x");
  Serial.print(register_address, HEX);
  Serial.print("\t");
  Serial.print(c);
  Serial.print("\t");
  Serial.println(millis());
  return c;
}

Similarly for writing to a register:

void fp::writeRegister(byte register_address, byte val) {
  Wire.beginTransmission(DEVICE_ADDRESS);
  Wire.write (register_address);
  Wire.write(val);
  Wire.endTransmission();
}

This is untested because I don't have the device here, but I know that what you had won't work. To check the actual device address run the I2C scanner I mentioned before.


How to declare and use "Variabled arrays" inside arrays Good day folks. I'm new here and have been starting to be enthusiast in Arduino. I have a problem and I don't know what I should do, or whether I did something wrong regarding an array of arrays. Surfed on the internet to find a bunch of examples but the only difference is that they don't use arrays that have been declared to have a name inside array.
Every array inside array I see that works is like this:
byte array[2][4] = { {1,2,3,4}, {5,6,7,8} };
Serial.println(array[0][2]); is equal to '3'.

But mine is like this:
byte arrayX[4] = {1,2,3,4};
byte arrayY[4] = {5,6,7,8};

byte arrayZ[2][4] = { arrayX[4], arrayY[4] };

Serial.println(arrayX[2]); is equals to '3'.
Serial.println(arrayZ[0][2]); is equal to '0'.

Why?
Below is what in reality I am experiencing. I hope someone can try this out too.
softAddr = cycle * 2;

is an expression I used for looping where cycle is the iterated variable
for (byte cycle = 0; cycle < 7; cycle++) {}

I did a simple simulation and I guess the way I initialize the parent array, it initializes a new array in the name same from the declared variables but separate.
byte arrayX[4] = {1,2,3,4};
byte arrayY[4] = {5,6,7,8};

void setup() {
  Serial.begin(9600);
  byte glass[2][4] = {arrayX[4], arrayY[4]};
  Serial.print(F("OLD 1: ")); Serial.println(arrayX[0]);
  Serial.print(F("OLD 2: ")); Serial.println(arrayX[1]);
  Serial.print(F("NEW 1: ")); Serial.println(`glass[0][0]`);
  Serial.print(F("NEW 2: ")); Serial.println(`glass[0][1]`);
}

output:

OLD 1: 1
OLD 2: 2
NEW 1: 0
NEW 2: 0

//answered realized
I forgot that the array I put inside the array already had its data based on its index and the [4] resulted to nothing or 0 since there is no value at index [4] (knowing, indexes where 0, 1, 2, 3 on a 4 sized array). I realized this after I made a simple loop declaration not instantly like this:
byte arrayZ[2][4] = { arrayX[1], arrayY[1] };

But like this:
byte arrayX[4] = {10,11,12,13};
byte arrayY[4] = {20,21,22,23};
byte arrayZ[2][4];
void setup() {
  Serial.begin(9600);
  for (byte parent = 0; parent < 2; parent++) {
    for (byte child = 0; child < 4; child++) {
      if (parent == 0) {
        arrayZ[parent][child] = arrayX[child];
      } else {
        arrayZ[parent][child] = arrayY[child];
      }
    }
  }
  for (byte parent = 0; parent < 2; parent++) {
    for (byte child = 0; child < 4; child++) {
      Serial.print(F("value: ")); Serial.println(arrayZ[parent][child]);
    }
  }
}

Output:

value: 10
value: 11
value: 12
value: 13
value: 20
value: 21
value: 22
value: 23

Resulting in simply like this:
byte arrayZ[2][4] = {
  {arrayX[0],arrayX[1],arrayX[2],arrayX[3]},
  {arrayY[0],arrayY[1],arrayY[2],arrayY[3]}
};

Something is wrong with your type description:

byte arrayX[4] = {1,2,3,4}; byte arrayY[4] = {5,6,7,8};

byte arrayZ[2][4] = { arrayX[4], arrayY[4] };

Serial.println(arrayX[2]); is equals to '3'.

This is normal ... arrayX[0] = 1, arrayX[1] = 2, arrayX[2] = 3

However, the next one is not good:

byte arrayZ[2][4] = { arrayX[4], arrayY[4] };

You are declaring a byte array, but you add arrayX[4] and arrayY[4] which, where arrayX[4] is the 5th elements of arrayX but it has only 4 elements, so it points to memory outside the array (probably into the next array.

byte arrayX[4] = { 1, 2, 3, 4 };
byte arrayY[4] = { 5, 6, 7, 8 };

byte* arrayZ[2] = { arrayX, arrayY };

Serial.print(arrayZ[0][2]);

This should print 3 (not tested).


How to connect dual brushless motors to arduino I'm planning on making a Force Feed Back racing wheel with arduino.Saw a lot of tutorials but it uses brushed DC motors ,couldn't find how to connect dual brushless motor for force feed back.

This the motor I want to use :
http://www.dx.com/p/chrgm25bl2418-dc-brushless-motor-with-built-in-drive-24v-12v-470930#.WkurLcvhVAg

.                       .

It looks like you provide the correct voltage to the VCC and GND pins to power it, and connect the CW/CCW and PWM (and GND of course) to your Arduino - the first to control the direction, and the second to a PWM pin to control the speed.

You can use the FG pin to monitor the speed from the internal hall effect sensor if you want.


Controlling a capacitive touch screen that doesn't have I2C/SPI I have been searching for cheap slim 3" 16:9 capacitive touch screens for a while now. But I couldn't find any that had an I2C or SPI interface. The cheap displays always have these ribbon cables with a ton or pins and it's really hard to find a way to control them from an Arduino (or ESP-32 or ESP-8266).

I recently found this one, but how do you access such a touch screen that doesn't have an I2C or SPI interface?
Do I need some sort of driver board? What exactly would I be look for?

Do I need some sort of driver board?

There are quite a few solutions around to interface with parallel devices like that. Some can be purchased off-the-shelf. I described a home-made solution on my page Connecting a graphical LCD via a I2C/SPI using a 16-bit port expander.

This isn't a touch screen, but from what I can make out of your (rather hard to read) image, it looks similar in concept.

I used a MCP23017 16-bit port expander (that is an I2C part, but you can get the MCP23S17 chips which has an SPI interface).

As you can see from the photo, there are only four wires from the Arduino to the LCD board: +5V, Gnd, SDA, SCL.

When I wrote that article it looks like the MCP23017 was $AUD 2.30. A quick Google search indicates it is still selling for around $US 2.50. On eBay they seem to be selling for around one dollar (eg. $5 for 5 chips).

Depending on the complexity of the driver (on the touch-screen board) writing suitable code may be moderately easy to slightly harder. It depends on how much you are used to coding for these port expanders, and how fiddly the interface requirements are.

Since Adafruit offer a driver shield, it can presumably be done.


Error while uploading the sketch for Arduino Mini I'm having a problem while uploading the program.

Arduino: 1.8.4 (Windows 10), Board: "Arduino Mini, ATmega328P"

Archiving built core (caching) in: C:\Users\UMME-K~1\AppData\Local\Temp\arduino_cache_566019\core\core_arduino_avr_mini_cpu_atmega328_3f323efdab4276426e9d8710d5d73f64.a
Sketch uses 3932 bytes (13%) of program storage space. Maximum is 28672 bytes.
Global variables use 250 bytes (12%) of dynamic memory, leaving 1798 bytes for local variables. Maximum is 2048 bytes.
D:\Amna\arduino-1.8.4\hardware\tools\avr/bin/avrdude -CD:\Amna\arduino-1.8.4\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\UMME-K~1\AppData\Local\Temp\arduino_build_808790/buzzer.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "D:\Amna\arduino-1.8.4\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

An error occurred while uploading the sketch

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

What should I do?

On Uno and other boards with USB on board, for flashing the IDE resets the Atmega to bootloader, sending signal over USB. Mini has not an build in USB and you connected it with an USB to TTL cable. Has this cable a Reset signal line? If yes, did you connect this line to Reset pin?

If not, then you need to do a manual reset in the right moment when avrdude sends the hex file. I count to 9 after the first attempt and then I push the reset button.


Strings becoming empty (Arduino Uno) I'm running a modifed code on Arduino Uno + WiFi shield (updated), and I have seen strange behaviors with String ; here is my code, the goal is to parse a HTML request to know which page was requested :

String line = client.readStringUntil("\n");
Serial.print("Line : [");
Serial.print(line);
Serial.println("]");

String cmd = line.substring(0, 3);
Serial.print("Command : [");
Serial.print(cmd);
Serial.print("]");

My problem comes from what appears in the console :

Line : [GET / HTTP/1.1
Host: 192.168.43.200
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch
Ac]
Command : []

I was expecting the cmd variable to contain GET, and I do not understand why it contains nothing.

I suspect this behavior comes from the lack of RAM (compiler says there are only 670 bytes available for local variables), but if it's the case, I do not know how to solve it, as I'm pretty inexperienced in C++ and I need to store a String containing the values that are sent as a reply to the HTTP request.

PS. I'm also wondering why the client.readStringUntil("\n") method sends the full request instead of only the first line.

In general, you don't want to be copying strings around when you don't have to because it's inefficient. For parsing things like command lines, you can often just work with the existing String (or better yet, string; see Majenko's tutorial).

In this particular example, you have a string and you want to know if it's an HTTP GET command. That's simple enough; the first four characters will be GET (we check the space on the end because we don't want to interpret GETMORE /foo as a GET command).

This is extremely easy:

String s = "GET /foo/bar";

if (s.startsWith("GET "))
    Serial.println("GET command");
else
    Serial.println("Not GET command");

For stuff in the middle of a string you obviously can't use startsWith, but there are other functions that can help. For example, once you know it's a GET command, you know that the URL starts at position 4 (the 5th character, since counting starts at 0). You could test to see if it starts with '/foo' with

if (s.indexOf("/foo") == 4)
    Serial.println("Path starts with /foo.");
else
    Serial.println("Path doesn't start with /foo.");

That said, while this kind of thing is workable for quick tests, in the long run you probably want to move towards parsing in C in the way that Majenko's tutorial above talks about, and likely parsing as much as possible as you do the reading (rather than reading everything into memory and then parsing it) due to HTTP requests being relatively large compared to the memory you have to handle them.


Reading pulse train with DC offset One of the analog inputs to Arduino is a pulse train with DC something like 1.5V to 3.9V pulse. This of course changes by time and Im only interested in the difference voltage (peak-to-valley). Like I want Arduino to measure (3.9V-1.5V) in the loop. I can use two analog inputs if there's no other way.

How to code this kind of measurement?
Does anybody have experience with this?

duty cycle is 50% freq 3.3kHz.

The proper method to use depends in part on what the data is for, and on what other processing your loop needs to do.  The following example assumes there is nothing to do except compute the difference between the highest and lowest readings from among the most recent 8.

enum { nReads = 8 }; // # of readings = 2**3
enum { rMask = 7 };  // index-mask of 3 bits
enum { aIn = A3 };   // analog input pin #
int reads[nReads];
byte rindex=0;

void loop() {
  int vhi, vlo, vdiff, r;
  r = reads[rindex] = analogRead(aIn); // Analog read takes about .1 ms
  vhi=0; vlo=1024;
  for (byte i=0; i<nReads; ++i) {
    if (r > vhi) vhi = r;
    if (r < vlo) vlo = r;
  }
  rindex = (rindex+1) & rMask;
  vdiff = vhi - vlo;
  //
  // In this section, scale or use or report vdiff
  //   ...
}

An analog read takes about 104 μs.  That, plus any time taken to scale, use, or report vdiff, will be the major determinant of how rapidly loop() runs, because the for loop that calculates vhi and vlo should take less than 10 or 15 μs.

For example, if loop() takes 125 μs per pass, the code will get about one reading per half cycle of input.  (3.3 KHz is 303 μs per full cycle.)  This will produce a steady precession of where the analog readings are taken within the input waveform's cycle.  If that phenomenon is undesirable, you may need to use interrupt-triggered ADC reads.

If you don't need new differences as frequently as the above code produces them, you could instead on demand take several readings in a row and produce a result.  For example:

int getDiff() {
  enum { nReads = 6 };
  enum { aIn = A3 };   // analog input pin #
  int vhi=0, vlo=1024, r;
  for (byte i=0; i<nReads; ++i) {
    r = analogRead(aIn); // Analog read takes about .1 ms
    if (r > vhi) vhi = r;
    if (r < vlo) vlo = r;
  }
  return vhi - vlo;
}

void loop() {
  int vdiff;
  if (readingIsNeededNow) {
    vdiff = getDiff();
    // do stuff with voltage difference
  }
  // etc
}


Reading bytes from a file on SD Card - Understanding Buffer I have the following piece of code which opens a Bitmap from the SD card and outputs the width to the serial monitor.

#include <SPI.h>
#include <SD.h>

File bitmap;

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

  Serial.println("Initializing SD card...");
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  bitmap = SD.open("/TEST2.BMP");

  int width[0]; // why can't I just write "int width;"
  bitmap.seek(18);
  bitmap.read(width, 4);
  Serial.println(width[0]); // and "Serial.println(width);"
}

void loop() {

}

It works perfectly fine but I don't understand why I have to declare the buffer for the width as int width[0];. I tried int width; but then the output is just 0.

You don't have to, it's just one way of doing it.

Basically the read function needs a pointer to a buffer to store the data in.  By using an array with one entry you get a pointer to a buffer that is big enough for one (32-bit) integer. And you then get an "easy" way of accessing that one integer within that buffer.

Another way would be to just use a simple integer and pass a pointer to that integer to read:

uint32_t width; // Use a fixed size integer for portability
bitmap.seek(18);
bitmap.read(&width, sizeof(width)); // Use sizeof for portability
Serial.println(width);


Convert INT to Array of Strings My sensor outputs an int. I would like this to be an array of strings so I can send it with my 433MHz transmitter.

Converting an int to a string to an array of strings seems to be extremely complicated. I've tried multiple approaches.

The error is always:

  array must be initialized with a brace-enclosed initializer

#include <VirtualWire.h>

const int led_pin = 11;
const int transmit_pin = 12;
const int receive_pin = 2;
const int transmit_en_pin = 3;
int mostureSensor = 0;

void setup()
{
  // Initialise the IO and ISR
  vw_set_tx_pin(transmit_pin);
  vw_set_rx_pin(receive_pin);
  vw_set_ptt_pin(transmit_en_pin);
  vw_set_ptt_inverted(true); // Required for DR3100
  vw_setup(1000);   // Bits per sec
}

byte count = 1;

void loop()
{
  // read the input on analog pin 0:
  String sensorValue = String(analogRead(mostureSensor));

  char charBuf[7];
  char msg[7] = sensorValue.toCharArray(charBuf, 7);

  //char msg[7] = {'h','a','l','l','o',' ','#'};
  Serial.println("sending");
  msg[6] = count;
  digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
  vw_send((uint8_t *)msg, 7);
  vw_wait_tx(); // Wait until the whole message is gone
  digitalWrite(led_pin, LOW);
  delay(1000);
  count = count + 1;
}

toCharArray is a method. It will copy the value from SensorValur to charBuff, it won't return the char array.

Line:

 char msg[7] = sensorValue.toCharArray(charBuf, 7);

Should be:

 sensorValue.toCharArray(charBuf, 7);

charBuf will already have the sensorValue copied.

Check more about "toCharArray" method :

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


Using IR Sensor to sense movement? I was wondering if I could use a IR sensor with my Arduino to detect if someone is present in front of it.

Like, the emitter should emit continuously and if the receiver drop connection it should do something.

Will this work fine? or the emitter wide angle and a human body in front of it wont drop the signal?

This will work fine. The easiest way to do this is using IR Sensor Module.

This will give you a digital output of whether there is someone in front of sensor or not. Use can use it as an Edge Trigger to detect Humans passing by.

You can buy one. They are both cheap and easily available.

Or you can create your own.