If you want to get maintained (automatically updated) version of Arduino IDE then you install if from a package repository with its dependencies e.g. using apt-get:

sudo apt-get update
sudo apt-get install arduino arduino-core

However, this way you get a very old version (currently 1.0.5). Obviously, it is not updated too often if at all.

If you already installed from the package repository via apt-get you can uninstall the package and its dependencies like this:

sudo apt-get remove arduino arduino-core
sudo apt-get autoremove

Better way is to download and install Arduino IDE yourself. This way Arduino software won't automatically be updated, so you should check Arduino website every now and then and download a new version if one is available.

Open a terminal window (e.g. by pressing CTRL-ALT-T), and run uname -m to check if you are running 32 bit or 64 bit platform:

uname -m

See output:

x86_64 ==> 64-bit kernel
i686   ==> 32-bit kernel

Go to Arduino Download page on Download the Arduino Software and download the 32 bit or 64 bit version, depending on the Ubuntu version installed on your computer.

In a terminal window extract the package and move it to your preferred location, e.g. /opt. You need sudo rights to move it to /opt. Finally, run the install script if you want to start the IDE graphically (adds desktop icon, MIME type, default application for .ino). See the example commands below for installing the latest 32 bit version as of the time of writing to /opt.

cd ~/Downloads
tar xf arduino-1.6.7-linux32.tar.xz
sudo mv arduino-1.6.7 /opt
/opt/arduino-1.6.7/install.sh

You can also start the IDE from the terminal:

/opt/arduino-1.6.7/arduino


How to specify a timer's name depending on the chip it will be compiled to?

Just as a complement to Delta_G's answer:

The names TIMSK0, OCIE0A, etc. are already preprocessor macros
so, for consistency, it makes sense to define your own preprocessor
macros for them. I tend to be lazy and use one of the already defined
names, like
#ifdef TIMSK0  // support both ATtiny{25,45,85} and ATmega328P
# define TIMSK TIMSK0
#endif

A const pointer for &TIMSK0 is fine though.

The macros identifying the MCU are defined to the value 1. Thus you
have the choice between these three idioms:
#ifdef __AVR_ATtiny45__
...
#endif

#if defined(__AVR_ATtiny45__)
...
#endif

#if __AVR_ATtiny45__
...
#endif

The third one is convenient when you want to address several MCU
models with the same code:
#if __AVR_ATtiny25__ || __AVR_ATtiny45__ || __AVR_ATtiny85__
...
#endif


Updating firmware on Adafruit Huzzah ESP8266

I'm confident that I've resolved this now. I'll leave the question here in case it is useful to anyone in the future.

The problem was they way I was downloading the individual bin files from the github repo, using right click -> Save As in Chrome. This downloads a file with the correct name, but it is actually the content of the file's html page, not the binary itself. Downloading the repo as a zip file, extracting the bin files,  and then uploading them to the Huzzah using a single command gave me a properly flashed device.

What happened was I noticed that esptool can upload multiple files in one go so, with the original bin files, I tried the command:

  esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m 0x00000 boot_v1.1.bin 0x01000 user1.bin 0x7C000 esp_init_data_default.bin 0x7E000 blank.bin

and got the following error

  esptool write_flash: error: argument  : Detected overlap at address: 0x1000 for file: user1.bin

Thats when I noticed that boot_v1.1.bin was way to big to fit in the space between 0x00000 and 0x01000. Examining it in notepad++ revealed that it was html.

A learning experience...


Boolean function call with character pointer input - dont understand how to get updated pointer value

You can't use Serial.println(array);. In fact, I'm not even sure how the compiler even let you do this...

A better approach would be to use Serial.write(array, sizeof(array));

Also, in order to ensure the function is even executing that portion of the code in the first place, you should but some debugging prints in the code. Like this:

     if (NULL != s) {
        i = 0;
        while (s < p) {
            number[i++] = *(s++);
            Serial.write(number[i++]); //-------- debug
            Serial.print(' '); //-------- debug
        }
        number[i] = '\0';
        Serial.println(); //-------- debug
     }

Also, proper use of whitespace is your friend ;)


MPU-9250 : How to convert pitch (+90/-90) to 360 degree?

The equations in you example convert a quaternion representation of rotation into euler angles correctly; The "pitch" euler angle only has a valid range of +90/-90 and changing it will make your angular representation invalid.

Euler angles specify an arbitrary rotation by 3 consecutive turns. You may want "apparent angle with the horizon", which is not the same thing, and does not define a sequential set of turns to get from rotation A to B.

To get pitch and roll with the horizon from a quaternion, I think you want something like:

float x = 2*m_data[1]*m_data[3] - 2*m_data[2]*m_data[0];
float y = 2*m_data[1]*m_data[0] + 2*m_data[2]*m_data[3];
float z = 1 - 2*m_data[2]*m_data[2] - 2*m_data[1]*m_data[1];

float pitch = atan2(y,z);
float roll  = atan2(x,z);

I got this by rotating the vector <0,0,1> by the quaternion and then measuring the angles of the result around x and y axis. This kind of freaks out when one of the angles is close to 90 degrees though; there are probably better equations out there.

"Yaw vs the horizon" doesn't make any sense, and people usually want the same "style" of yaw you are getting from the euler angle equations, so that shouldn't change.


my LM35 temperature sensor gives weird measurements,

ok, the problem is that i used to the wrong voltage conversion, just use:

RawValue = analogRead("your analog input pin");
Voltage = (RawValue / 2048.0) * 3300;
Serial.println(Voltage);

this should print the tempeture in celcious


There may be better ways to mitigate button bounce. Check this link for a discussion on button bounce and example code to work around this problem. In your code, it appears you can not press your buttons faster than once a second.

Determine if the servos you are using are capable of the range you are demanding.  Some servos only travel from 0 degrees to 180 degrees.  Your code is asking the servo to travel from 0 degrees to 360 degrees.  Also, it is unlikely that any normal servo can travel this far.  Most servos use a potentiometer as a feed back sensor.  And most potentiometers can only be turned to something less than 1 full revolution.

It is likely you have not given the servos enough time to move to the zero degree position at the start of each of your 3 loops.  Understand that normal servos can not make complete revolutions.  They need to stay within their designed limit of rotation.  If you want to start over at 0 degrees you need to allow the servos time to rotate back in reverse to the 0 degree position.

Consider your last loop.  You are asking the servo to move from 0 degrees to 360 degrees in 10 degree steps.  You are allowing 20ms per step.  That means the servo will be demanded to move almost a complete revolution in (((360 / 10) * 0.020 = 0.72 seconds) less than a second.  Some but not all servos can move that fast.


Arduino Clone - A request for the USB device descriptor failed

Solution for semi-bricked Pro Micro/mini-Leonardo clones:

The OP's question is ambiguous to as the exact Arduino device in question. My answer applies to the "Pro Micro" or "mini-Leonardo" since these Clones usually use the default Leonardo boot loader, not the modified Sparkfun version.

Note the the Pro Micro doesn't use an external serial to USB chip at all. So the "CH340T USB" argument doesn't apply here. The USB is directly wired to the ATMEGA chip in this case as it has built-in USB 2.0 support.

I've made two projects with these: I gutted an old keypad replaced with a Pro Micro Clone and turned it into a extended keyboard so I could get F13 to F24 keys plus some others, then a custom game foot controller (to 'Q' and 'E' lean in FPS shooters).

Problem, I went to update my Foot controller sketch and after over a year later I forgot my Arduino IDE settings. This time I must have used the wrong setting like "Sparkfun Pro Micro" 3.3.v 8Mhz when your clone is probably like mine a 5v 16Mhz model.
When I uploaded the sketch it failed and apparently corrupted the program Flash header or something.
The original code was still running (on pedal press my LED lit up) but the device now showed up as "..missing USB device descriptor.." type message in the Windows device manager.

Fear not, it's probably recoverable like it was for me.
First of all realize you DON'T set in the Arduino IDE the board to "Spark Fun Pro Micro", simply set it to the default "Arduino Leonardo".
That's the right board setting for these clones. The Sparkfun bootloader IS different, as it says on their site. If you uploaded their bootloader then it might work but that's an experiment for another time.

Now you will need to add a reset button to the right hand side of your board (with the micro USB plug pointing up). The pins are next to each other and are clearly labeled.
I found a mini-switch just right to fit into the header pins from my parts box. In a pinch you can probably solder two small insulated stripped wires as a makeshift switch, but it might make the following step harder which is timing related.

If you plug your Clone Micro back in, notice if you press the switch the Clone Micro will show back up as a Arduino Leonardo on a COM port for about 8 seconds, then fall back to the bad USB ID thing again.

Now in your Arduino IDE create a NEW sketch. Which will create a minimal program that you'll need to restore your Clone back to working order.
Hit the reset switch again and quickly in your IDE preset the "port" to the COM port that shows up. Don't worry it will remember it after the device falls back again.

Now comes the hard part. Unlike a real Sparkfun Micro you can't double tap the reset button for extra time, you only get the 8 seconds period.
In the IDE click the "Upload" button, wait about a second, then hit your reset button.
If all goes well, you will see the typical flashing programming LED success lights and you will have restored your Clone Micro! This might take a few tries depending on your timing.
The thing is to press your reset button slightly after you click the Upload button (or CTRL-U) else you will miss the time frame of the special bootloader reset phase.

Basically this is the directions given here, with a little more details:
https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide#troubleshooting-and-faq

The OP got some opinionated and pretty toxic responses for an open-source hardware device. Some common sense notes on the morality and ethics of buying Chinese clone devices:

First of all, at least this is not nearly as bad a situation of the Chinese fake chips, arguably the real scourge of the Electronics parts world.

Without spending too much time on the legal ramifications and not being a lawyer, it looks like most of the Sparkfun stuff is CC licensed. Although doubtful the license if for their original or modified software/firmware.

From the Arduino site:
"Arduino is an open-source hardware and software company". So the clones are apparently not illegal to buy in the USA (if this is the country of contention).

The reason a lot of people buy the clones is you can buy around three or more of them for the same price of just one Sparkfun Micro.
I've been an electronic hobbyist since the late 70's and part of the equation for me is getting a few extras because there is always that chance I'll fry something despite double if not triple checking my wiring.
I can make a project plus have some spares for the next time.

I wouldn't use it in anything mission critical, but so far the Clone has been working fine for me as a hobbyist.

These things being said, I'm a big fan of Sparkfun. They are a relatively small USA company that makes fun innovative products with helpful Youtube "how too" videos, etc. I'm all for supporting them.


Having trouble assigning colour to my neopixels

You already are choosing a random LED. Now you only need to define and use the colors, that you need. Define an array with the colors:

#define COLOR_N 4
uint32_t colors[COLOR_N] = {0x00FF0000, 0x000000FF, 0x0000FF00, 0x00FFFF00};

Also define a static or global variable to hold the current color:

uint8_t current_color = 0;

Then use this array in strip.setPixelColor() with the current_color variable as index:

strip.setPixelColor(i, colors[current_color]);

Now increment current_color for the next color. To go from yellow to red again, you can use the modulo operator %:

current_color = (current_color + 1) % COLOR_N;

You can easily extend to more colors, by writing the new colors into the colors array and setting COLOR_N to the corresponding value.

About the color values: The neopixels use an RGB color model with 8 bit depth. That means, that each component (red, green and blue) occupies exactly 1 byte. Thus there are 256 steps for each component. To describe a full color, you need all three components, thus 3 bytes or 24 bits. The data type, that fits this uint32_t (unsigned integer with 32 bit), though the most significant byte is unused here (if you use an RGBW strip, this byte is the component for the white LEDs).

We can write the number, that is representing a full color, as a hexadecimal value. Each component occupies 2 hexadecimal digits:

0x00RRGGBB

where 0x is the prefix, which marks a hexadecimal number, and RR, GG and BB are the components red, green and blue of the color. So a full red is 0x00FF0000, a full blue is 0x000000FF (the leading zeros are not mandatory, but I think they help readability and comparability).

The color mixing works additive here, just like light does. All components mixed together at the same ratio gives you white, all components to zero means black. Thus you get yellow from mixing red and green the same ratio. So a full yellow is 0x00FFFF00.


After a careful study of C/C++ documentation, I finally managed to use pointers in Arduino :)

So, the final code became like this:

int arrayAAA[] = {6, 8, 10, 12};
int arrayBBB[] = {9, 15, 27, 41};

//Create a pointer, which will point to any of your arrays of your choice
int *newArray;

const int arrayAAALength = sizeof(arrayAAA)/sizeof(int);
const int arrayBBBLength = sizeof(arrayBBB)/sizeof(int);

void setup() {

    Serial.begin(9600);

    //Uses the address of arrayAAA (i.e. inherits the content of arrayAAA).
    //&: points to address of a chosen array.
    //[0]: is a must to grab all values!
    newArray = &arrayAAA[0];

    Serial.print("arrayAAA:");
    for (int i = 0; i < arrayAAALength; i++){
        Serial.print("   ");
        Serial.print(arrayAAA[i]);
    }
    Serial.println();

    Serial.print("newArray:");
    for (int i = 0; i < arrayAAALength; i++){
        Serial.print("   ");
        Serial.print(newArray[i]);
    }
    Serial.println();
}

void loop(){
    //Left empty
}

And it works perfectly, just what I expected!


Menus not changing when button is pressed TFT 128 x 128

You can make things much simpler:

int count = 0;
int button = 5;
int buttonStatus;
unsigned long timer = 0;

void setup() {
  Serial.begin(9600);
  pinMode(button, INPUT_PULLUP);
}

void loop() {
  buttonStatus = digitalRead(button); // read the button status
  if (buttonStatus == LOW) {
    if (millis() - timer > 200) { //de-bouncing the button
      count++; // increase +1 each time button is pressed
      // clear screen function should be here
      timer = millis();
    }
  }
  if (count > 3){ // if count is bigger than 3 start over.
    count = 0;
    // clear screen function should be here
  }
  switch (count){
    case 1: // if count == 1
    // show charecter :)
    break; // break out of this case!
    case 2:
    // show charecter :(
    break;
    case 3:
    // show charecter :D
    break;
    default: // if none of above cases is valid
    count = 0;
    // clear screen function should be here
  }
  Serial.println(count);
  delay(100);
}

simulate this circuit – Schematic created using CircuitLab

So each time button is pressed count value will increase by 1. you can also add another button to decrease this value...

You might also notice when pushing the button it'll count more than once, you'll also need to De-Bounce the button. tutorial.

Edit: added de-bounce function.


Here are a couple sources of ATmega328PB bootloaders based on optiboot:

https://github.com/watterott/ATmega328PB-Testing
https://github.com/ElektorLabs/Arduino

I haven't used either.
If you are set on making your own at least they can provide you with a reference.


Why can't I use an optocoupler to drive an AC circuit using the arduino digital pins?

Use it with Triac.  I use MOC3020 + BT138 + 330 and 510 Ohm resistors.
It works good as relay and in dimmer scheme.
Scheme is here
http://cyber-place.ru/attachment.php?attachmentid=1030&d=1370462030


Burning the Arduino bootloader without an extra Arduino board

If you don't want to go the route of a dedicated programmer, you could try ArduinoISP where you can program an Arduino board (with a Mega on it) to be a programmer for another AVR device (e.g. another Mega). The instructions can be found at https://www.arduino.cc/en/Tutorial/ArduinoISP and allows you to do something like this:


What does the line "while (! Serial);" do in an Arduino program?

On boards with an FT232 chip or other USB->Serial bridge chip (Uno, Mega, etc) it does absolutely nothing.

On boards with a direct USB connection, such as the Leonardo or the Yùn it waits for an active serial connection to be established by the PC (i.e., for the serial port to be opened by a piece of software).

When you open the serial port of a board like the Uno or Mega the whole board usually resets*, so opening the serial port allows you to see the first bits of the serial data.  On the Leonardo etc it doesn't reset when you open the serial, so any serial output during the setup() function would be missed.  Adding that line makes the board pause until you open the serial port, so you get to see that initial bit of data.

*) Unless you specifically write some software that doesn't assert DTR when you open the port


How to measure CO2, Ammonia and Detect Smoke using MQ135?

Now, I dont know how to differentiate it in all different values of required gases and trigger smoke alarm

This sensor does not differentiate between the various gases that it is sensitive to.


Wanted to control 2 servos with serial read

Without knowing, what exactly you want it to do (since you didn't tell us), I see 2 problems in your code:

The code around the line marked with "from here" will ask the user over Serial, if he wants to shoot, but directly after it, it will read a value, without waiting for the user to input something. Serial.read() will not wait for data to arrive, it will just return -1 if nothing is in the buffer. You have to check, if there is actually something in the buffer with Serial.available() and only proceed, if there is actually data to read.
In the following if-statement, you first write the value 60 to the servo and directly after it, without any delay, the value 0. The servo doesn't have enough time to get to 60 - or to even start to move - before you tell him to go to 0. The servo needs time for movements.

Apart from the specific problems with your code, I would use a finite state machine (FSM), to implement it, instead. You declare a global state variable, which represents the possible states, in which your machine can be. If I assume some type of gun/shooting device, these states could be ASK_USER_TO_POSITION_GUN' and 'ASK_USER_TO_SHOOT'. In each state you check the Serial interface (first withSerial.available()then reading withSerial.read()` if it returns something greater than 0) and based on that input you first take the appropriate action and then do the state transition, by changing the state variable.

As example of the general structure:

int state = 0;

void loop(){
    switch(state){
        case 0:
            if(Serial.available()>0){
                int input = Serial.read();
                //take appropriate action
                state = 1; //do state transistion
            }
            break;
        case 1:
            if(Serial.available()>0){
                int input = Serial.read();
                //take appropriate action
                state = 0; //do state transition
            break;
    }
}

Depending on the exact actions to do, you can also tune this, by reading Serial outside of the switch statement and in the case statement only check the input variable. In this case reset the input variable after every interaction.

EDIT: For giving a better explanation about finite state machines, I've drawn a graphical representation of the states. Mostly it is way easier to code, when you first have drawn such a graph to visualize the codes functionality. Note, that this is the logic from your code. You may want it to work another way, but this is beyond the scope and only for understanding. Also note the different numbers of the states than I used above, which I only change, because I needed more states.

See first this graph:

We begin in state 0, where we are waiting for user input through serial. If we go some input, we make a decision: If the value is 111, we will transition to the next state (state 1) to position the gun, else we will wait again for more input. In stage 1, we are positioning the gun and go directly to state 2. There we are again waiting for user input. If we received something, we will again make a decision: On the value 107 we will do the transition to state 3 to shoot, else we will go to state 0, to ask again for positioning, like we did before. In state 3 we are shooting and directly go to state 0 again. This is rather strict division into states.

Since in state 1 and 3 we are only doing a short action and then going directly to another state, we might cut those states away, implementing the corresponding code in the transition from state 0 to 2 and vice versa. This is the logic from my FSM code example above (action together with transition). The graph would look like this:

Which version you should implement depends on other factors. If you are OK with the action code to be blocking, you can implement version 2, since it has less states. If you want to write the action in a non-blocking style, you might find version 1 easier to implement.


That's impossible to tell without looking in the source code for that SDK.
However it will just be a pre-processor macro which probably expands out to one or more attributes, some of which may be specific to the XTensa LX106 compiler.

Update after your edit:
It places the function in the privileged_function section. That section is then placed into a specific area of memory by the linker.
To further examine what it does you will have to look in the linker script to see how it handles that section, and what that means from the chip's perspective, by cross-referencing that with the chip's technical datasheet.


Error trying to compile an example from newly added Arduino menu library

I think you have to add your library in the library folder. Below is the path of that folder. It will help you.

C:\Program Files (x86)\Arduino\libraries


ISP works by using a serial connection (usually via the SPI and nRESET pins) to the MCU. The programmer talks to the device using the low-level protocol that the device expects, and connects to the host using a different, high-level protocol. The host then directs the programmer to perform the various programming actions on the device, and in turn the programmer reports to the host about its current status.

There are a number of programming protocols that already exist, such as the one described in AVR910. As long as both the connection type and the protocol itself are supported by AVRDUDE it will work transparently once the hardware is assembled.

Further details about ISP are available in both AVR910 as well as the "Serial Programming" section of the datasheet for the device in question.


Arduino Uno & Wemos (0.66” Across) OLED Shield

The first thing I see when googling "0.66 lolin oled" is the link to https://wiki.wemos.cc/products:d1_mini_shields:oled_shield and their Get started guide. This yields the libraries to be used with it:

for the OLED: https://github.com/mcauser/Adafruit_SSD1306/tree/esp8266-64x48 with the dedicated test sketch
for the A & B buttons: https://github.com/wemos/LOLIN_OLED_I2C_Button_Library


When setting hardware timers as interrupts, should I prefer a lower prescaler value or a lower CTC?

If 'clock tick' count (here 1024), timer width and  MCU clock used are constant (a fixed value), I would not go for last option i.e. prescalar 1024 and CTC of 1. Here are my reasons (specially for Arduino )

1) When CTC is close to zero ( like 1-> 10), sometimes timer behaves as if count is zero and outputs a square wave (with 50% duty ratio) with half the demanded frequency. So make CTC reasonably big. But again selecting a high clock frequency (pre scalar 1) may also show reduced accuracy. A intermediate option I think is better.

2) When count CTC changes dynamically in a process, timer pre scalar should be selected such that CTC count will always be less than or equal to timer width over whole process.

i.e. the maximum 'timer tick count' should be comfortably accommodated by the timer with it's given width. Even here same dilemma again occurs, then selection based on point 1 is better.

If this is not enough, then only way I think is to implement each case  physically and check which combination gives you the best results. Practical results I think are more reliable ( may be you will get a board specific efficient combination!)


I'm having similar issues, although it could well be my fault!
I can't see any coding sending AT commands, or waiting for responses in your example.
Try running your TX pin to your RX pin on your Arduino (take the SIM7000e out of the equation completely).  If your code works, then the issue is elsewhere.
I've tried connecting via USB and that seems through a terminal.  I was able to connect to a mobile network using the AT command
AT+CSTT="cmnet"


Is this class declaration wrong? " Declaration has no storage class or type specifier" error

Code goes in functions, not the global scope.
Your line
pubClient.setServer(mqtt_server, mqttPort);

should be inside a function. Most probably setup() so it gets called when your program starts.
Incidentally - where are setup() and loop() - the two functions that are required by Arduino code?


How to make ultrasonic and light sensors detect whether a person moving in or out

See this tutorial on the Arduino Projecthub, that project was already made. Here is a tutorial how to use a Ultrasonic sensor.


UNO R3 + WiFi ATmega328P+ESP8266 (32Mb memory) USB-TTL CH340G For Arduino Uno - External ESP8266 Pins

From esp8266 datasheet:

TOUT - ADC pin. It can be used to test the power-supply voltage of VDD3P3 (Pin3 and Pin4) and the input power voltage of TOUT (Pin 6). However, these two functions cannot be used simultaneously.

from the pinout PDF of the Uno+WiFi board:


Can I get the current connection speed with ESP8266?

Wifi modules decide on link speed based on signal strength. So you can estimate the link speed with signal strength, which you can get with WiFi.RSSI(network).

The datasheet of ESP8266 contains a table mapping RSSI to link speed under "Sensitivity":

-98 dBm: 1 Mbps
-93 dBm: 6 Mbps
-91 dBm: 11 Mbps
-75 dBm: 54Mbps
-71 dBm: 65Mbps, 72.2Mbps

Whenever these values are "minimum", "maximum" or "typical" remains unclear. These dBm limits are also quite low, which means the link speed will probably be capped by the other communication peer (your router). Here's the same table for a random D-link router, DI-624.


Why should I connect the l289n motor driver wires to specific arduino pins only?

Pwm is just a digital out with extra fancy on off controls.  You can use any digital out if you do not need those extra features.
To just signal a single H bridge (1 motor of your l289n) for forward, reverse, stop, one only needs two digital outs.
I recommend you get the hang of your h bridge first - signaling it on a bread board with vcc (usually 5v but can be 3.3) and ground rather than the arduino.  Then once you understand the motor directions that result from your wiring, write the code accordingly.  This tends to result in:

fewer fried arduinos
code with functions and signals named after their intent (rather than having to mix forward and reverse)


does anyone know how to keep ...

think about ways to conditionalize execution on time elapsed. I showed a short while ago ways to construct a software timer and you may want to look into that.


How to control nokia 5110 display using esp-01

Yes, you can use a NodeMCU ESP12E board for example as a standalone microcontroller, you actually don't need an Arduino in your case.


Use trigonometry (sin() and cos()) functions to get the right x and y coordinates.
I would consider replacing your drawLine() command with something like this (untested) assuming the tiltAngle is in degrees from -90 to +90 (with 0 degrees is straight up) and you want to draw a line at this angle from the origin (63, 63) with a radius of 64.
float tiltAngleRad = tiltAngle * DEG_TO_RAD; // convert angle to radians
int xEnd = 63 + 64 * sin (tiltAngleRad); // Ending x-coordinate offset & radius
int yEnd = 63 - 64 * cos (tiltAngleRad); // Ending y-coordinate offset & radius
display.drawLine (63, 63, xEnd, yEnd);

You might have to experiment with the offset and radius but I believe this will get you close yo what you want.


Necessary torque of motor to move a door.

You need a "hanging scale" preferably "analog one".

Mount it to any place of the door and slowly pool at 90 degrees. Check what value does the scale show when doors start moving. Static friction is always higher than dynamic friction.

Torque = Radius * Force

Raduis is the distance between mounting place and door hinges.
Force is 9.81 times max value shown by the scale in kilograms.

Do this many times for many mounting points then take average.
Use safety margin of 50% (motor should have at least 150% of required torque)


Arduino extended database library data type. Is char str[] in Arduino the equivalent of VARCHAR in SQL?

If you mean, are these equivalent:

foo VARCHAR(100);

and:

char foo [100];

No, they are not equivalent, really. In the case of SQL you can put 100 characters into foo. In the case of C++ you would (generally speaking) put up to 99 characters into foo, with the final character being 0x00 which indicates the length of the string.

You could conceivably put 100 characters into foo but then you would have to store the size of foo in another variable.


Using the VCC as voltage reference is ok only if

you accept poor performances or
you need to measure a ratiometric output.

Case 2 is because the output depends on VCC (so you compensate). For instance, if you want to get the value of position in a potentiometer, you have that the voltage you see is Vo = Vcc * X (where 0<=X<=1 is the position), then the result you have on your ADC is Y = Vi / Vcc * k = X * k (where k is the maximum value of the ADC reading - e.g. 1023). So you actually compensate the Vcc deviation.

If you want to measure an absolute voltage, however (case 1) you will have a lot of uncertainties. For instance, if your current varies during the time (for instance you turn on the LED), the Vcc voltage can vary quite a lot. This is why for precise measurements you always must use a voltage reference.

In your case, you can

Use the internal reference - for the Atmega328 it is nominally 1.1V, but it can range from 1.0V to 1.2V
Use an external reference

You have to keep in mind that the voltage reference is the maximum value you can read. For instance, if you use the internal reference and then try to measure a 2.3V, you will not be able to do it (you will read the maximum value of 1.1V)

In order to fix this, you can use a trick: use Vcc as reference, and then use a voltage reference to get a precise calibration every time you need to measure something. For instance, if you have to read values from ADC1 and ADC3, you can

Read the value of the internal/external reference
Read ADC1
Read ADC3
Use the reading in point 1 to be able to guess what ADC1 and ADC3 readings were

This way you compensate for variations in the supply.

Just note that, even if the internal reference is not very precise (it has a 10% deviation from the standard value), it is indeed stable, while the VCC varies (a lot) during time. So if you have to calibrate, calibrate against the internal reference and not the Vcc.

If you can afford an external voltage reference, these are usually very stable and have very little deviation from sample to sample, so you may assume their value is "fixed"


Use transistor to press button on external device

Yes, you have screwed the circuit up slightly.

You want to lose the red wire between the collector and +5V otherwise when you turn the output pin HIGH the transistor will explode.

Also you need to make sure that the ground of the Arduino (emitter of the transistor) is connected to the - of the target circuit and that the button you are "pressing" is an active-low system with internal pullup. If it's not then you will have to come up with another way.

An opto-isolator is a better choice than a transistor when you don't know the internal circuitry of the target device:


I think your Arduino resets itself because of connection or current overload. Also, please share your connection. What is the voltage of the external source? If it needs high power, try a MOSFET like this.


Arduino for delivering a WoL signal over ethernet, when receiving a specific command over WiFi

The Arduino might not be a choice for you. The reason why microcontroller boards(like Arduino) become popular is the simplicity and the easiness of control peripherals through GPIO pins, like output PWM signal to control motors, reading sensors through SPI or I2C, reading analog voltage, and etc. Most microcontrollers on Arduino boards itself, however, is not designed for networking features and does not have even enough performance for it. This means that it would cost you much more money on additional networking devices like WIFI shield, Ethernet shield and microprocessor for networking (Arduino Yun).

So, if you are looking for just a pure networking device like what you have in mind, I would highly recommend you Raspberry Pi(2 Model B for $39 and 1 Model B+ for $30), which has enough capability of networking itself. All you need is a USB WIFI dongle($9) with the Raspberry Pi, I guess. I am pretty sure you won't have a cheaper option using Arduino.

You can use the raspberry Pi as a web server, a NAS, a media server along with the features you mentioned.


How do I output tone() and audioFX board output through a single speaker?

Yes, a passive mixer would do fine. I would recommend capacitors to remove any DC component too, before you do the mixing. 22uF should do fine.

I will draw a circuit in the morning.


Adding esp32_komoot_ble library to Arduino IDE

The file, that you are searching, is the one, which contains the setup() and loop functions: esp32_komoot_ble.cpp

These functions are part of the Arduino framework and wrap the classic main() function. setup() is called once at startup, loop() after it repeating forever.


Detecting the down time of a system by subtracting the time when the sytem gives ON signal and when it goes OFF

You have the same state being tested twice:

if (c.state == LOW && new_state == HIGH)   // input rose

and:

else if (c.state == LOW && new_state == HIGH)  // input fell

If "A", else if "A". It makes no sense. I think you wanted the second one to be the opposite:

else if (c.state == HIGH && new_state == LOW)  // input fell

Also, this calculation in display_channel doesn't work:

if (seconds >= 60)
{
  seconds = seconds % 60;
  minutes = minutes + 1;
}

For example, if seconds is 378, then seconds ends up as 18, and minutes as some undefined number plus 1.

That whole block should be replaced with:

minutes = seconds / 60;
seconds = seconds % 60;

In your code:

minutes starts off undefined
You add only 1 to minutes regardless of how many minutes have passed.


Split serial monitor output to only save part of the output

implement a circular buffer of say 30 characters.

clear the circular buffer

read into the circular buffer, char by char

when the last 13 characters in the buffer are: :4CAA0DE091B7 Then the prior 12 characters are the data of interest


Cat motion detector that can tell the difference from humans

Place an additional motion sensor such that it can only detect motion from things significantly taller than cats, and use that as an inhibitor/classifier of the cat motion signal.


There are three basic factors that control long distance communication:

Transmitter Power
Receiver Sensitivity
Signal Directionality

The more transmission power you have the "louder" your signal is at the receiver.

The more sensitive your receiver the "quieter" the signals it can pick up.

The more directional (focussed) your signal is the more arrives at the receiver and the less gets sent off elsewhere.

So you would think get all three of those and you're laughing, but it's not that simple:

High power transmission requires high-power power source
Good focus requires heavy and bulky antennae.

Neither of those are very good on a satellite, since you want it to be as small and light as possible and use as little power as possible.

So in general you have a medium to low power transmitter on the satellite with reasonable directionality, and put all the bulk on earth.  That is why satellite dishes are so big.  They give good focus, and the large size captures a lot of the signal making them more sensitive. You can also use very precise electronics to amplify the signal more.

There is, of course, nothing like that in a shield format, so you would have to create your own. The transmitter isn't so hard, since you don't want to have anything too meaty - the hard part comes when you want to make the base station.  If you can afford enough power to transmit a strong enough signal and have it with enough directionality you can use a satellite TV dish (not a little Sky dish, one of the bigger solid round ones - Sky satellites actually have quite powerful transmitters and the massive solar panels to go with it; not really practical for a small home-built satellite).  Getting the receiver and LNB (Low Noise Booster) tuned properly as well is vital - unless you're transmitting at the same frequency as the satellite the dish is intended to receive (which you mustn't or there'll be a lot of annoyed people around - there are specific frequency ranges you are allowed to use) then you will need to ensure the antenna is exactly the right length and that the LNB amplifies and filters the right frequency range.

Once you have got over all those hurdles the receiver is just a simple receiver.

The actual transmitter and receiver circuits themselves can be something fairly off-the-shelf (the lower the frequency the better since that goes further than higher frequencies) - it's what goes between - the antenna and amplifier - that makes it much more special and long range.


Question different ways of connecting L298N motor driver board to arduino and motors and powering them

Here is a link to a robotoid page which describes a way to use it.
Here is a link to funnyrobotics which explains how to use it.

I am confident that you could use a search engine to find more examples.

One trick is to use image search. Then look for pictures which look like your photo, and which have extra writing on them. Most people who add labels and writing to the photo are writing to help beginners understand how to use something.

Edit:
That L298N board claims to have a 5V regulator for powering the Arduino, in which case you could use a single power supply, and let the motor board feed the Arduino.

There are two schools of thought on powering the Arduino and motors:

Use two separate power supplies, one for the motor and one for the Arduino.
Use one supply for both the motor, and Arduino.

Using one supply is simple overall. One concern is electric motors can create a lot of electrical noise. If this is not adequately filtered, it might get injected into the Arduino and maybe cause the microcontroller to reset, or become temporarily unstable. The single supply advocates say the power supply to the Arduino should be properly filtered using capacitors and a proper voltage regulator usually, and the problem is solved.

I agree in principle. However, I have seen situations where the transient failure was so brief it looked 'mysterious'. It took time and effort to track it down. Sometimes it was because the motor power supply was underpowered. When the motor 'stalled', for example when changing direction, taking maximum current, the power supply voltage might dip enough to cause the Arduino supply to dip, and reset the chip.

Summary, if you are going to use a single power source for both motor and Arduino, ensure it has plenty of electrical noise filtering, and is a bit over-engineered to cope with the motor stalling. Specifically, it should be able to supply the motors stall current without dipping too low for the Arduino. The 'professional' approach is to have the Arduino monitor the main power supply, and detect that voltage dip. However, that is more complexity, and I suggest you avoid that.

Edit: If you are concerned you might have weird, hard to trace problems, using a single supply, try to design the system so that the Arduino can be 'unplugged' and given its own supply. That should be easy to do with that L298N board as the connections are screw terminals.

Using two separate power supplies should reduce the chances of electrical noise from the motors getting into the Arduino. In some circumstances is it useful to be able to change the motor power supply, or switch it off, without powering the Arduino off.

When the motor voltage is a lot higher than the 5V needed by the arduino, simple techniques to step down the voltage (linear regulators, like the part on that L298N board) convert the excess power to heat, which is quite inefficient. Much above, about, 18V it can generate enough heat to reach quite a high temperature (i.e. 100C) unless it has a good heatsink.

In that case, a simple, cheap solution is to use a second small power supply for the Arduino. An Arduino is likely using under 100mA, so a PP3 would be okay for, maybe, a few hours. A longer term approach is to step the motor voltage down efficiently.

If you use two power supplies, connect the two 'ground' (i.e. or most negative battery connections) together so that they have a common 'ground' reference. That way the Arduino signals will control the motor driver reliably.

Edit:
PWM does not step down voltage. It gives the illusion of less power because the full voltage is only applied for a fraction of each millisecond. When it is on, it is providing (very close to) the full 'motor' voltage. If the 'motor voltage' connected to that L298N board is 12V, then the motor will see 12V.

However, even if the motor is rated at only 3volts, it is unlikely to break only because 12V is applied across it. A 3V motor is as likely to break because it gets too hot, or spun too fast (e.g. the bearings get damaged).

It will likely get too hot under load, or spin too fast if the PWM signal is on for more than, WAG 50% of the time (but there is no warranty with WAG = Wild-A$$-Guess).

If, and only if, your software doesn't run PWM more than 50%, then those motors may be okay. That is a risk I might be prepared to take if the motors are cheap, and replacements easy to get.

Skimming the datasheet, the L298N needs an absolute minimum motor supply of 2.3V+2.5V = 4.8V.
Also, the output switches which control the motor appear to 'drop' a minimum of 1.8volts.
So I think it would be okay with 6V or 7.2V (maybe upto 9V) motor voltage.

IIRC the arduino will work okay with 7.2V upwards, i.e. 6 x NiMh batteries. A higher voltage is just converted to heat by the on-board voltage regulator. I might be tempted to experiment with the L298N boards 5V output, unless you have seen complaints about it.

I am assuming the motors are brushed DC motors (and not steppers or something exotic)

The motor driver will handle switching the current that the motor needs. However, each time the current is switched on or off, the motor will draw current, or generate current (remember it is a motor and also a generator). That could cause the power rail to dip, or even feed current into power or ground. There are diodes on the board to prevent those spikes doing anything awful to the chip, but there is still current flowing through wires.

Further, every rev of the motor, the brushes will break one connection, and make a different connection with the commutator, typically 6 times. (The commutator is the mechanical system that directs the current to flow the correct way round in the motors spinning electromagnet). That creates electrical noise. In some cases so much that you can hear it on an old fashioned radio receiver or analogue TV.

So noise may be a problem. People typically put a 10nF-100nF, relatively high voltage (say 50V), capacitor directly across the motors power connections, at the motor end.

If things get bad, I did a quick search and this blog looked okay, it illustrates ways to use capacitors and inductors to reduce motor noise.

I wouldn't worry too much. Put 10nF-100nF across the motor wires, and see what happens.


Error using nRF24L01+ with ATmega328P-PU. Works fine on Uno

The ATmega328P can't run at 16MHz at a supply voltage of only 3.3V (check the datasheet). Either raise the voltage or lower the frequency.

Also note that 16mHz would be 16 milliherz (16E-3), so you probably mean 16MHz, i.e. 16 megahertz (16E6).

Remember that the nRF24L01+ is a 3.3V device, so don't connect it to the ATmega's Vcc when changing the supply voltage to 5V.
The IO pins are 5V tolerant, so that's not an issue.


Without seeing the actual code (BTW why can't you add it? Is it top-secret?) I can't be sure, but usually this happens when you don't define a variable but just declare it. Example:

// File myclass.h
class A {
public:
  static int i;
};

// File myclass.cpp
void myfunc() {
    A::i = 0;
}

If you actually declare it the error should go away:

// File myclass.h
class A {
public:
  static int i;
};

// File myclass.cpp
int A::i = 0;

void myfunc() {
    A::i = 0;
}

Remember that the class definition (so the class {}) can go in a header file, but the variables definition MUST go in a source file (so the .cpp one) AND if you have multiple source files you have to put this in ONLY ONE file (usually the file where you implement the functions).

This only applies to static variables.

EDIT: Further explanation.

You should understand the difference between declaration and definition of a variable.

Definition is just stating "there exist a variable called i, which is an integer"; for instance the statement extern int i; defines a variable. All the variables listed in a class are only defined there.

Declaring a variable is one more step: it tells the compiler to reserve the space in memory (this operation is called allocation) and so to physically create the variable. Always keep this in mind.

Little example. Let's say you have a library, using files lib.h and lib.cpp, and files A.cpp and B.cpp both referencing the library (they have a statement saying #include "lib.h"). When writing a library without a class you usually write global variables in this way:

// header file: lib.h
extern int i;

// source file: lib.cpp
int i;

(note: it is better to always define an initialization value, so for instance int i = 0;). The two files (A and B) both have the line extern int i; in they, which means "there exist a variable called i, and someone else is allocating the space for it. Result: the compiler will link all those definitions to the same memory location, thus actually sharing the variable. If you wrote int i; in the header file each cpp file would have its i variable allocated, so each would point to a different block of memory.

Now, for the classes. If you write

class A {
public:
    int a;
    static int b;
}

you have two variables. A gets instantiated when you instantiate an object, so does not have any problems. But b... well, b is just defined, never declared. So there is no place in memory where b actually resides (the reference is undefined).

To deal with this, you have to manually declare it in a cpp file, with the syntax int A::b;. This way you are reserving some space for that variable


Your void_Menu_draw_test_man() function checks menu_redraw_required

Does your other part of the program update that variable? Do you call void_Menu_draw_test_man() from the loop() function?

It may help if you show the complete code, rather than small segments, since there are variables, such as menu_redraw_required, which are not changed anywhere in what is visible.

Note also that u8glib is no longer updated in favor of u8g2


nrf24l01 (8pin) + adapter board (10pin) oops?

To be honest, I don't see much added value for this breakout board.

First, as you mentioned, you won't be able to plug your NRF24 directly into it because the pinout is not compatible; hence, you will have to use wires for that. But you could as well use wires directly from your Arduino to the NRF24 module.

Second, regarding power (you are right, AMS1117 is a voltage regulator), the Arduino 3.3V pin is enough (50mA for UNO) to power your NRF24 as its current consumption is low (max 13.5mA as per the datasheet):

Please note these are specifications for the chip itself not for the board, which may need a bit more current, but not much more according to my own experiments.

As a side note, I have created my own very simple breakout for the NRF24 board, with just a tiny piece of stripboard, that's something you can easily do by yourself if you have the right tools (saw, cutter, soldering iron), a few pin headers and some stripboard scrap:

Last, the only utility I see with your breakout board is to be used as 3.3V supply for higher currents in future experiments.

EDIT:

as commented by @Hans-Neve, a capacitor would be useful between 3.3V and GND pins, as near the NRF24L01 board as possible, so that short consumption peaks do not impact correct function of the board. The breakout board has one (or more exactly 2: 100nF and 10uF) It is advised you add those two (at least the large 10uF cap) in your circuit. I saw some people directly soldering one cap on the pins of the NRF24 board, but if you use short enough wires to connect it, you can perfectly put this cap on a breadboard during your experiments.


MPU6050 accelerometer giving output as -1 -1. Can anyone tell the issue in the code?

I found that there was a communication problem between MPU and Arduino which I found using code given in this link http://playground.arduino.cc/Main/I2cScanner .
Then I found thought problem Must be in MPU or arduino and problem was in Arduino MCU.
So after changing the Arduino MCU it worked


What does this lines mean in RFID UID Card Reader Code?

The code formats UUID as a string of 4 hex bytes (each bytes a pair of hex digits) separated by colons.

String ID = ""

Blank the string

for (byte i = 0; i < 4; i ++){

Iterate over the four bytes of the UUID

  ID +=

Add the following to the string "ID"

(rfid.uid.uidByte[i] < 0x10 ? "0" : "") +

If the hex number to be displayed is less than 0x10, add a leading '0' to the string 'ID'. This ensures the UUIDs are all aligned and all bytes within the UUID are displayed as two hex digits (even if only one is needed). It uses the ternary condition operator, which is a compact if/then/else that can only return one of two values (rather than executing chunks of code). See https://en.wikipedia.org/wiki/%3F: for more on the ternary condition operator.

 String(rfid.uid.uidByte[i], HEX) +

Add the UUID to the string 'ID' as HEX.

   (i != 3 ? ":" : "" );

Another instance of the ternary condition operator. This one adds a colon to the string 'ID' after the hex byte unless the index is 3 (ie the last one).

 }

End of for loop.
This means that the result is nn:nn:nn:nn instead of nn:nn:n:nn: (leave off trailing colon and differing numbers of hex digits).


I have found the solution to my question so I thought to post it here so that others could also get benefit out of it. Here's the link to GPS Library for Proteus - A complete step by step tutorial on How to download GPS Library for Proteus.

From this link you can download the GPS Library which you need to add to the libraries folder of your Proteus software and you will have the GPS module in Proteus and you can design your simulation quite easily. More details are given in this link.


Is it a good idea to turn those macros into functions?

it depends.

macros are fast, but lack type checking.

functions offer type checking but incur overhead.

whether one is better than the other depends on your priorities.


EEPROM library has two functions put and get , which can help you store character array of any size, not exceeding the size of internal EEPROM size of Arduino. Please see the examples provided in the link above.

Here is a sample code to get you going.

int address = 10;
char arrayToStore[20];                    // Must be greater than the length of string.
String testString = "hello there";

testString.toCharArray(arrayToStore, testString.length()+1);  // Convert string to array.

EEPROM.put(address, arrayToStore);                 // To store data
EEPROM.get(address, arrayToStore);                 // To read data


There are lots of examples on the official Arduino website.

My advice is you follow them, not only by reading, but buy the components you need (they are cheap) and practice and see how to handle them within the Arduino environment.

Do one component at a time (led, switch, Servo, Sensor), and focus on the servo/sensors you want to use.

Than try to combine multiple components, step by step until you have your dream project ready.

Also, try not to just copy sketches (programs), but understand them. And than adapt them a bit, make variations on the component 'tests'.

I have a whole folder where I test each component with Arduino (and for some complicated components multiple sketches). Save them, and add links etc, so you can easily reference back to it.

You can use books, but there is so much information for the Arduino that this forum, the official web site and google should be enough to get you going.

(note: for the Arduino I did not use books, since as above said, there is so much information. I'm now diving in to STM32 which is more complex and a book/PDF is more convenient).


Led issue with arduino controled by raspberry pi/python

Your second condition is written wrongly. It should be this way:

elif pot >= 450 and pot <= 650:
    # do stuff

Your code should be such that only an option is chosen at any time. There should be only one 'if' condition at the top and the rest should be 'elif'.


How can I control blinking of LED while in timer function?

Your waiting loop runs much faster than once per millisecond, and even faster per second. So to get just one "event" per second, you need to detect the change of the second.
void wait_function() {
  timer_init();
  for (int second = 0; second < 30; ++second) { // 30 second wait
    // Wait for the next second
    int old_second = read_counter() / 1000;
    int new_second;
    do {
      new_second = read_counter() / 1000;
    } while (new_second == old_second);

    // A LED blinking at 1 second intervals
    PORTB ^= 1 << LED;
  }
}

However, you may think about refactoring your timer. You can put the division in the ISR, and then set a flag if a second has past. In your waiting loop you could wait for the flag, reset it, and toggle the LED.
EDIT:
If you have your (pseudo) code like this:
while (!timed_out) {
    if (timer % ticks_per_second == 0) {
        do_something();
    }
}

you will have the following erroneous behavior, presumed that the loop runs 1 million times per second and the timer increments 20000 times per second.

The timer starts at 1000, for example, and has just incremented.
The loop runs for 50 times until the timer increments to 1001.
This happens repeatedly until the timer gets 20000, which will be after (20000 - 1001) * 50 = 949950 loops.
Now the loop will run for 50 times, while the timer is still at 20000.
The condition is true on each repetition, so do_something() will be executed 50 times in a row.
Next, the timer increments to 20001, and the condition becomes false.

This is exactly what you observe: If the condition of the if becomes true, its statement will be executed repeatedly.
Because the relation between the loop's repetition frequency and the timer's frequency is not the presumed value (but similar) and even depends on the instructions executed, the state of the output is subjectively random. If the XOR instruction is executed an even number, the LED does not change, and if it is executed an odd number, the LED changes.


Delay in displaying data received from UART when used with PCINT on PIN0

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

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

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


How to use Atmega328p-PU from an Uno, on a breadboard without a crystal

You can use another IC like the 555 timers as an external oscillator.


Unspecified running error while programing WeMos D1 in wireless mode

You might have Python installed, but can you run it?

Open a command window on you PC.  (Windows button R then CMD)
Then in that type python.

If python starts up then it should be working, but I suspect you will get an error saying:

'python' is not recognized as an internal or external command, operable program or batch file.

To fix this you need to edit you path and restart the IDE.  (How you edit you path depends on your version of Windows so you would be best searching for edit environment path and your version of windows and that should come back with an answer quickly.

Of course if its Linux/mac then it could still be the same issue.


Need some more help? As I previously wrote that snippet I might as well continue until you understand how to use indexOf() and substring().

  String s = "draw(10,20,30,40)";

  // Parse the argument list
  s = s.substring(s.indexOf('(') + 1);
  s = s.substring(0, s.lastIndexOf(')'));

  // Parse comma separated arguments
  String arg[4];
  for (int i = 0; i < 3; i++) {
    int ix = s.indexOf(',');
    arg[i] = s.substring(0, ix);
    s = s.substring(ix + 1);
    Serial.println(arg[i]);
  }
  arg[3] = s;
  Serial.println(arg[3]);

There is absolutely no error handling in this. You will have to add that. You can also improve the parse of the right parenthesis. That could be added last instead.

Later in the game we will come to why using String is a bad idea and why a character buffer and the standard library functions such as strtok() is a much better solution strategy both performance and memory footprint and especially heap.

  char* s = (char*) "draw(10,20,30,40)";
  s = strtok(s, "(),");
  Serial.println(s);
  while ((s = strtok(NULL, "(),")) != NULL)
    Serial.println(s);

Maybe the simplest solution is to use sscanf(). That will also do the conversion from text to binary.

  const char* s = "draw(10,20,30,40)";
  int x, y, w, h;
  int n = sscanf(s, "draw(%d,%d,%d,%d)", &x, &y, &w, &h);
  Serial.print(F("n="));
  Serial.println(n);
  Serial.print(F("x="));
  Serial.println(x);
  Serial.print(F("y="));
  Serial.println(y);
  Serial.print(F("w="));
  Serial.println(w);
  Serial.print(F("h="));
  Serial.println(h);

Cheers!


The Arduinos are shipped without CKDIV8 enabled.

New chips without bootloader and the chips after chip erase are having CKDIV8 active.

And you can change the clock prescaller in software, but it mess up everything that depends on it. Delays, serial baud rate and USB as well.

However fuse setings are stored in boards.txt definition file. None of the bootloaders would work with default settings. They are usually compiled for 16MHz @5V and  8MHz @3.3V with xtal or resonator. But the custom boards may have much more options.


Problem connecting 10W led + Led driver Directly Arduino Uno

To operate LED using Arduino you will need a switch that can be operated using electronic switch like transistor, Mosfet or Relay board.
More easy and reliable option would be using Relay Board.

You can visit this link and can get more idea....

http://www.electroschematics.com/8975/arduino-control-relay/


The short answer: You don't.
With enough know-how, you could probably extract the executable binary from the Arduino, but the source code is not installed on the device. You would need to run a decompiler on the binary. (Or read the machine code directly.) The output of a decompiler is usually pretty ugly however, and will look quite different from the original source-code. It won't have meaningful variable names, class names, or function names, and the code structure will likely be a little different than the original source code.
EDIT:
As mckenzm pointed out in his answer, you could download the binary image from your Arduino, and then copy it onto another Arduino, but all that would let you do is to make an exact copy of the program. You wouldn't be able to modify it at all.


I wrote a simple program that used all six analog pins as digital outputs, and wired up an LED. All of the pins except A2 would blink the LED. So yes, it is fried.  Thanks.


Reading consecutive two pulse periods continuously

An interrupt off of one of the timers sounds like the easiest way to go. To get a measurement precision of, say 3% at 4ms means sampling every (4000us * .03) = 120us (8.333 KHz). If your code has little else to do, you might get away with clock-watching - micros() ticks every 4us - but you'll need to keep anything else you do between reads of micros() to under 120us, and half of that might be a good target figure.

In this answer I described a general non-blocking procedure for managing several tasks in a timely way. If you chose such a design, one task might manage the potentiometer and analog output, another one the RPM measurement, and another the LCD. The ISR would do nothing but set a flag.

The RPM & LCD tasks can run at a relatively low rate as they're intended for human consumption only. They may have to work piece-wise, though, to meet their time restrictions.


dir_t * is a pointer to a variable of type dir_t.

I don't know the API to which you refer, but the format for passing it would be:

dir_t Bass;
char dName[13];
BrowseFile.dirEntry(&Bass);
BrowseFile.dirName(&Bass, dName);
Serial.println(dName);


The following libraries are probably used:

SD Card, using a buffer of 512 bytes (see also the comment of DataFiddler below).
SSD1306 OLED library, using a buffer of 1,024 bytes
Serial, using a buffer of 128 bytes (64 for RX, 64 for TX, see comment of Majenko below)

Since there is only 2,048 bytes of SRAM in an Arduino, this leaves 384 bytes. If you actually READ a file you are already above the maximum.

Your own global variables also will consume a considerable amount of SRAM.

Than, if you execute your sketch, parameters and local variables are stored on the stack (in SRAM), so even if your program starts well, it might/will run in problems when calling functions.


Look at page 35 of winbond datasheet.
If the LED is blinking 7 times either the chip is in isp mode or in an unstated mode. This can happen after power off during erase function.
I held erase button for about 20 seconds and after that I was able to record messages.


NodeMCU 1.0 - Exception 9 `Fatal exception 9(LoadStoreAlignmentCause):`

Fatal exception 9(LoadStoreAlignmentCause):

This is caused by you (or some code you are running) attempting to read or write a 32 bit value from memory that is not "aligned" to 32 bits.  It is most often the result of trying to cast portions of a byte array (for instance a buffer received over UDP) to a 32-bit integer.  The compiler is not clever enough to know that the byte array portion you are casting isn't at a 32-bit boundary and thus doesn't know to use the 8-bit load/store instructions to access the memory.

Mapping a struct over a buffer can also have similar issues where the buffer is 8-bit aligned and the struct contains 32-bit words.

You can combat it by forcing the alignment of any buffers which you treat in such a way with the __attribute__((aligned(4)) tag:

uint8_t __attribute__((aligned(4))) buffer[128];

You can also "pack" structures to tell the compiler "These variables are mis-aligned and should not be padded to 32-bits":

struct foo {
    uint8_t bar1;
    uint32_t bar2;
} __attribute__((packed));

If in doubt, though, just pull individual bytes out of buffers (or wherever) and build up your larger integers manually with bit shifting and OR operators (<< and |), and do the reverse for filling byte buffers.


Why am I always getting 48 with serial communication?

Your Arduino sketch (snippet) is reading a byte and writing the value, not the character. The value 48 in ASCII is the character '0'.

The below loop() function will echo all the characters received.

void loop()
{
  while (Serial.available()) {
     char c = Serial.read();
     Serial.println(c);
  }
}

This could be a good starting point when debugging what is actually written from MATLAB.


Serial communication between arduino and raspberry pi works once, then stops working

"It always works if once after the code was uploaded to the arduino...."
Whenever you you reset the arduino the link between the arduino and the rasperry pi is broken momentarily thus causing the code on the raspberry pi to hang/ffreeze and not responding/ showing any valid results.

Try giving a keyboard interrupt by ( Ctrl + Z ) and restart the python script and that should work just fine!


Bouncing of a mechanical switch happens in very few milliseconds, faster than you can see a led shine.

So, for your task, you don't need any debouncing.

The description or your task lacks what should happen "if not". I assume the led should shine while both button is pressed and ldr is covered. If either button is not pressed, or ldr is lit, the led should remain off.

This one is too simple:

void loop() {
  bool ldrDark = analogRead(A0) < MAX_LDRBRIGHT;
  digitalWrite(led, ldrDark && digitalRead(buttonPin));
}

To add a delay (led goes on only when button is pressed some time) is easy as well.

const byte LED = LED_BUILTIN; // 13 on UNO

const byte BUTTON = 8;  // Button connects to GND
const byte PRESSED = LOW; // due to INPUT_PULLUP
const int DELAY = 300; // ms
bool btnState; // true = HIGH when presse

const byte LDR = A0; // LDR to 5V, Resistor to GND : Low values when dark
const int MIN_LDRBRIGHT= 420; // depends on resistor and LDR

void setup() {
   pinMode (LED, OUTPUT);
   pinMode (BUTTON, INPUT_PULLUP);
}

void loop() {
  static unsigned long lastOpen;
  if (digitalRead(BUTTON) == PRESSED) {
    if (millis() - lastOpen > DELAY)
      btnState = HIGH;
    else btnState = LOW;
  } else {
      lastOpen = millis(); // to remember last moment button was released
      btnState = LOW;
  }

  bool ldrDark = analogRead(A0) < MIN_LDRBRIGHT;

  digitalWrite(LED, ldrDark && btnState);
}


First of all, you have a while(true) in your loop, that makes no sense. The loop already loops for ever.

You are also changing the number every time the loop() is run, making it flicker. If you follow the Arduino library example, you can see they only use setNumber every so often and use refreshDisplay every time the code runs through the loop().

Also, you didn't setBrightness, which shouldn't be a problem since the library probably sets a default value, but I'd advise on including it in your code to eliminate unforeseen problems.

Try this code and let me know if it works:

#include "SevSeg.h"

SevSeg sevseg1; //Instantiate a seven segment controller object
SevSeg sevseg2;

void setup() {
  byte numDigits = 4;
  byte digitPins1[] = {2, 3, 4, 5};
  byte segmentPins1[] = {6, 7, 8, 9, 10, 11, 12, 13};
  byte digitPins2[] = {14, 15, 16};
  byte segmentPins2[] = {17, 18, 19, 20, 21, 22, 23, 24};

  sevseg1.begin(COMMON_ANODE, numDigits, digitPins1, segmentPins1);
  sevseg1.setBrightness(90);

  sevseg2.begin(COMMON_ANODE, numDigits, digitPins2, segmentPins2);
  sevseg2.setBrightness(90);
}

void loop() {
  static unsigned long timer = millis();
  static int deciSeconds = 0;

  if (millis() >= timer) {
    deciSeconds++; // 100 milliSeconds is equal to 1 deciSecond
    timer += 100;
    if (deciSeconds == 10000) { // Reset to 0 after counting for 1000 seconds.
      deciSeconds=0;
    }
    sevseg1.setNumber(deciSeconds, 1);
    sevseg2.setNumber(deciSeconds, 1);
  }

  sevseg1.refreshDisplay(); // Must run repeatedly
  sevseg2.refreshDisplay(); // Must run repeatedly
}


Nano Every clone with ATMega4808 not recognized

Probled solved, it turns out to be a Thinary Nano Every.
Instructions for installing on the Arduino IDE are on Github here: https://github.com/Thinary/ThinaryArduino


Is it possible to use Serial window for debug statements while using the hardware serial port for GPS module?

Is it possible to print the debug statements in the Serial window while the GPS module is connected to the hardware serial ports?

Yes, that works.  If you connect the Arduino TX pin 1 to the GPS RX, then everything you print to Serial goes to both the Serial Monitor window and the GPS device.

This works, because:

It's ok if you see the GPS configuration commands (if any) on the Serial Monitor window.  Your debug prints will appear after them.
The GPS device ignores anything that doesn't start with a '$' character; it ignores all your debug prints.


Powering Arduino Components with AA in Parallel and Series

Wiring 6 batteries up so it gives you both a stack of 3 and a stack of 4 is not easy, and although you can do it you shouldn't do it.  The only arrangement is this:

simulate this circuit – Schematic created using CircuitLab
(The grey link is optional and makes little difference if it's there or not).
The reason you shouldn't really do that arrangement is that you have a mismatch in your capacities, as [BAT1+BAT2] || [BAT3+BAT4] has more capacity than BAT5, so the current drawn from the 4.5V output will cause BAT5 to go flat far sooner than the others. This will then cause BAT5 to take a reverse charge as current from the other cells flows through it damaging it permanently (especially bad for rechargeable batteries as you will not be able to recharge it, but pretty nasty for alkaline batteries too).
Another consideration when running from different voltages like this is the communication between the different units. If the Arduino is running at a lower voltage the signals it sends out will be of a lower voltage, and it expects to receive signals at a lower voltage. Likewise with the HC-SR04; it will expect to receive higher voltage signals and will send out higher voltage signals. So you will require some logic level translation between the two devices to correct that mismatch in the signal voltages.
As you can see it's all starting to get a little messy now.
A much simpler solution is to keep everything at one voltage. The ideal voltage is 5V since that is the common voltage that all the devices expect to work at.
Since you are running from batteries you want efficiency. To that end you need an efficient solution for generating a stable 5V. The Arduino's built-in regulator is far from efficient, so that can be instantly discounted.
A more efficient solution is a step-down or "buck" switching regulator.  This uses PWM to rapidly turn the power on and off (before then filtering and smoothing it) to effectively convert voltage into current.
You'd run your system off a voltage higher than 5V then use a switching regulator to reduce the voltage down to 5V. Since you have 6 batteries at your disposal the logical voltage would be 6x1.5V = 9V - all 6 batteries in series:

simulate this circuit
If you're running non-rechargeable batteries then you don't need to worry about low-voltage cutoff (you shouldn't over-discharge rechargeable batteries), so this arrangement will get the most out of your battery life. Depending on the "drop out" voltage of the regulator (you can get some with a "zero drop-out bypass" mode) your batteries could get down as far as 0.8V each before the system starts to become unstable (even lower if your HC-SR04 is one of the "upgraded" ones that can run from 3V).


The "Mini Ethernet Shield" uses ENC26j60 chip. The Arduino Ethernet library is for Wiznet W5100/W5200/W5500 chips. You can't use it with ENC26j80.

With Arduino Mega I would recommend to use the UIPthernet library for ENC26j80. Other option is the EtherCard library.

The UIPEthernet library has the same API as the the Arduino Ethernet library.


Compass modules are highly susceptible to interference from ferrous deposits underground and metals in or around your robot. To correct for them, you need to shift and scale both axis.

But first, test if the sensor's X axis is working by watching the value while moving a small magnet around the sensor. If should overpower any stationary field and bias in the sensor, if it can't then there may be a problem with the sensor.

To calibrate the compass, first find the min and max value for each axis. Do this by reading all the outputs of an axis when moving the sensor in a complete circle in the environment you will be using it in. Making the robot drive in a circle when first turned on to calibrate itself is not a bad idea. Anyway, the shift is the negative average and the scale is half the difference between maximums. what really matters is that this "distance" is the same on both axis, but normalizing both is easier. For example,

float Scale, Shift, Value;
Scale =  (max-min)/2;
Shift = -(max+min)/2;
Value = float(raw+Shift)/Scale;

Once both axis are corrected the atan2() function can work properly. If you were to plot the x and y points on a graph, they should trace a unit circle at the origin.


I suspect if you were a fly you would see your LED flashing very very rapidly.

The reason is, your interrupt will constantly trigger itself over and over and over again.

Why? Because you aren't reading the incoming character from the RX buffer. And until you do the chip will keep alerting you that there is something there to read by triggering the interrupt.


real-time reading of a quadrature encoder at full resolution with only one interrupt on ATmega328

This is just a partial, rushed answer.

You should be able to get a significant speed-up if you define your own
ISR for handling the interrupt, as in:

ISR(INT1_vect) { ... }

The Arduino way of using interrupts is instead

void trigger() { ...}

void setup() {
    attachInterrupt(int_number, trigger, CHANGE);
    ...
}

but this is slow, as it involves the ISR provided by the Arduino core,
which has to locate and call your interrupt handler. The way you wrote
the handler is wrong: either you define a regular function, without the
ISR macro, and go the Arduino way, or you go the plain AVR path and
define the ISR yourself, which should be named INTERRUPT_NAME_vect, in
which case you don't use attachInterrupt(). The way you did it is
probably the slowest you can get, as the compiler will needlessly add an
ISR-type prologue and epilogue to your handler.

As for the maximum frequency, that's hard to assess without testing, but
you may get some idea by reading this answer on interrupt
latency.

Edit: As I stated in my first comment to the question, a pin change
interrupt can be used instead of an external logic gate. Here is how to
do it.

First, one should look at the Arduino Uno pinout and see that:

digital 4 = PD4 = PCINT20
digital 5 = PD5 = PCINT21

Both pins are tied to the pin change interrupt request 2 (PCINT2_vect).
This interrupt can be configured in setup() as follows:

PCMSK2 = _BV(PCINT20)   // enable interrupt on pin PCINT20 = PD4
       | _BV(PCINT21);  // enable interrupt on pin PCINT21 = PD5
PCIFR  = _BV(PCIF2);    // clear interrupt flag
PCICR  = _BV(PCIE2);    // enable pin change interrupt request 2

Now, the interrupt will fire on every change of the logic levels of
inputs 4 and 5.

Then, in the ISR, the whole port D can be read in a single cycle by
just evaluating the corresponding pin input register, i.e. PIND. With
some shifting and masking, one can get a phase between 0 and 3
(the count is in Gray code: 0, 1, 3, 2, 0...). From the previous and the
current phase, one can compute the change that needs to be applied to
the counter:

// Handle pin change interrupt request 2.
ISR(PCINT2_vect) {
    static uint8_t previous_phase;
    uint8_t phase = (PIND >> 4) & 0x03;  // read input pins
    counter += encoder_delta(previous_phase, phase);
    previous_phase = phase;
}

The implementation of encoder_delta() is left as an exercise to the
reader. ;-)


Sending SMS once with arduino GPRS SIM900 if an input is HIGH

You need to attach an interrupt to the pin which is getting HIGH and then the function connected to the interrupt will have the code to send the SMS.

Just init the GPRS with connecting to the network then just wait for the interrupt to send anything.


I don't see any reason not to use Arduino in an industrial, engineering, or laboratory environment, if it meets your needs and does the job well. It is highly recommended, however, that you provide some sort of pin protection to keep industrial noise or voltage spikes from frying pins. Minimum pin protection could consist of using current-limiting resistors (or better yet, the other, more robust techniques shown here) on pins used for output and input signals. Optical isolation is also a good option, especially if potentially dangerous voltages are being used. Lastly, after you prototype and test your Arduino setup you should solder the wires to the Arduino and provide a protective case. You don't want to accidentally fry the Arduino or a pin via accidental static discharge (hence the case, and pin protection above), and you don't want jumper wires vibrating loose and connections slowly oxidizing over time and loosing electrical connectivity in any type of industrial or laboratory application that is expected to be used regularly (hence replacing your jumper wires with soldered wires). Shields, however, are prob. ok for low-humidity and room-temperature environments, as they are generally much more secure and solidly connected than individual jumper wires.

Note that you can solder wires to any Arduino, even the Uno, Leonardo, or Mega, for example, simply by soldering to the exposed portions of the pins on the bottom of the board. You can also cut off and desolder the female headers and either solder directly to the holes, or solder on male headers that you then solder to other PCBs. I especially like the Arduino Nano, Pro Mini, and Micro since they are small, have exposed holes or male pin headers, and can easily be soldered onto a professionally-manufactured circuit board or cheap protoboard, for better mounting in a final application. Keep reading below for more details on this.

I am an aerospace research engineer and use Arduino in my line of work regularly to solve problems. Here are some examples of current applications in use today, that I implemented, that are based on and using Arduino boards:

sensorless brushless motor RPM sensor, motor commander, and data acquisition device for bench-top testing
linear actuator closed-loop controller (linear stepping resolution is 0.01mm [10um], full moving range is 0 to 15mm); the Arduino commands the actuator driver board via a custom PWM signal using the Timer1 library (http://playground.arduino.cc/code/timer1); position is read via a custom quadrature encoder reader algorithm on the arduino; the actuator is used for very precise aiming of certain instruments; the $30 Arduino is taking the place of a $500 board that the actuator manufacturer makes, and the Arduino gives us much more functionality than the $500 board would give us. The Arduino and actuator will be used to precisely aim a laser for experiments in a wind tunnel.
flight controller interfaces between MATLAB and off-the-shelf Radio Control transmitter (read and write RC PWM & PPM communication signals)
Professional film studio communication interface on robotic, drivable camera system (info sheet & video).

Those are just a few cases. If it works, do it.  Once you prototype with a solderless breadboard, however, it is recommended that you at least hand-solder the final configuration to a permanent prototyping board, to make it more durable and noise-resistant (ie--primarily: so that it will have solid connections that can't corrode, break, come apart, or vibrate free easily).

Here's a soldering article I wrote (http://electricrcaircraftguy.blogspot.com/2014/08/recommended-soldering-kit.html#.VP-JCPzF-So). see the links at the bottom for recommended soldering tutorials. The one about how to make "solder tracks" was especially useful to me once I got past the breadboard stage and started prototyping things on double-sided perf board.

Here are some double-sided prototyping boards (or "perf boards") to look into once you get to this stage: (Ebay search for "double sided pcb") http://www.ebay.com/sch/i.html?_from=R40&ghostText=&_sacat=0&_nkw=double+sided+pcb&rt=nc&LH_BIN=1 -- get the ones with all the little holes in them. You can put the whole thing in a plastic case if you want too. You can permanently solder an Arduino (esp. the Nanos or Micros more easily) to one of these perf boards.

Here's another example of double-sized perf board. (image source: http://www.elecfreaks.com/store/doublesided-protoboard-8cm-x-12cm-p-410.html)

Professional PCBs:

If you need to make more than a few of some device, hand-soldering wires and pieces all over a perfboard can get to be VERY tedious. In this case, you need to design a more professional PCB with custom traces and pads and layout and all for your project. If you don't have PCB-designing skills yet with a professional tool like Eagle or KiCad, you can use Fritzing (http://fritzing.org/home/) to design a PCB, and then send it off to a company like OshPark (https://oshpark.com/) for high-quality, reasonably-priced, low-quantity US-based manufacturing---or send it off to the Fritzing Fab lab in Germany for high-quality PCB manufacturing that supports the Fritzing project. Lastly, for a couple really inexpensive Chinese options, look at ITEAD Studio and Seeedstudio. Fritzing and any other PCB CAD software tool can output the necessary Gerber files for manufacturing.

Quick tip: when designing a PCB, don't use any 90 deg corners for your traces. They can act as antennas (sending or receiving) and cause electromagnetic (including radio) interference and noise. Use multiple 45 deg edges and corners instead.

Once you get your boards back, solder your Arduino to them, and solder any extra parts or hardware to them you need as well. Now you have quite a professional product, even if it has an Arduino soldered right to it.

Summary:

In summary, yes I think Arduino is great. Without it, I wouldn't know how to even blink an LED or load a single code to a microcontroller, because getting into using microcontrollers was just to enigmatic, difficult, and complicated for someone not professionally trained in it, such as an Aeronautical engineer like myself.  With Arduino, however, I learned to build up my skills and solve real-world problems in professional environments.

I am very grateful to Massimo Banzi, David A. Mellis, and others who have made Arduino possible. It has changed my life and my ability to be useful in this life.  My favorite part about it is that even though it is a tool meant to get the non-programmer or lay-person to do basic stuff like blink a light using poorly-written blocking code, it has opened up my world beyond what I ever imagined before, and it is a fully-capable microcontroller that doesn't permanently hide away the low-level stuff. The low-level AVR functions, registers, etc are ALL STILL THERE AND ACCESSIBLE once you get to a level where you need them!

Cheers,
Gabriel Staples

PS: To see many of the very helpful links which I've referenced as I've built up my Arduino and ATmega328 microcontroller skillset, please see this article here, esp. all of the links at the bottom: http://electricrcaircraftguy.blogspot.com/2014/01/the-power-of-arduino.html


Motor shield not providing enough current to 2 12V DC fans

I kinda doubt that that fan will actually draw 3A. You could probably get away with using your shield--just measure the fan current draw by directly connecting it up to a 12V supply and measuring with a multimeter.

If it actually draws 3A, any of these sounds like a decent idea:

https://www.amazon.com/WGCD-Controller-Module-Stepper-Arduino/dp/B06X9D1PR9/ref=sr_1_4?s=electronics&ie=UTF8&qid=1523692716&sr=1-4&keywords=arduino+h+bridge

https://www.amazon.com/Diymall-Module-Stepper-Modules-Arduino/dp/B00NJOTBOK/ref=sr_1_8?s=electronics&ie=UTF8&qid=1523692716&sr=1-8&keywords=arduino+h+bridge

https://www.amazon.com/SainSmart-Stepper-Controller-Mega2560-Duemilanove/dp/B00AJGM37I/ref=sr_1_11?s=electronics&ie=UTF8&qid=1523692716&sr=1-11&keywords=arduino+h+bridge


TSX0108 logic level converter not working

When the output-enable(OE) input is low, all outputs are placed in the high-impedance (Hi-Z) state.  You must connect the OE pin to logic high to enable the outputs.


How would i capture and split serial data?

This string is actually fairly easy to split up, because everything is separated by commas nice and regularly.

Assuming you have the string in a char array (aka a C string) and not a String object (I and most other programmers abhor the String class) you can use the function strtok() to split the string up into parts.

So you have the string:

char string[] = "<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>";

The function strtok() takes, on its first call, the string you want to split and the delimiter that you want to split on.  It returns a pointer to the chunk:

char *alarm = strtok(string, ",");

alarm now contains <Alarm and strtok() moves its internal pointer to point at the next character, so it sees the string as MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>

With the next and subsequent calls to strtok() you don't give it the string, or it will reset its internal pointer.  You just pass it NULL and it gives you the next block:

char *mposX = strtok(NULL, ",");
char *mposY = strtok(NULL, ",");
char *mposZ = strtok(NULL, ",");
char *wposX = strtok(NULL, ",");
char *wposY = strtok(NULL, ",");
char *wposZ = strtok(NULL, ">");

Note that I changed the delimiter on the last one to > so it chops off that extra character that we don't want (and there is no , after the last part).

So now you have 7 variables that point to chunks of the string, which has internally been chopped up and modified into individual substrings:

*alarm = "<Alarm";
*mposX = "MPos:0.000";
*mposY = "0.000";
*mposZ = "0.000";
*wposX = "WPos:0.000";
*wposY = "0.000";
*wposZ = "0.000";

So now we can clean up the three entries that have extra stuff in them, and that is a simple as adding an offset value to the pointers we have:

alarm += 1;
mposX += 5;
wposX += 5;

Our list of pointers now looks like this:

*alarm = "Alarm";
*mposX = "0.000";
*mposY = "0.000";
*mposZ = "0.000";
*wposX = "0.000";
*wposY = "0.000";
*wposZ = "0.000";

The position variables can now be passed through strtod() to convert them to float values:

float mx = strtod(mposX, NULL);
float my = strtod(mposY, NULL);
float mz = strtod(mposZ, NULL);
float wx = strtod(wposX, NULL);
float wy = strtod(wposY, NULL);
float wz = strtod(wposZ, NULL);

You can do different things depending on the content of the *alarm string by using strcmp():

if (strcmp(alarm, "Busy") == 0) {
    // Something to do when Busy
}

etc.

Or you can just use it to print the content to the LCD.


how to use keypad button multiple integer value input

When you use the keypad library, there is a command to read a key:

 myKeypad.getKey();

Store these keys in a (string) buffer, and after a certain key is pressed (e.g. #), parse the string buffer to retrieve the integer (with the c function atoi, see here for a description).


Atmel Studio is a windows only product.
The only way to run it on linux is in a virtual machine running windows.


Efficient algorithm/data structure to calculate moving averages

If your data has low standard deviation, then one method would be to sum values over the window, and then keep subtracting the mean from the sum, while adding the new value.

This would work well if there are no outliers, thereby leading to the aggregate error tending to zero over time.

//Pseudocode

count=0
while new_reading and count<7:
    sum += new_reading        //Calculate the sum of first 7 values
    count++

while new_reading:            //Loop till new readings available
    avg = sum / 7             //Calculate average
    sum -= avg                //Subtract average from sum
    sum += new_reading        //Add next reading to sum
    print avg


The IRF540 is not suitable to be controlled by a 3.3V device because it has a gate-source-threshold voltage of 2-4V (that's the voltage at which the mosfet starts to conduct, but you need to be above that voltage). While this worked at 5V logic level on the arduino, the 3.3V are not enough to make the mosfet switch entirely.

A suitable mosfet has a threshold voltage below 1V. Also for a fan, you eon't need a big mosfet rated for 30A, a tiny one will do it.


Arduino gets stuck: battery powered, wireless, dc motor drive

My guess is that your motors are drawing too much current and the voltage from your battery is dropping too low for the voltage regulator on the Arduino. Looking at the data sheet, the L293D will provide up to 600-mA for up to 2 motors at a time. That's up to 1.2 amps, a whole lot of current. I would suggest trying to power your arduino from a separate 9 volt battery as an experiment.


Arduino works bad when powered by 9V battery

I got a fresh 9 V out of a packet and measured it.

 9.58 volts

Now with a load of 500 mA (which you quite likely would get with a robot) it dropped to:

 7.4 volts

With a load of 750 mA the voltage dropped to 6.6 V which is below what you are supposed to supply via the power jack.

And that was with a fresh battery, testing for a few seconds.

Those 9 V batteries are just not designed to drive motors.

I suggest a somewhat heavier-duty battery, like 5 x AA batteries, at least for the robot part.


Arduino , python , pyfirmata , standard firmata

No, not as far as I know. The firmata protocol does not include a command to set the analog reference. However, you can of course modify the firmata firmware to your liking. In the simplest case, just add the appropriate command to the setup() function of the main .ino.


Connecting the cathode of a diode to the output of a multiplexer

The code you have posted should loop through the 8 possible MUX in/out pins (Y0...Y7) connecting one at a time to pin 3.
Assuming your Y0 through Y7 are each connected to a pin on your "do something" block, the mux should connect each of the 7 pins on your "do something" to Z.
One problem I see is that your code changes the pin select values on the MUX while the MUX is enabled. As you execute your for(int i=0;i<3;i++) loop and toggle the different select bits to S0...S2, the MUX will connect different Y0...Y7 pins to Z, until it settles on the final set of values for S0...S2. You should really set inhibit_pin to HIGH (disabling the mux before entering your for(int i=0;i<3;i++) loop, and then set it to LOW again at the end of the i loop and before the delay. (to re-enable the MUX at the now-completely-selected pin.)
Your description is a little hard to follow, but it sounds like that is what you want.
If you want each pin to be connected for 3 seconds, then not connected to any pin for .1 seconds before moving on to the next pin, you might rewrite your loop like this:
void loop() {
  // looping through all 8 LEDs
  for (int j=0;j<8;j++){

    // disable the mux while selecting a pin
    digitalWrite(inhibit_pin,HIGH);

    // select a MUX pin
    for(int i=0;i<3;i++){
      digitalWrite(outputs[i],bitRead(j,i));
    }
    // re-enable the mux now that we've selected a pin
    digitalWrite(inhibit_pin,LOW);

    delay(3000); // leave the pin active for 3 seconds.

    // disable the mux for .1 seconds
    digitalWrite(inhibit_pin,HIGH);
    delay(100);
  }
}


Arduino not running the sketch with external power supply of 9v, but runs the program when connected to pc

TX LED is blinking because of communication (indicating data transmit via serial). It will not blink if there are no communication from Arduino through USB cable.

For simple observation, use LED_BUILTIN pin. Its a build in-LED indicator on Arduino.

pinMode(LED_BUILTIN, OUTPUT);

then

digitalWrite(LED_BUILTIN, HIGH);
delay(500)
digitalWrite(LED_BUILTIN, LOW);
delay(500)

Arduino fail on external power supply is usually because of voltage drop or your system draw too much current.


Help needed understanding Due performance

What does the Arduino library do to make loop() so inefficient?

Alot.  For a start it's a function, so it has to push registers onto the stack before it runs, and pop them off afterwards.  Secondly there is the "serial event" system outside the loop.  In main.cpp in the core you can see how loop is called:

setup();

for (;;)
{
    loop();
    if (serialEventRun) serialEventRun();
}

  Is there any harm in keeping all your code inside an infinite loop in setup() and never returning out of it?

If you don't use serial events, no harm whatsoever.

  Why would I sometimes see the number of increments being 2 or 3 times higher than usual? Could the counter be getting cached (despite being marked as volatile) and not reset properly? If so, how can I prevent this?

My guess is the operations you are using are not atomic.  This is, the interrupt is able to be fired right in the middle of doing the series of instructions that perform the increment. The temporary registers end up not being the same as they were at the start of the operation, and consequently the value is corrupted.  You should wrap the increment in a critical section (i.e., disable interrupts before it, and enable them afterwards).

To better analyse the speed of execution you can look at the generated assembly code of your program.  If we look at the disassembled main() function for the bit where it loops you can get this:

80596:  f7ff fe05   bl  801a4 <loop>
8059a:  4b04        ldr r3, [pc, #16]   ; (805ac <main+0x30>)
8059c:  2b00        cmp r3, #0
8059e:  d0fa        beq.n   80596 <main+0x1a>
805a0:  f7ff feec   bl  8037c <_Z14serialEventRunv>
805a4:  e7f7        b.n 80596 <main+0x1a>
805a6:  bf00        nop

loop() consists of this:

801a4:  4b02        ldr r3, [pc, #8]    ; (801b0 <loop+0xc>)
801a6:  681a        ldr r2, [r3, #0]
801a8:  3201        adds    r2, #1
801aa:  601a        str r2, [r3, #0]
801ac:  4770        bx  lr
801ae:  bf00        nop

If we feed that into main() where it calls loop() the finished code looks like:

80596:  f7ff fe05   bl  801a4 <loop>
801a4:  4b02        ldr r3, [pc, #8]    ; (801b0 <loop+0xc>)
801a6:  681a        ldr r2, [r3, #0]
801a8:  3201        adds    r2, #1
801aa:  601a        str r2, [r3, #0]
801ac:  4770        bx  lr
801ae:  bf00        nop
8059a:  4b04        ldr r3, [pc, #16]   ; (805ac <main+0x30>)
8059c:  2b00        cmp r3, #0
8059e:  d0fa        beq.n   80596 <main+0x1a>
805a0:  f7ff feec   bl  8037c <_Z14serialEventRunv>
805a4:  e7f7        b.n 80596 <main+0x1a>
805a6:  bf00        nop

So that is what gets executed for every single iteration of loop().  If we (incorrectly) assume that each instruction takes 1 clock tick, that's 13 ticks.  84,000,000 / 13 = ~6.4 million loops per second.

Now - if we map the instructions against actually how many clock cycles they take, we can get a clearer picture:

bl                  1+P  (P = 1 to 3)
ldr (pc relative)   2
ldr (word)          2
adds                1
str (word)          2
bx                  1+P  (P = 1 to 3)
nop                 1
ldr (pc relative)   2
cmp                 1
beq.n               1 or 1+P (P = 1 to 3)
bl                  1+P (Only if serial event runs)
b.n                 1 or 1+P (P = 1 to 3)
nop                 1

So taking a worst case scenario where P = 3 (pipeline re-fill clock counts, that is), and no serial event running, we can calculate a total number of clock cycles of 4+2+2+1+2+4+1+2+1+4+0+4+1 = 28.

84,000,000 / 28 = 3,000,000 loops per second.

But hang on - that's still much more than you're seeing.  That's because you're still only looking at the small picture.  You're looking at just your sketch and forgetting what else there is going on.

Every millisecond the SysTick_Handler() gets called which does various tasks, including calling the TimeTick_Increment() routine to deal with millis().  That's 1,000 times per second, and that eats into your processing time somewhat.

Another important point is it can't be incrementing while you're running your interrupt.  The more you do in your interrupt (and using serial is a very heavy-weight thing to do in an interrupt) the less of your 1-second slice you get for doing your incrementing.

As an experiment, why not try disabling all the interrupts except just the one you are using for your timer and see how it changes the value.


How to make a 5-volt relay work with NodeMCU?

I have several of these modules. They have an optional opto-isolator built-in, but you have to remove the jumper to use it.

Connect your GPIO trigger as you have it
Run the relay's Vcc and Gnd pins to the MCU, not the power plug.
connect the power plug's +5v to the left-most pin, where the jumper once stood: JDVcc
connect the power plug ground to the MCU or the open common Gnd on the left-group of pins.

Now your relay coil(s) will be powered by the 5v plug, but the relay's logic and control are handled by the MCU.