text:
How to unify all RPS reading in one function?
Want to unify rps reading in one function.
However, it shows incorrect values.
when it is reading for one it works fine.
Following is the code. Appreciate for your help.
float rps[4] = {0.00, 0.00, 0.00, 0.00};
long int PRINT_PERIOD = 1000;
long int lastTimePrinted = 0;

void setup() {
    Serial.begin(9600);
    DDRD &= ~_BV(7); // pinMode(7, INPUT);     // rps_1
    DDRB &= ~_BV(0); // pinMode(8, INPUT);     // rps_2
    DDRC &= ~_BV(1); // pinMode(A1, INPUT);    // rps_3
    DDRD &= ~_BV(2); // pinMode(2, INPUT);     // rps_4
}

float rps_out(int k) {
    static int lastReedState;
    static unsigned long lastTransition;
    static float rps_result;
    int reedState;
    unsigned long now;
    unsigned long revolutionTime;

    if (k == 1)    reedState = (PIND & _BV (7)) == 0; // digitalRead(7);
    else if (k==2) reedState = (PINB & _BV (0)) == 0; // digitalRead(8);
    else if (k==3) reedState = (PINC & _BV (1)) == 0; // digitalRead(A1);
    else if (k==4) reedState = (PIND & _BV (2)) == 0; // digitalRead(2);

    // HIGH LOW measuring the low period
    // LOW HIGH measuring the high period
    // On a rising transition of the reed switch:
    if (reedState == HIGH && lastReedState == LOW) {

        // Compute time since last valid transition.
        now = micros();
        revolutionTime = now - lastTransition;    // measuring the High period
         rps_result = 1.00 / (12.00*revolutionTime) *1000000.00;  // 12 is rotary encoders resolution
        // Remember this transition.
        lastTransition = now;
    }

    // Remember last state.
    lastReedState = reedState;

    return rps_result;
}

void loop() {
    rps[0] = rps_out(1);
    rps[1] = rps_out(2);
    rps[2] = rps_out(3);
    rps[3] = rps_out(4);

    if (millis() - lastTimePrinted >= PRINT_PERIOD) {
        Serial.println(rps[0]);
        Serial.print(',');
        Serial.println(rps[1]);
        Serial.print(',');
        Serial.print(rps[2]);
        Serial.print(',');
        Serial.println(rps[3]);
        lastTimePrinted = millis();
    }
}

worked code except for rps[3] at the beginning. it shows rps[3] = 672.04
float rps[4];
long int PRINT_PERIOD = 100;
long int lastTimePrinted = 0;
int lastReedState[4];
unsigned long lastTransition[4];
int reedState[4];
unsigned long now[4];
float rps_result[4];
unsigned long revolutionTime[4];

void setup(){

 Serial.begin(9600);

 DDRD &= ~_BV (7); // pinMode (7, INPUT);       // rps_1
 DDRB &= ~_BV (0); // pinMode (8, INPUT);       // rps_2
 DDRC &= ~_BV (1); // pinMode (A1, INPUT);      //  rps_3
 DDRD &= ~_BV (2); // pinMode (2, INPUT);       //  rps_4

}

float rps_out(int k){

    //static int lastReedState;
    //static unsigned long lastTransition;
    //static float rps_result;
    //float rps_result;
    //int reedState;
    //unsigned long now;
    //unsigned long revolutionTime;

   if ( k == 0 )     reedState[0] = (PIND & _BV (7)) == 0; // digitalRead (7);
   else if ( k==1 )  reedState[1] = (PINB & _BV (0)) == 0; // digitalRead (8);
   else if ( k==2 )  reedState[2] = (PINC & _BV (1)) == 0; // digitalRead (A1);
   else if ( k==3 )  reedState[3] = (PIND & _BV (2)) == 0; // digitalRead (2);

    // On a rising transition of the reed switch:
    if (reedState[k] == HIGH && lastReedState[k] == LOW) {                   // HIGH  LOW   measuring the low period    // LOW HIGH measuring the high period
        // Compute time since last valid transition.
        //unsigned long now = micros();
        //unsigned long revolutionTime = now - lastTransition;       // measuring the High period
         now[k] = micros();
         revolutionTime[k] = now[k] - lastTransition[k];       // measuring the High period
        // Compute the rps

        if(revolutionTime[k] == 0 ) rps_result[k] = 0.00;     // avoid deviding by zero

        else rps_result[k] = 1.00 / (12.00*revolutionTime[k]) *1000000.00;  // 12 is rotary encoders resolution

        // Remember this transition.
        lastTransition[k] = now[k];

    }

    // Remember last state.
    lastReedState[k] = reedState[k];

    return rps_result[k];

}

void loop() {

   rps[0] = rps_out(0);
   rps[1] = rps_out(1);
   rps[2] = rps_out(2);
   rps[3] = rps_out(3);

    if (millis() - lastTimePrinted >= PRINT_PERIOD) {

     Serial.print(rps[0]);
     Serial.print(',');
     Serial.print(rps[1]);
     Serial.print(',');
     Serial.print(rps[2]);
     Serial.print(',');
     Serial.println(rps[3]);

      lastTimePrinted = millis();

     }

}

Remember your question Getting different results from function? Same problem here: rps_out() has state (its static variables), and the state should be stored independently for each channel. Same solutions as in the answers you already got. Oh, and you forgot to actually compute rps_result.

ok, I added rps_result calculation.

So you mean I have to make rps_result as an array?

@edgar could  you please explain in detail which one should be as global array?

I have done it, except for the last one rps[3]. it is  supposed to be rps[3].=0.00 at the beginning. However, it shows  rps[3] = 672.04.  What is wrong?

Any help please.

I got stuck with the initial value of the last one.

I only see a couple of small issues with your updated code: 1) lastTimePrinted and PRINT_PERIOD should be unsigned, PRINT_PERIOD should be const also. 2) reedState, now and revolutionTime don't need to be stored between calls to rps_out(): they can be local scalar (i.e. not array) variables of rps_out(). However, none of these are critical, and I see no reason why channel 3 should behave differently than the others. The reason may well be outside the code, in the hardware.

Your problem is that you have one set of (static) state information that you are trying to use for all your inputs. That's never going to work. You need separate state information for each and every input.
There's numerous ways of doing that:

The traditional C library "re-entrant" style. This involves passing pointers to any state variables into your function. The caller is responsible for creating and managing these variables and passing the pointers when the function is called. This is messy but pretty much completely portable across systems since it doesn't rely on any C++ facilities.
Similar to option 1 but grouping your different state variables into a struct to make things cleaner.
Global arrays - have a global array (maybe of structs as in option 2) to store the state information and pass the slice number to your function.
The OOP (C++) way - create a class with all the state variables and functions within it then instantiate a new object for each input. This is by far the cleanest and most self contained way but does require knowledge of creating and using classes.

Of the four options I would most likely choose option 4:
class RPS {
    private:
        uint8_t _pin;
        uint8_t _lastReedState;
        uint32_t _lastTransitionTime;
        uint32_t _rps;

    public:
        RPS(uint8_t pin) : _pin(pin) {}
        void begin() {
            pinMode(_pin, INPUT);
            _lastReedState = digitalRead(_pin);
            _lastTransitionTime = millis();
            _rps = 0;
        }
        void calc() {
            uint8_t reedState = digitalRead(_pin);
            if (reedState != _lastReedState) {
                uint32_t now = millis();
                _lastReedState = reedState;
                if (reedState == HIGH) {
                    uint32_t diff = now - _lastTransitionTime;
                    if (diff == 0) {
                        _rps = 0; // Avoid divide by zero
                    } else {
                        _rps = 1000 / diff;
                    }
                }
                _lastTransitionTime = now;
            }
        }
        uint32_t get() {
            return _rps;
        }
};

RPS rps1(1);
RPS rps2(2);

#define PRINT_PERIOD 1000

void setup() {
    rps1.begin();
    rps2.begin();
}
void loop() {
    static uint32_t lastTimePrinted = 0;

    rps1.calc();
    rps2.calc();

    if (millis() - lastTimePrinted >= PRINT_PERIOD) {
        lastTimePrinted = millis();
        Serial.print("RPS 1: ");
        Serial.println(rps1.get());
        Serial.print("RPS 2: ");
        Serial.println(rps2.get());
    }
}

(note: Untested. It may not even compile)

Your get() method has to be called as often as possible in order to get an accurate reading of the transition time, but your loop() only calls it one per second. You may want to split this method into update() (takes the reading, to be called often) and read() (just returns _rps). You may also want to use micros() instead of millis(), for better resolution.

Good point. Fixing now.

As to millis/micros, that's up to the end user to choose. This just gives a framework for them to build on to demonstrate the concept. If you feel the need to use microseconds then you won't be wanting to use micros() since it is only a rough guestimate at the best of times. Using IC would be preferable.


text:
How do I see the command line equivalent of clicking Verify?
I am using the ESP8266 board manager. I want to see how Arduino IDE compiles my code once I click Verify.
Why do I want to do this?
I am trying to integrate a C library for which there is now Arduino library package available. So I have to integrate it from source. I want to be able to specify custom -I, -L  and -l flags when I compile my code.

Turn on the verbose compiler settings in the preferences.

In the Arduino IDE switch on File>Preferences>Upload erbose and Compile Verbose
When you build you will see all the compiler commands
The verify is often a -v param in the command
You will find the esp8266 platform.txt in a location such as c:\users\[name]\appdata\local\arduino15\packages\esp8266...
The platform.txt contains all the compiler switches, the boards.txt in the same location can also contain board specific switches.
You can not specify different switches for different files in a compilation but you could compile your code into an archive then force it into the build process. Not sure if that is practical or not.

source: Stack Exchange

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

sort: votes


text:
Understanding Nikon modified version of SPI
I am trying to use this library to connect a Nikon lens to an Arduino.
https://lainy.github.io/NikonLens/classlain_1_1t_nikon_lens.html
I'm finding it very hard to understand the correct wiring.

Connections are as follows (with Arduino Uno pin numbers):
SS (10) is unused.
SCK (13) is connected directly to lens SCLK.
MISO (12) is connected to the lens Data line, which must be pulled
  high.
MOSI (11) drives the lens Data line through a transistor,
  open-collector. So: MOSI -> Base, Data -> Collector, GND -> Emitter
handshakePin_In is connected directly to lens H/S
handshakePin_Out drives lens H/S through a transistor, open-collector.

I would like help to understand this.

drives the lens Data line through a transistor, open-collector. So:
  MOSI -> Base, Data -> Collector, GND -> Emitter

It uses a variant of SPI interface. I'm just finding it hard to wrap my mind around it.

It is simply a way of splitting a single-pin read/write function between two pins. It's easier to visualise with schematics:

simulate this circuit – Schematic created using CircuitLab
Under idle conditions the resistor pulls the data signal high. When the lens wants to transmit the open-collector output (represented by a transistor here) either pulls the data line low (for a 0) or releases it to be pulled up by the resistor (for a 1).
The Arduino reads that data in through the data in pin.
When the Arduino wants to transmit it does the same thing, but the "open collector" is external in the form of the transistor. It drives the transistor using the data output pin to get it to pull the data line low for a 0, or release it to be pulled up by the resistor for a 1.
This is exactly the same way (on an electrical level) that I2C works and studying that protocol can help you to understand what is going on here.

great answer! Can you describe how the correct wiring would look like for interfacing Arduino with a Nikon camera? I.e. Arduino with MISO and MOSI pins acting as an SPI slave and Nikon camera with a single data pin as master?

authors: Александр Иванов

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


text:
Best way to detect tilt using MPU 6050
I want to make a gesture controlled car using this IMU.. What is the simplest way to detect tilts? I've seen many programs on the Internet that calculate the angles but is this really necessary?
Why can't we just get components of acceleration in the x, y plane and then detect tilts..Pls tell me how to do this!

Well suppose you have a starting position, let's say 0 degrees, then once you detect and angle change, let's say 10 degrees, you know that there is a tilt of 10 degrees on one of the 3 axies.
The MPU6050 is a 6DOF, meaning 6 Degrees Of Freedom. This means that it can detect acceleration on axis: x, y, and z and it can detect gyro angles on axis: yaw, pitch, and roll.
For the best accuracy, use a mix of both acceleration and the gyroscope. This is the best way to calculate position. Heck, the Apollo space program used a gyro and accelerometer to navigate from planet Earth to the Moon.

How could I just use accelerometer readings to detect the tilt??

You can't, you mainly use a gyroscope for tilt detection, but, in some cases where super accuracy is necesssary, a hybrid of both is great. It is very complex so I don't really want to go in much detail. The MPU6050 has a gyro, why not use it?


text:
Global variables use to much space in the dynamic memory
I use two simple libraries (see 1, 2) I found online for my code on the Arduino Uno, unfortunately I also use ROS and all those libraries take away to much space, when I compile my code I get this error:
Global variables use 2,112 bytes (103%) of dynamic memory, leaving -64 bytes for local variables. Maximum is 2,048 bytes.

I shortened my Strings, but it was not enough. How can I change the code in the libraries to achieve less used memory?
I think I don't understand the concept of global variables completely. For example I changed all double variables in the libraries to float variables, but it did not change dynamic memory use at all. How can I use less memory?

Did you placed your string literals into the flash memory?

I shortened them down to 1 letter, to see how far it reduces the size, but putting it into flash memory won't solve the problem, since it is not enough.

Well, then you should provide your code so we can try it...

I checked and about 75% of global variables are already used by the libraries I use. Since they are open source I was hopping to change those. They are provided in the links I gave in my question.

A very generic description: Variables that hang around (global, static, ect) are assigned their own memory location in RAM, variables that have limited scope are temporarily assigned a memory location in the RAM in an area called the stack & variables that never change can be put into program memory.  On an embedded processor this usually means putting variable into flash.

This is "off the cuff" advice, hence it is only a comment, not an answer, but, if you are hurting for memory why not switch to an ARM based Arduino.  Many ARM based Arduino's have much more memory than, say, an Uno.

How many of those objects do you instanciate? The most obvious candidate for memory saving is double lastInputs[100]; in class PID_ATune. It takes 400 bytes. If you shorten this array, make sure you don't access it out of bonds.

@EdgarBonet I reduced the number to 80, it helped, thank you! Why does it not change memory consumption if I change the double to float?

@Jonas, because on arduino, double and float have the same size : https://www.arduino.cc/en/Reference/Float or https://www.arduino.cc/en/Reference/Double

The first library defines a class PID_ATune which contains a lot of members, including an array of 100 double, i.e. 400 bytes for each instance of PID_ATune. Not sure so many double are needed there, but you could first try to reduce this number.

have you solved this, I am facing the same exact issue! as I am currently using the autotune library ! and can't optimize the sample code! please help

Unfortunately I could not solve the issue. I think I moved to a larger microcontroller that time. Sorry. You could try to use the source code of the autotune library directly and fine tune it?

When you write a program, some memory can be determined in compilation time, due to it's predefinition, (float and double in Arduino - not Due model - use 4 bytes each - in Due, double uses 8 bytes for 64 bit precision).
But there is some memory that only can be known at runtime; where we are talking about objects (or arrays determined by user input). In these cases, programs need to dynamically allocate memory, for which the C++ language integrates the operators new and delete. More info at: Dynamic memory.
You should control the creation of objects and arrays (those are created with new and then deleted with delete).
If your requirements are greater than the resources of any Arduino (except Arduino Due), you should change to the Due model, which has more memory space and computing power (but changes the 5 V to 3.3 V, be careful).

There is also the Mega 2560, which has the same architecture as the Uno (AVR), but 4 times as much RAM.

@jonas I had a similar problem not quite exceeding the limit.  One item you can do is move the strings to Flash.
<pgmspace.h> there is the definition of PSTR which will place the literal in flash
the patternname, which we normaly just use strcpy, we need to use strcpy_P.
strcpy_P states the string will come from Flashmemory and copy it into SRAM space.  Once it is in SRAM sapce we can maniputate it all we want.
for example:
setPatternName((char*)PSTR("My PatternName"));

void setPatternName(const char* text) {
  memset(patternName, MAX_PATTERN_NAME_LEN + 1, 0 );
  strcpy_P(patternName, text);
  int length = strlen(patternName);
}

This should have a significant reduction in mem usage.

char buf[50];

char* tm1Txt (byte num){
  if (num == 0){strcpy_P(buf, (char*) F("t1 - Задepжka koмaнды xoд"));}
  if (num == 1){strcpy_P(buf, (char*) F("t2 - Bpeмя cepвoфиkcaции "));}
  if (num == 2){strcpy_P(buf, (char*) F("t3 - Bpeмя дoтягивания   "));}
  if (num == 3){strcpy_P(buf, (char*) F("t4 - Bpeмя тopмoжeния    "));}
  if (num == 4){strcpy_P(buf, (char*) F("t5 - Наложениe тормоза   "));}
  if (num == 5){strcpy_P(buf, (char*) F("t6 - Снятия нагр воздуха "));}
  return buf;
}

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


text:
Why use a motor driver board?
I'm just getting into electronics in general and I'm confused a bit as to why I'd want/need to use a motor driver board instead of just setting up my own transistor/diode/etc when attempting to power and control a DC motor.
Any chance someone could clarify the point to using a motor driver board instead (assuming there is another option as I think there to be)?

It is for simplicity - the board will work without needing to design and build your own circuit. You could design and build your own motor controller, but it would take longer. It is a bit like asking, "why buy a radio when I can make one?" :-)

@Greenonline I actually assumed a single transistor/resister/diode would be sufficient in powering a motor. I wouldn't think to build my own motor driver board knowing now more of what it is/does. That, I believe, was closer to what I should have been asking (what a motor driver board is compared to using a single transistor/diode).

It actually uses 4 transistors, to be able to reverse the motor as well. Some drivers even allow two motors in both directions. One may roll it's own, but a readymade part is usually cheaper than ging through the whole design and test/optimize iterations himself.

A motor driver board is just a convenient way of creating what is known as a "H Bridge". This is an arrangement of 4 (or more, but 4 primary) transistors.
You can make it yourself with discrete transistors, but it is simpler to just use a pre-made chip.

A H Bridge gives you greater control over a motor than a single transistor alone. It allows you to control the direction, which you can't do with a single transistor, and it also gives you access to braking modes where the motor becomes harder to turn thus assisting in slowing down the load.
With a single transistor you can turn the motor on and off (or vary the speed if you use PWM) but that is all.

simulate this circuit – Schematic created using CircuitLab

A couple of extra reasons.  If you have low power controllers (like computers), it keep the low power devices away from higher power motor drivers, electronic noise etc.
If you use AC, it can also keep the issues of driving inductive loads away from your micro-electronics (phase and power factor issues).


text:
Keyboard.println missing characters when I print long strings
The topic is pretty straight forward: When I use Keyboard.println(), it sends short (up to 30-ish) strings just fine, but when I get up around 100 characters there are random characters missing. "Random" - meaning it is not all the time, it's somewhat consistently the same characters missing though.
I've checked and the data is arriving at the Arduino correctly (over web service), but once it shows back up in the notepad, it's missing random stuff.
Any thoughts or suggestions?
Edit: Examples as requested:
I'm sending...

cheat SpawnDino Blueprint'/Game/PrimalEarth/Dinos/Pelagornis/PelaCharacter_BP.Pela_Character_BP' 10 1 1 10

And what's printing is...

cheat SpawnDino Blueprint'/Game/PRIMALEarth/Dinos/Pelgornis/PelaCharacter_BP.Pela_Character_bP' 10 1 1 10

I've actually noticed now that it's changing capitalization too, the BP to bP and Primal to PRIMAL.

Could you provide examples which compare the data arriving and the println output?

Not sure why it's happening, but you can probably avoid it by sending only a smaller number of characters at a time, and then add a small delay in between.

Yeah, thanks for the suggestion. I've already tried that though and it's being weird too.. Wont send anything when I nest a keyboard.anything inside of a for loop, regardless what the wait is set to..
Back to tinkering :) thanks.

Could you please provide your code?

I'd bet the issue is overflowing the keyboard buffer of the device you're talking to. On Windows, you can change a registry value to make the buffer larger:
http://www.windowsnetworking.com/kbase/WindowsTips/WindowsNT/RegistryTips/Hardware/KeyboardBufferSize.html
(and in fact, the Windows keyboard buffer is 100 characters by default.)
The reason the capitalization is becoming strange is because the device missed the shift-down or shift-up event, so it's using whatever it would use if the shift key wasn't pressed or released.
The best solution is to avoid sending so much: break it down and send a little at a time as Gerben said.

I just got another idea how to do that instead of character by character since you said that.. Will give it a try, thanks a lot


text:
Temperature sensor and LCD
I have a project which uses a DS18B20 temperature sensor and an LCD with an I2C interface on it. I have connected the sensor to my micro-controller (the DS18B20 has a 12-bit digital output) to the ATmega16 PD17, but as I try to print my values on the terminal the sensor output a really high value in decimal. Here is part of the code (and yes everything is working fine, this is a home-made Arduino):
DDRD &= 0x00;
PORTD |=  0x00;
ds18b20_init(&PORTD, 20, 30, DS18B20_12BIT_RES);
int temperature_sensor_output =  (float)ds18b20_temperature(&PORTD);
printf("Temperature: %d  ", temperature_sensor_output);
delay_ms(500);

ds18b20_init is the Dallas function for initializing the module. ds18b20_temperature returns a float value of the temperature
From this code it just prints:

Temperature: 51603

If I change %d to %f it prints:

Temperature: without any value

I do not understand where I may have missed some things.

Should it be float temperature_sensor_output =?

"printf"?  Are you including the standard I/O C library?  I would have thought that a bit much on a small embedded processor.  But if it works, great! Still, floating point math too?

The home arduino works, though the way I am using the sensor does not.I think I am using these functions wrong but I cannot see the mistake.

@Gerben Yes you are right, but if I put a float into an int it should truncate it?like float 27.89 to int 27?

@DianaLc, you are doing normal C programming on an embedded processor.  A float is usually made up of a integer mantissa and an integer exponent.  I am not sure how much supporting software is available (has been written) for this platform to support casting like you are doing.  I am thinking, not sticking to integer arithmetic is probably causing your problems.  Most professional embedded programs would stick to integer math.  Most software only people just assume all hardware is abstracted to the same level.  That's the different between software and firmware.

Without more detail about the system, I won't understand what printf() does; in non-embedded systems,  printf() writes to stdout by default, but Arduino systems typically don't use such a device.
That aside, %d is the proper format code for printing an integer value, and %f is proper for a float or double.  If you attempt to print an integer value like temperature_sensor_output under a %f format code, either the compiler will complain or the integer pattern of bits (plus perhaps two additional random bytes) will be interpreted as if it is a float or double pattern of bits.  No type cast occurs within printf().  If you want to use a %f format code, pair it up with a float-type variable.
If, as you say, ds18b20_temperature() returns a float, then the type cast  (float)ds18b20_temperature(&PORTD) will have no effect.  Generally, casts convert data from one form to another, or in some cases declare that data has a given form.  Going from float to float doesn't change anything.
In a C statement like a=b, if b has a type that's different from that of a, the b value will be cast to the type of a.  Thus, the float value on the right hand side of
int temperature_sensor_output =  (float)ds18b20_temperature(&PORTD);

will be converted to an integer value and stored into the integer variable temperature_sensor_output.

You can use printf(), if you define a FILE descriptor for stdout as: "static FILE uartout = { 0 };   // dbprintf file descriptor" and a declare and write a char-output function, e.g.: "static int uart_putchar (char c, FILE *stream);", where uart_putchar() Serial.write()s 'c' to the terminal (and ignores the "stream" arg). Note, however, the arduino library's printf() does not implement "%f", even if floating-point is loaded.

Have you looked at the raw return value from ds18b20_temperature(), without casting it to float and then to int, perhaps in hex? It may not be your printing code that's causing trouble but the value returned from the function. If the function is returning something equivalent to 51603, it is already bogus. DS18b20s temperature values are in 16-ths of a degree (Celsius, assuming the routine didn't convert it). 51603/16 is still an unreasonable value, not to mention that viewed as as a 16-bit int, the sign bit is set. Is it truly negative? Did something overlow?
I think you need to look at what that function is doing.


text:
Serial Communication
When I send data using
Serial.println()
in what format does it go? I want to observe the data using the software 'Terminal'. When I observe there, if I've sent 255 using Serial.println(), I get a series of numbers 0 0 224 on the terminal. I've kept the baud rate same in both places(9600), Stop Bits as 1 in Terminal.

Bytes. Always bytes.

On the Arduino Serial.print() method web page it says:

Prints data to the serial port as human-readable ASCII text.

...which is suitable for most terminal programs.  ASCII or American Standard Code for Information Interchange is (usually) an 8 bit code for printing characters.  It is not a code which you can do normal math with.  That is the integer 1 (which is, in binary, b00000001) is not the same as the character '1' (which is, in binary, b00110001).

Example: If you want to print "123" on most terminals you can use the Serial class method print:
Serial.print(123);

Now, you have to understand that the Arduino paradigm is to make programming simple.  So the print method in the Serial class will assume you want to see the characters "123" on the terminal.  So, guessing, the print method will convert each decimal number into an ASCII character and print them out as 3 values to the terminal.  That is, the ASCII value for 1, followed by the ASCII value for 2 finally followed by the ASCII value for 3.
If this is not what you want there are other variations for the print method in the Arduino Serial class.  But all tend to print using ASCII codes.
If you want to print out the binary values, see the Serial.write() method.  This method will send the value of the argument to the terminal with out converting into ASCII code.

Example: If you want to print "1" on most terminals you can use the Serial class method write:
Serial.write(49);

...as 49 is the decimal equivalent of the ASCII code for the character '1'.

Try using terminal program on PC side. NOT Arduino Serial port monitor built into Arduino IDE.
For example try http://docklight.de/
With this or some other similar terminal program, you can see each byte not only as ASCII representation, but also in HEX or binary format.
So you will easily in no time understand difference between ASCII "224" string and single byte 224 value.
With binary format you can have much much faster PC communication especially when sending float numbers. 4 bytes vs 3.7348823457458743 for example :)
On docklight you even have possibility to define macros for sending back to Arduino i ASCII or in binary format. Or even adjustable macros to send most of the string fixed, but change one byte inside string every time when sending.
But even basic ASCII or binary representation of data is enough for now to help you understand this problematic.


text:
4.7v as HIGH on digital output instead of 5v
I'm new to Arduino, just got my starter kit, and I noticed that digital outputs 3 & 4 have 5v as HIGH level while 5 to 13 have 4.7v as HIGH level.
Is it as it suppose to be?

Datasheet says?

Please add your code so that we can check that there isn't a problem there.

Also depends on what your driving via this output. Standard TTL is:

But CMOS will be a bit different:

The Arduino is connected to USB port of MacBook pro. I wrote simple code to check HIGH level on digital pins:
`void loop() {
digitalWrite(3, HIGH);
digitalWrite(4, HIGH);
digitalWrite(5, HIGH);
digitalWrite(6, HIGH);
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
digitalWrite(10, HIGH);
digitalWrite(11, HIGH);
digitalWrite(12, HIGH);
digitalWrite(13, HIGH);
}`

Are those pins output? @d.a.  Please amend your question to post your entire code. You may also want to read up on how to make a loop.

@NickGammon as a point there.
Instead of putting that in loop(), of that in setup() and do the same readings to see if you have the same voltages.

I should point out, that after I tested, I noticed you omitted pin 9 from your list. A loop wouldn't have had that issue.

Yes, that's perfectly fine.
According to the datasheet, at 5V, the minimum voltage you can expect on a HIGH output (AKA VOH) is 4.2V. 4.7V is above that, so it's fine.

Thanks. That was weird for me, because 1 hour ago it was showing 5v to me. And I do not understand what changed.

Maybe the battery in your meter is running out?

Also if it is set to INPUT_PULLUP it will look HIGH but maybe with a lower voltage (depending on the impedance of your meter)

Some of the answers here suggest that a reading of 4.7V is in spec (which it is). As Majenko says, 4.2V is the minimum output high voltage, at an ambient temperature of 85°C, with a load of 20 mA, and Vcc = 5V.
However with no load, and at room temperature, I measured 4.99V on all of those pins, when set to OUTPUT and HIGH on my Uno. Test code:
void setup()
{
for (int i = 3; i <= 13; i++)
  pinMode (i, OUTPUT);
}
void loop()
{
for (int i = 3; i <= 13; i++)
  digitalWrite (i, HIGH);
}

That was weird for me, because 1 hour ago it was showing 5v to me.

Right. What were you doing an hour ago? Did you have LEDs connected to those pins? If so, what value resistor did you have in series with them? Or were you driving a motor from the pins perhaps?

Thanks everybody for help, I forgot to set pin 5 as OUTPUT. When I dit it, I got 5v on it.


text:
Barebones Arduino Zero with ATSAMD21G18
I have been using the ATmega328P TQFP32 chip for quite a while and I would like to try something new. I came across the ATSAMD21G18 used by Arduino Zero and M0. However, there aren't any information online regarding how to develop a standalone, very basic setup of it.
Previously, I have used...

ATmega328P TQFP32
For the crystal: 16Mhz and 22pF caps
For bootloading: 10 11 12 13 for Arduino ISP
For uploading programs: TX and RX of an Arduino Uno with its chip removed.

For the ATSAMD21G18, I am also looking for a similar setup. I checked out the Sparkfun Mini breakout schematics, but I am not good at reading them and there seems to be a lot of components just for protection and to make it more stable, which I don't need as you can probably know from the setup I used for the 328.
https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/sparkfun-samd21-mini-breakout-v10.pdf
What are the basic required components for it to work properly?
For bootloading, am I required to use the Atmel Ice? If so, what are the pins and components needed for burning the Arduino Zero bootloader?
For uploading a program, am I required to use the USB functionality built in? How can I use it (components pins and connections)? Can I use Arduino ISP using an Arduino Zero?
Finally, what should I bear in mind when switching from an ATmega328P to an ATSAMD21G18?
Thanks in advance!

Datasheet says?

Google Samd21 xplained pro. It's got a similar chip but with more features. It also has an on board debugger/programmer.

This seems to be the simples form of the Arduino M0 I could find.
From this tutorial site
The ICE programmmer makes it very easy to program and all you need is the SWD pins to program the bootloader.
ISP is for AVR chips where as with ARM chips like SAMD21 you will need to use JTAG/SWD to program it.
I am also try to make a home brew Zero but I am getting stuck after the bootloader where the board just does not want to expose a Serial port.


text:
Can I detect with software when a PIR sensor is physically connected to Arduino?
I'm creating a circuit using an Arduino Nano + ESP8266 to allow LED remote (via mobile app) activation and configuration (RGB colour, timeout, etc.). The circuit also has an optional PIR sensor to switch on the LED when someone enters the room.
I'd like the circuit to behave differently when the PIR is physically connected to the Arduino (i.e. to light the LED in a different colour) but I have no idea of how detect if the sensor is physically connected to the circuit.
I tried reading the value of the Arduino PIN but (obviously) the signal is LOW whether nothing is detected by the PIR or is not physically connected.
I have two different PIR detectors that I can use for the project:

Arduino Compatible PIR Motion Detector (Description)
DFRobot PIR Detector (Description, Schematic)

Thank you for your time. If there is missing information in my question, please tell me and I will add it.

Which PIR sensor are you planning to use please?

Hi @MarkSmith, I've edited the post to include the information about the sensors. Thank you!

Will the PIR always be connected at power-up?

Yes @sa_leinad, you can assume that the PIR will be connected at power_up.

The PIR sensor I have will overpower the internal pull-up resistor of the ATmega328P used on the Arduino Nano. This means if you turn on the pull-up and then get a read of LOW you know something is connected to that pin because the unconnected pin will always read HIGH with the pull-up on. With this approach you can get false negatives because the pin will also read HIGH if the PIR is triggered but you won't ever get false positives for PIR sensor detection. This means you can't rely on just doing a single test in setup() because the PIR might be triggered then so you will need to repeatedly run the test until the PIR sensor is detected. Example sketch:
int PIRpin = 2;    //the input pin for the PIR sensor
boolean PIRconnected = false;

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

void loop() {
  if (PIRconnected == false) {
    pinMode(PIRpin, INPUT_PULLUP);
    if (digitalRead(PIRpin) == LOW) {
      Serial.println(F("PIR sensor detected"));
      PIRconnected = true;
    }
    pinMode(PIRpin, INPUT);  //turn off the internal pull-up to reduce power consumption
  }
  Serial.println(digitalRead(PIRpin));
  delay(500);
}


text:
Using MMA8451 accelerometer to count steps
I'm trying to use an Adafruit MMA8451 accelerometer to create a pedometer-type device that counts steps. I'd like to initiate a counter that says "if the x-axis readout is > some threshold, add 1 to the counter" so that once the counter reaches a certain point, I'll be able to trigger a separate event (like an LED turning on). I'm an Arduino beginner, and would appreciate any pointers in the right direction as I work through this.
I'm using the Sparkfun Redboard and the Adafruit MMA8451, and wrote a loop to check whether the x-axis readout was over 5. If it's over 5, I want it to add 1 to the accumulator. However, it's accumulating 1 each readout regardless of what the 'x' reading actually is. Can anyone tell what I'm doing wrong? A nudge in the right direction would be much appreciated.
Code is here:
/**************************************************************************/
int lastStepCount = 0;
int accum = 0;

#include <Wire.h>
#include <Adafruit_MMA8451.h>
#include <Adafruit_Sensor.h>

Adafruit_MMA8451 mma = Adafruit_MMA8451();

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

  Serial.println("Adafruit MMA8451 test!");

  if (! mma.begin()) {
    Serial.println("Couldnt start");
    while (1);
  }
  Serial.println("MMA8451 found!");

  mma.setRange(MMA8451_RANGE_2_G);

  Serial.print("Range = "); Serial.print(2 << mma.getRange());
  Serial.println("G");

}

void loop() {
  // Read the 'raw' data in 14-bit counts
  mma.read();
  Serial.print("X:\t"); Serial.print(mma.x);
  Serial.print("\tY:\t"); Serial.print(mma.y);
  Serial.print("\tZ:\t"); Serial.print(mma.z);
  Serial.println();

  /* Get a new sensor event */
  sensors_event_t event;
  mma.getEvent(&event);

  /* Display the results (acceleration is measured in m/s^2) */
  Serial.print("X: \t"); Serial.print(event.acceleration.x); Serial.print("\t");
  Serial.print("Y: \t"); Serial.print(event.acceleration.y); Serial.print("\t");
  Serial.print("Z: \t"); Serial.print(event.acceleration.z); Serial.print("\t");
  Serial.println("m/s^2 ");

  /* initiate for loop to count movement— this is the piece I'm having trouble with */
  if (event.acceleration.x >= 5);
    accum = accum + 1;
  Serial.print("X Counter: "); Serial.print(accum);

  /* Get the orientation of the sensor */
  uint8_t o = mma.getOrientation();

  switch (o) {
    case MMA8451_PL_PUF:
      Serial.println("Portrait Up Front");
      break;
    case MMA8451_PL_PUB:
      Serial.println("Portrait Up Back");
      break;
    case MMA8451_PL_PDF:
      Serial.println("Portrait Down Front");
      break;
    case MMA8451_PL_PDB:
      Serial.println("Portrait Down Back");
      break;
    case MMA8451_PL_LRF:
      Serial.println("Landscape Right Front");
      break;
    case MMA8451_PL_LRB:
      Serial.println("Landscape Right Back");
      break;
    case MMA8451_PL_LLF:
      Serial.println("Landscape Left Front");
      break;
    case MMA8451_PL_LLB:
      Serial.println("Landscape Left Back");
      break;
  }
  Serial.println();
  delay(500);

}

**Update: the output I'm getting is as follows. The "X Counter" accumulates even when the x-reading is well below 5...not sure what's going on:
X:  1Adafruit MMA8451 test!
MMA8451 found!
Range = 2G
X:  144 Y:  50  Z:  4052
X:  0.34    Y:  0.11    Z:  9.66    m/s^2
X Counter: 1Portrait Up Front

X:  138 Y:  62  Z:  4052
X:  0.34    Y:  0.11    Z:  9.70    m/s^2
X Counter: 2Portrait Up Front

X:  0   Y:  48  Z:  4040
X:  -0.02   Y:  0.11    Z:  9.67    m/s^2
X Counter: 3Portrait Up Front

X:  -780    Y:  106 Z:  3814
X:  -1.80   Y:  0.25    Z:  9.11    m/s^2
X Counter: 4Portrait Up Front

X:  -510    Y:  106 Z:  4008
X:  -1.46   Y:  0.20    Z:  9.68    m/s^2

What is your output?

Voting to close because it's a typing mistake / syntax error, and user has not returned since asking the question.

Change your if statement - remove ; (semicolon) from the end.
Use this:
if (event.acceleration.x >= 5)
accum = accum + 1;

Notice there is no semicolon after if statement

Mark as answer if it helped you.

The OP has not returned since asking the question, so I doubt it will ever be accepted. +1 for your answer.


text:
Implementing an external ADC in Arduino
I'm planning to use a ADS1220 4-channel 24 bit adc but I really have no experience with SPI. I have found this library but I can't really understand the code that much and also this is measuring the differential voltage. I want to use this for my accelerometer (x, y and z data) but I can't seem to find how to do read from 3 channels, and I can't understand the code in the library :( I've also found a video for this adc in youtube but he didn't used it for multiple channels. I'm sorry for asking this, I'm just pressured since the deadline is really soon.
EDITED

sketch
#include "Protocentral_ADS1220.h"
#include <SPI.h>

#define PGA 1                 // Programmable Gain = 1
#define VREF 3.3
#define VFSR VREF/PGA
#define FSR (((long int)1<<23)-1)

volatile byte MSB;
volatile byte data;
volatile byte LSB;
//volatile char SPI_RX_Buff[3];
volatile byte *SPI_RX_Buff_Ptr;

long int bit32, data1, data2, data3;
long int bit24;

Protocentral_ADS1220 ADS1220;

void setup() {
  pinMode(ADS1220_CS_PIN, OUTPUT);
  pinMode(ADS1220_DRDY_PIN, INPUT);

  ADS1220.begin();
  //ADS1220.Single_shot_mode_ON();
}

void loop() {

  byte *config_reg;

  data1 = aRead(0x81);
  data2 = aRead(0x91);
  data3 = aRead(0xA1);

  Serial.print(data1);
  Serial.print("    ");
  Serial.print(data2);
  Serial.print("    ");
  Serial.println(data3);
  delay(500);

}

long int aRead(uint8_t config_byte) {
  ADS1220.writeRegister(CONFIG_REG0_ADDRESS , config_byte);
  uint8_t r = ADS1220.readRegister(CONFIG_REG0_ADDRESS);
  //Serial.println(r,HEX);

  ADS1220.SPI_Start();

  while (ADS1220.NewDataAvailable == false) {
    SPI_RX_Buff_Ptr = ADS1220.Read_Data();
  }

  if(ADS1220.NewDataAvailable = true) {
    ADS1220.NewDataAvailable = false;

    MSB = SPI_RX_Buff_Ptr[0];
    data = SPI_RX_Buff_Ptr[1];
    LSB = SPI_RX_Buff_Ptr[2];

    bit24 = MSB;
    bit24 = (bit24 << 8) | data;
    bit24 = (bit24 << 8) | LSB;

    bit24= ( bit24 << 8 );
    bit32 = ( bit24 >> 8 );
  }

  return bit32;
}

I tried to use the above sketch and I successfully read from 3 different channels but I noticed that the readings vary too much, compared to the example code. In the example code when I turn my potentiometer full CW, it outputs 8388607 which is correct right? since it is signed int.
But when running this sketch, the image below shows the output when the potentiometer is fully CW. Also turning the potentiometer fully CCW leads to negative values (shown in the 2nd picture) but in the example code, it gives 100-300 decimal values.  Also these are the configuration registers I sent in registers 1-3 (I edited it in the part of the library) and for register 0, it is on the sketch.
Config_Reg1 = 0x00;
 Config_Reg2 = 0x40;
 Config_Reg3 = 0x00;

using accelerometer
format is (x,y,z)

What kind of deadline? School project or assignment?

Writing ADC driver code from scratch is NOT easy.  What is wrong with the ADC built into most Arduino's processors?  The ADC driver for most Arduino's is already part of the Arduino SDK.

What's the model number of the accelerometer? Many of them digitize their results already.

@MikaelPatel it's for my thesis in college

@jwpat7 adxl335, this has analog outputs, my adviser wants to have a 24 bit output accelerometer, I know there are lots of accelerometer that has 16 bit output which is already enough for precise measurements but I wanna give a try implementing an external adc before suggesting to my adviser to use accelerometers with digitized outputs

To get an understanding of how to read from the various ADS1220 channels, first review Figure 38, Analog Input Multiplexer, in the Datasheet as obtained from a link on TI.com's ADS1220 technicaldocuments webpage.

As can be seen, you'll need to close a switch from an AINx input line to the AINₚ bus, and also close the switch between AINₙ and AVSS.  The IDACx switches and the BCS switches should remain open.
To operate those switches, first look at §8.6.1, Configuration Registers, in the Register Map section of the Datasheet.  You'll see that MUX bits are in register 0, BCS is in register 1, IDAC is in register 2, and IxMUX are in register 3.  To see what to put into those fields, look at Tables 16, 17, 19, and 20.  For the MUX field, you will want a binary value like 1000, 1001, 1010, or 1011 to select one of AIN0-AIN3 as the AINₚ input and AVSS as the AINₙ input.  BCS, IDAC, I1MUX, and I2MUX all should be zero.
For example, to read channels 0, 1, 2 in sequence, set MUX to 1000, set up other register fields, and trigger a conversion.  After reading the result, change MUX to 1001, trigger a conversion, read result,  change MUX to 1010, trigger a conversion, read result, etc.

Edit 1: In slightly more detail, one could do as follows.

• Use a WREG command [as in §8.5.3.6; or some library equivalent] to send three bytes to set up Configuration Registers 1, 2, 3.
  • For i=0, 1, and 2 in turn, construct a configuration byte, send that byte to Configuration Register 0, start a conversion, await result, read result; as follows:

Set the MUX field of a byte to i
    Set PGA as desired (ie, to 1, 2, or 4, via codes 000, 001, or 010)
    Set the PGA_BYPASS bit (as required when AINₙ = AVSS)
    Use a WREG to send the constructed byte to Configuration Register 0
    Use a START/SYNC command to start a conversion (see §8.5.3.2)
    Wait for DRDY to go low
    Use an RDATA command to read iᵗʰ ADC result (see §8.5.3.4)

Edit 2: In Protocentral's ADS1220.ino sketch, one finds the code sequence
  MSB = SPI_RX_Buff_Ptr[0];
  data = SPI_RX_Buff_Ptr[1];
  LSB = SPI_RX_Buff_Ptr[2];
  bit24 = MSB;
  bit24 = (bit24 << 8) | data;
  bit24 = (bit24 << 8) | LSB; // Converting 3 bytes to a 24 bit int
  bit24= ( bit24 << 8 );
  bit32 = ( bit24 >> 8 );     // Converting 24 bit two's complement to 32 bit two's complement

More competently and concisely, and with SPI_RX_Buff_Ptr renamed to SPI_RX_Buff, this could be written as:
  bit32 = (((long)(SPI_RX_Buff[0]<<8 | SPI_RX_Buff[1])<<8 | SPI_RX_Buff[2])<<8)>>8;

which acts as follows:  Assemble three bytes from SPI_RX_Buff into a 24-bit twos-complement-signed number.  Shift that number left 8 bits so that its sign bit now sits in the sign bit position of a 32-bit signed integer.  Shift that result 8 bits right with sign extension so that the final result is a signed 32-bit integer with possible values from -2²³ up to (2²³-1).
Sign extension occurs – usually – because in many implementations of C, the >> operator does an arithmetic shift instead of a logical shift when its operand is signed.

I just read this and it made me understand the datasheet, thank you so much!! I'll just update you if I was able to make it work

hello I'm wondering what would I send first when I want to read the data. I found this youtube video and he started with setting CS to low (which I think I should also do in my case) then sends a byte which is equal primary byte with a start bit and single/diff mode and to a register mask that isolates 3 LSB. I'm sorry if I'm noob but it would mean a lot to me if you help

I'm guessing I should send all those 4 configuration registers? I just don't know the flow I'm sorry

oh I get it why he and it with a mask, just to be sure that the config register will not be changed during the process, now my main concern is how to send these configuration registers

Edit 1 reflects my understanding (from datasheet) of the process - I haven't tried it out, and haven't looked at what library calls might apply

thank you so much for the fast reply, I'll figure this one tomorrow since its 4 am already but I did a quick scan and now I can at least understand the library already, really appreciate your help! I hope I can do more than saying thanks because your did really help me a lot with the information you gave!

hello I just continued following what you wrote and looking for the commands written in the library, also in your edited line did you mean for the gain in this line Set PGA as desired (ie, to 1, 2, or 4, via codes 000, 001, or 010) ? as I've read in the datasheet the commands corresponds to the gain. I was also a bit confused in the library on the reading of data part.

It is written on line 235, why did he used a loop in reading the data and in the example extracted the data buffer in line 58 do I also need to read the value like this? and also he sent SPI_MASTER_DUMMY which is equal to 0xFF. In the datasheet RDATA command is like this 0001 xxxx, does this mean that the x's are considered 0? so when I read for data I should send a command byte of 0001 0000 and loop it again for the other channels right?

Only gains of 1,2,4 are available for single-ended input, and their codes are 000, 001, 010 in the gain field, which is above the PGA_BYPASS bit in the config byte.  The for loop at line 243 in Protocentral_ADS1220.cpp loops 3 times to read all 3 data bytes of result.  As noted in SPITransfer at arduino.cc,  “SPI transfer is based on a simultaneous send and receive”; if sent data is irrelevant, dummy it.  In 0001 xxxx each x is a don't-care, so can be anything. §8.5.4 says  “An RDATA command does not have to be sent”  after DRDY goes low.

okay thanks again for the help, so I would stick to the library with the for loop in reading right? I'm still a bit confused with the dummy thing, what does it mean if send data is irrelevant? but basically I'll get my reading with the code inside this function right? uint8_t * Protocentral_ADS1220::Read_Data() since it checked for the DRDY to go low so no need for RDATA command

I also have a question in the pin configuration, does AVSS go to ground?

You may need to experiment some with that library.  It uses some 100 μs delays (before dropping CS) that appear unnecessary  and it may improperly depend on delays instead of busy-waiting on flags.  It also uses an if statement instead of a while to check if DRDY is low, rather than busy-waiting for DRDY to go low.  ¶  AVSS is analog low-side voltage (see Pin Functions table, page 4 of specs), typically ground, but some people like to  keep it separate from digital ground DGND.  ¶  Do some web searching for "Analog ground", "busy wait", etc.

hello I tried the library already and it's working, I also added an external reference successfully. I just wanna clarify what you wrote at the top, in my case I should always write a configuration byte to Register 0 right? does this also mean I should change my conversion mode into single-shot? so that every time I write the config byte then I'll start a conversion with the START/SYNC command? the wait for DRDY to go low and read the data, then another configuration byte to the next channel and so on..

Yes, that's my understanding of what you need to do.

hello sorry to bother you again but if you don't mind, please take a look at the edited part. thank you so much!

I'll look at it more later this week - no time ATM - after setting up on a channel try several readings in a row before going to next channel to see if readings settle in

no luck, i tried reading only one channel in single shot mode, still same result. it maxes out at 83875xx and -9xxx as minimum reading

Though I  think depending on my application, i don't really reach the minimum and maximum values since I have -/+3g accelerometer for measuring vibration and it's unlikely for it to reach more than -/+1g. I am having doubt though on the values I'm getting using the accelerometer, I added it at the top. The values should reflect 0g on x and y axis and 1g on z axis. For example I am only getting the +8388608, the value for 0g should be expected to be half of it (between 0-+8388608 = 4194304) but it seems like it's far than that. Also ow can I get the whole 2^24 = 16777216 analog levels?

I asked how to get the whole 2^24 levels since I don't really understand the code above for bit24 and bit32 variables

i actually tried to convert these values to g values and it pretty much does the job!! i got precise measurements now really thanks a lot to your help!!!! and Merry Christmas by the way!

See edit 2 regarding  code with variables bit24 and bit32.   ¶ If the library code turns out to be too slow, there are a dozen or two unnecessary delay(2)'s and delay(5)'s and delayMicroseconds(100)'s egregiously scattered around in Protocentral_ADS1220.cpp.  You probably can remove most of those, or change all the 2's and 5's to 1's, etc

authors: Александр Юферев


text:
ML8511 Sensor, unable to achieve meaningful results. Output voltages are atypical
Problem: ML8511 Sensor, unable to achieve meaningful results.  A mapping to the voltage output yields values that are unrealistically high. Variance is greater than expected [by me], and sensitivity, if any is questionable. In essence, the sensor reports high levels of UV whether is a dimly lit room, or exposed to daylight.
Background:
The interface is simple enough, and Google Search renders numerous hits, e.g., https://learn.sparkfun.com/tutorials/ml8511-uv-sensor-hookup-guide
All coding examples I have seen are akin to the one shown by Sparkfun.
Prior experience: I have a number of other Arduino devices running my sketches that record, collect, analyse, distribute, transmit and display findings.  All of these work as intended.
Observations:  I have spent a lot of time trying to make sense of the behaviour i observe with the sensor output, but have been unsuccessful. I have used two different sensors [same model], and switched UNO boards.  I've removed all other connections to the board, reverted to using the example code, then to code measuring only pinout values.  I have also measured pin voltage via voltmeter for both the output signal and the 3.3 volt reference pin..  According to specs, the sensor outputs voltage correlate with UV levels, and calibration is achieved via a known voltage reference level.
Based on a 3.3 volt reference, the sensor should output 1 to 3 volts, which can be mapped to a UV Intensity (mW/sq cm) range of 0 to 15.  My output voltages range from 2.8 to 3.2 v, the last of which is seemingly out of specs.
I have also used different sample sizes that comprise a data point, but that has little effect, but since the underlying values are out of range, it really would not matter.
Although cheap sensors such as this are not known for great accuracy. I find that they generally work rather well.
My supposition is that:
a) I am working with defective [abeit new] sensors.
b) This particular model of sensor functions in an atypical manner.
c) Being unexperienced in such, I an overlooking something glaringly obvious to others.
d) Somehow my perception of reality is defective.
e) I have truly entered into the Twilight Zone.
Seeking: Information that supports or refutes my observations.  Ideas that I might use to further isolate/ identify the problem.  A solution to the problem.
Image of item used

ML8511 UV Intensity Graph from specs
[
Typical ML8511 Wiring Diagram, the GYML8511 also has an additional connector for 5V, which I have tried both connected and disconnected, not understanding the board behaviour.

I found another, third sensor identical to mine and functioning properly.  By measuring pin output, then cross swapping with one of my two "supposedly abberant" sensors, I have identified my two as being defective, i.e., the other sketch then failed to function properly with one of those so identified sensors, whilst mine now worked as it should.
I typically buy at least two of everything in an effort to isolate such problems, but if from the same batch, two may not be sufficient in some situations.


text:
Why declare analog pins as ints?
I often see code like this:
const int piezo = A0;
const int sensorPin = A1;

From my understanding, an int variable can hold things like -123, 0, 1, 456, etc.
How can A0 or A1 be an int?

The board definition (pins_arduino.h) has this:
static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
static const uint8_t A3 = 17;
static const uint8_t A4 = 18;
static const uint8_t A5 = 19;
static const uint8_t A6 = 20;
static const uint8_t A7 = 21;

Since A0 is a constant variable equal to 14, if you assign that to a variable, it just assigns 14.
In other words:
A = 14.
B = A.
Therefore B = 14.

They are defined in the Arduino libraries, and the Arduino libraries will translate them into the appropriate pins and registers before they are used. But in the meantime they're numbers.


text:
How is a local variable address retrieved/returned inside the CPU of Arduino?
How is the address of a local variable retrieved in Arduino's ATMEGA328 micro-controller?
Lets say somewhere inside the main we have lines as:
int x = 5; //a variable declared and value of 5 stored in SRAM ??
int  *p; // a pointer is declared
p = &x; // p holds the address of the variable x

What happens above is &x retrieves the address of the variable x.
But how does this happen in a lower level?
Which function retrieves the address of a variable and how does it do it?
How does that function know the address of the variable x?
I'm wondering what happens step by step after the instruction comes to the instruction register.
edit: Another question for int x = 5; is 5 stored at CPU register or SRAM?
.

LDS. It doesn't, the compiler does.

oh do you mean when the code is running inside the micro-controller the address "was" retrieved already before by the compiler and the instruction code operating inside the microcontroller holds that address already? im sorry i just want to clarify. very new to subject.

Yes, the compiler maintains a symbol table for all symbols in the code. And for any actual dynamic addresses there are indirect opcodes that work with those.

Are you asking: how does a compiler translate C++ code into assembler? This is rather a broad question. Perhaps better suited to Stack Overflow.

But how does this happen in a lower level? - you are asking how a compiler works. This is really nothing to do with the Arduino per se.

Disassemble your program and you will get your answer, at least for that particular program. You will find instructions on how to disassemble here and elsewhere on the Web.

Another question for int x = 5; is 5 stored at CPU register or SRAM?

That depends entirely on how the compiler optimizes your code. If you never refer to x in your code the compiler may discard that statement entirely. Or it might use a CPU register. It might use RAM.

Just as an experiment, I tried the following:
void bar(int *);

void foo()
{
    int x = 5;
    int *p;
    p = &x;
    bar(p);
}

And here is what gcc translated that into (comments mine):
__SP_H__ = 0x3e
__SP_L__ = 0x3d
__tmp_reg__ = 0
foo:
    push r28            ; save r28
    push r29            ; save r29
    rcall .             ; make room on the stack
    in   r28, __SP_L__  ; copy SP into r29:r28 = Y: LSB...
    in   r29, __SP_H__  ; ... and MSB
    ldi  r24, lo8(5)    ; store x in a register: LSB...
    ldi  r25, 0         ; ... and MSB
    std  Y+2, r25       ; copy x into the stack: MSB
    std  Y+1, r24       ; ... and LSB
    movw r24, r28       ; r25:r24 = Y
    adiw r24, 1         ; r25:r24 = Y+1 = &x
    call bar            ; call bar(&x);
    pop  __tmp_reg__    ; release the two bytes...
    pop  __tmp_reg__    ; ... of stack space
    pop  r29            ; restore r29
    pop  r28            ; restore r28
    ret                 ; return

Expanded comments:
The instruction rcall is normally used to call another function. Here
it's calling the following instruction, so it doesn't affect the program
flow. It's only a trick: as rcall saves the return address into the
stack, it makes the stack grow by two bytes, and is used here as an
optimized way of reserving to bytes of stack space for storing x.
Next you see the stack pointer being copied into the r29:r28 register
pair, also known as “Y pointer”. The stack pointer is a CPU register
holding the address of the top of the stack, namely of the first free
slot. As the stack grows towards the bottom of the RAM, at this point
it looks like this:
address | SP = Y | Y+1 | Y+2  | Y+3 | Y+4 | Y+5  |  Y+6  |...
--------------------------------------------------------------
data    | (free) | room for x |  saved Y  | return addr. | ...

Next you see the value of x being placed first in a register pair
(r25:r24), then on the stack at the addresses Y+1 and Y+2.
The instruction mowv copies a register pair, so now you have a copy of
the stack pointer in the pair r25:r24. The instruction adiw adds an
immediate value (here, 1) to a register pair, so that now r25:r24 holds
the address of x. Finally, the function bar() is called: per the
calling convention, the argument is to be passed in the r25:r24 pair.
A few final remarks:

I passed the pointer to another function just to make gcc believe that
I am actually using that pointer, otherwise it would optimize out
the whole code into a function that does noting but return.
You don't need to create a pointer variable to hold the address of
x: calling just bar(&x) compiles into the very same assembly.
Most local variables are assigned to CPU registers. Only because I am
using the address of x did this variable get stored in the stack.
The compiler output is very sensitive to the surrounding code, the
compiler version, the optimization options, and so on. So you should
consider all this as only an example.
If you do not completely understand what each instruction is doing,
you should now take a look at the AVR Instruction Set Manual

That manual says: "Registers concatenated with the X-, Y-, and Z-registers enabling indirect addressing of the whole data space on MCUs with more than 64KB data space, and constant data fetch on MCUs with more than 64KB program space" Does that mean X Y Z registers are never used in an ordinary Arduino UNO since it has ATMEGA328 which has only 2KB RAM?

@user16307: You are quoting the description of the RAMPX, RAMPY and RAMPZ registers, which are not the same as X, Y and Z. The ATmega328P does not have RAMP registers.

To answer your question you first have to understand what exactly happens when a function is called.
The very first operation, in what is known as the function prologue, a stack frame is allocated. This stack frame contains, amongst other things:

The return address of the function
Copies of any CPU registers that the function uses
Storage space for any local variables

This may be through the use of a dedicated PUSH instruction or by manual manipulation of the stack pointer and writing of data direct to memory, depending on the CPU architecture.
During this process the compiler says "This variable is stored at stack offset X" for each variable. From that point on there is no "variable" as such, only a stack offset. All accesses to the variable are actually accesses to the memory at the location it already knows about within the stack frame.
When you then access the address of a variable you are basically saying "instead of getting me the contents of this memory address, just give me the memory address". Since the compiler already knows what that offset is it just adds it to the address of the stack frame and gives you that.
So if your stack frame is at 0x500 (for example) and the variable x is at offset 0x004:

Accessing x gives you the contents of address 0x500 + 0x004
Accessing &x gives you the value 0x500 + 0x004

Assigning p to &x creates another variable in the stack frame (which could be at offset 0x006 say). To that variable is assigned the value 0x500 + 0x004 (or 0x504 of course).
However, that is all from the point of view of a non-optimising compiler.  The compiler itself may go "There is no need to store this value in memory, I have enough registers to keep it internally". So it doesn't actually allocate anything on the stack for the variable, it just "remembers" it in a register. That makes the function shorter and faster since there are less memory accesses.
There are a couple of variable attributes that affect how these decisions are made. The first is volatile which tells the compiler that "this variable must be stored in RAM and, further to that, don't trust that the value in RAM is the same since I last looked at it". This is essential for variables shared between the main loop and an interrupt context, since the compiler doesn't know if the interrupt is going to change the value of the variable.
volatile int foo;

The second is the register attribute.  This suggests to the compiler that it might like to store this variable in a register to make things faster. This flag is seldom seen any more since the optimiser generally does a much better job of working out which variables would fit better in a register than a human can. It's very much a deprecated attribute now.
register int foo;

I'm mostly asking what happens inside the uC after the compilation. When the micro-controller running the program counter(PC) starts to fetch instruction codes to  Instruction register So you see there is a movement here. Im talking about this movement inside the uC. I can understand  how the program data ca be sent to a CPU register by the micro code. It decodes the data from the instruction register and does its job. But what kind of instruction makes the micro code to retrieve the address of a variable stored and how does it do is mystery to me. But I will reread your answer again and again

There is no instruction that retrieves the address of a variable. There is no variable. There is only the address at which the compiler has placed the contents of the variable (the offset in the stack frame). It's what you do with that address that counts. You can use it as a number (it's just a number after all) or you can retrieve the value from memory at that address.

The address is the variable. The variable is the address. We just give it a name for our own convenience. The compiler just knows it as (SP+4) (for example).


text:
Explanation of the formula of the map funtion
Can someone please explain (mathematically) how the formula for the map function actually came to light?
I have given the code of the map function below. You can see that it uses a formula to "map" values in a given range from a certain range. I don't quite understand how it came (not good at maths) :| So, I would like an explanation to how this formula came to light.
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

(x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;

X is your value. in_min is the minimum value of X. If you subtract that minimum value from X you re-map X into the range it can be.
For instance if X can be between 10 and 20 the in_min would be 10 and in the in_max would be 20. X will be somewhere between the two. Say X is 14. So X is 4 more than the minimum, or X - in_min = 4.
That gives you how far (in quanta of X) into the range you are.
out_max - out_min gives you the range of the output in the same way. If you want to map to 200 to 300, say, the range between the two is 100.
The same with in_max and in_min - it gives the size of the input range - 10 in this case (20 - 10 = 10).
So you now have some values:

4 is how far through the input range you are
100 is how big the output range is
10 is how big the input range is

Multiply the first two together and divide by the third and you get how far through the output range the input is. You could also do it the other way around - divide the input offset (4) by the input size (10) to get the percentage (in the range 0 to 1) that you are through the input. Multiply that percentage by the size of the output range to get how far through the output you are. The way it is done avoids the use of any floating point values which makes it faster.
So 4 * 100 = 400. 400 / 10 = 40.  Or, 4 / 10 = 0.4, 0.4 * 100 = 40.
Then you just add to that the output minimum values which just gives it an offset.  40 + 200 = 240.
Thus:
map(14, 10, 20, 200, 300) == 240.

To reiterate the steps:

14 - 10 = 4 (input offset)
20 - 10 = 10 (input range)
300 - 200 = 100 (output range)
4 * 100 = 400 (percentage of input range
400 / 10 = 40 applied to output range)
200 + 40 = 240 (add output offset)

map() implements linear interpolation.

In mathematics, linear interpolation is a method of curve fitting using linear polynomials to construct new data points within the range of a discrete set of known data points.


text:
Arduino + ESP8266 as Webserver
I want to connect Arduino to my Home Wifi and make it serve as a server to access GPIO pins on Arduino from remote (like controlling LED connected to Arduino from remote).
I am using ESP8266 to connect to my wifi network.
I am facing some issues like:

sometimes it doesn't connect to my wifi router.
not connecting to my mobile Hotspot.
not able to serve default and AP mode.

I am following tutorial from http://allaboutee.com/2014/12/30/esp8266-and-arduino-webserver/
Here is my code:
#include <SoftwareSerial.h>
#define DEBUG true

SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                             // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                             // and the RX line from the esp to the Arduino's pin 3
void setup()
{
  Serial.begin(9600);
  esp8266.begin(115200); // your esp's baud rate might be different

  sendData("AT+RST\r\n",2000,DEBUG); // reset module
//  sendData("AT",2000,DEBUG); // send AT command
//  sendData("AT+GMR\r\n",2000,DEBUG); // returns firmware
//  Serial.println("checking mode");
//  sendData("AT+CWMODE=?\r\n",5000,DEBUG); // check supported modes
//
//  Serial.println("scanning APs");
//  sendData("AT+CWLAP\r\n",21000,DEBUG); // scan list of access points

  Serial.println("set mode 1");
  sendData("AT+CWMODE=1\r\n",5000,DEBUG); // configure as both mode

//  Serial.println("joining AP");
  sendData("AT+CWJAP=\"<MY_WIFI_SSID>\",\"<WIFI_PASSWORD>\"\r\n", 16000, DEBUG); // connect to wifi

  Serial.println("Testing CIFSR");
  sendData("AT+CIFSR\r\n",7000,DEBUG); // get ip address

  Serial.println("setting for multiple connection");
  sendData("AT+CIPMUX=1",2000,DEBUG); // configure for multiple connections

  Serial.println("print MAC address");
  sendData("AT+CIPSTAMAC?\r\n",2000,DEBUG); // print current MAC address

  Serial.println("set port 80 for server");
  sendData("AT+CIPSERVER=1\r\n,80",2000,DEBUG); // turn on server on port 80
}

void loop()
{
  if(esp8266.available()) // check if the esp is sending a message
  {

    if(esp8266.find("+IPD,"))
    {
     delay(2000);

     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48

     String webpage = "
Tyagi IoT
<button>LED1</button>";

     String cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();
     cipSend +="\r\n";

     sendData(cipSend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);

     webpage="<button>LED2</button>";

     cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();
     cipSend +="\r\n";

     sendData(cipSend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);

     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId; // append connection id
     closeCommand+="\r\n";

     sendData(closeCommand,3000,DEBUG);
    }
  }
}

void sendData(String command, const int timeout, boolean debug)
{
    esp8266.print(command); // send the read character to the esp8266
    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {
        // The esp has data so display its output to the serial window
        Serial.write(esp8266.read());
      }
    }
}

I know this is an old question, but posting my 2 cents for future visitors. You're setting "AT+CWMODE=1" which is Client mode. Mode 3 is the correct one for both client and server mode.

Are you using an arduino (as in UNO / mini / nano etc.) and communicating with a separate esp8266 via serial?
I've found esp8266 module to be more reliable by using a 12e or such like and running arduino boot loader on it. There's more memory to play with, and I tend to formulate the data I need within the ESP8266 and then communicate with that via serial or I2C to get data / requests to and from.
Make sure you're supplying the ESP module with enough current - they're juicy little things, so good 300mA @3.3v and use a good 470uf 10v cap or something too.. They can splurge current on occasion, particularly when scanning networks.
Let me know what set up you're running
Cheers

Using Uno and communicating using AT commands on Software serial as mentioned in the code above.

If you're running the esp straight off the uno 3.3v power supply, that'll be the first thing to change. The esp8266 can draw around 200mA transmitting and around 60mA when receiving. The 3.3v regulator built into the arduino UNO is rated for like 50mA max from memory, so defo get a better 3.3v supply. I usually use a MIC5219 LDO regulator which is good for around 500mA but super efficient. Gotta sort power out before trying anything else at this point :)


text:
Is it possible to measure the velocity of a Unmanned Aerial Vehicle using only accelerometer?
Our project is about dropping a payload from a UAV on the specified area. We are using an accelerometer (connected to the Arduino board) to measure the velocity of the plane (assuming the initial velocity to be zero). Is it possible to accurately measure the velocity of a plane moving in the air for a time t? Will this method be feasible?

Is there a reason why you can't use a GPS system?

Not with any measure of accuracy, no.
You're basically asking about Dead Reckoning which is problematical at best - and when doing it with just a low-grade accelerometer it can't be anything more than a rough "It's moving quick" or "it's moving slower now" accuracy.

I'm a little interrested in this, what happens if we remove the high accuracy contraint, is it possible, with something like an MPU6050, mesure a the velocity to, maybe an accuracy of +- 10km/h?

@DatHa: No; this won't work reliably without a source you can use to fix your position or velocity. An accelerometer can only measure acceleration. Measuring velocity requires continuously integrating the accelerometer over time, but because you can only sample finitely many times per second, you will gradually accrue errors in your estimation until it becomes completely useless.

It's even worse than that: to get position requires double-integrating the velocity over time. It works on paper, but in the real world, physical disturbances and electrical noise soon dominate the sums, rendering them useless very quickly.


text:
Stepper motor jittering
I'm trying to make a nema17 stepper motor work using ramps1.4 and A4988 driver.
But when I'm trying to rotate motor, it spins with almost no torque and constant shaking.

Motor 2-phase nema17 , Step Angle 1.8° .
Power supply 12v/60w.

Here is the sketch:
(I copied it from RepRap wiki , and removed everything except X Motor)
#define X_STEP_PIN         54
#define X_DIR_PIN          55
#define X_ENABLE_PIN       38

void setup()
{
  pinMode(X_STEP_PIN       , OUTPUT);
  pinMode(X_DIR_PIN        , OUTPUT);
  pinMode(X_ENABLE_PIN     , OUTPUT);
  digitalWrite(X_ENABLE_PIN, LOW);
}

void loop ()
{
  if (millis() % 10000 < 5000)
  {
    digitalWrite(X_DIR_PIN    , HIGH);
  }
  else
  {
    digitalWrite(X_DIR_PIN    , LOW);
  }

  digitalWrite(X_STEP_PIN     , HIGH);
  delay(1);
  digitalWrite(X_STEP_PIN     , LOW);
}

The wiring diagram:
(I have only X Motor plugged in)

and video: (Google Video link is dead @ 2017-02-09)

Does the stepper motor breakout have a potentiometer to set the maximum current?

Add a second delay after:
digitalWrite(X_STEP_PIN    , LOW);
Also try increasing the delay maybe you are pulsing the step pin too fast.

Nothing changed , it keeps doing the same , but slower .

Have you tried removing your if that control the dir pin?

You may also want to check your driver current: https://www.pololu.com/product/1182/faqs

If i remove if completely it is just shaking . If i remove  if , but leave digitalWrite(X_DIR_PIN    , HIGH); it keeps doing the same thing .

Yes , checked driver current limit , it is set to 700mA and motor has Rated current of 400mA .

And you did try with a different step motor and driver right ?

Yes i tried three different motors and two drivers but nothing changed .

How is your power connected to the arduino and driver board? Ground is common ?

And i also forgot to mention that copied code from RepRap wiki and just removed everything except X Motor . But original code does the same thing .
link

Yes ground is common , if i understand everything correctly .

According to the A4988 datasheet the driver requires 200ns setup time to read signals MS1, MS2, MS3, RESET and DIR, before the STEP signal can be set. Maybe all you need is delay(1) at the end of void setup(){}?


text:
2D Tracking of an object - which sensor?
I'm currently working on a project for which I require a sensor. I've made a quick and simplified drawing of what the result is supposed to do:

Basically, I want one LED of a LED-Strip to light up dependent on the location of a moving object. If the object in above image (say a slow rolling ball) were to move from bottom to top, then the LED strip should also light up from bottom to top. I have no problem getting the LED strip to light up adequately, however I'm not sure which sensor actually can pick up objects as required in this case.
As I've understood regular IR sensors can only detect if there is an object and how far it is away, however they can't pick up said object's relative position on the y-axis. Is there any way to do this rather easily, perhaps with triangulation? I've looked into Bluetooth and RFID but haven't found anything particularly useful.

Why not just infra-red beams going to detectors. As the object travels it breaks different beams and triggers different LEDs. You don't even need an Arduino to do it.

How small can the IR beams become? I was under the impression that they would always scatter and thus interfere with each other.

Depends on how good your lenses are. If you want ultra-narrow then use lasers.

I feel that an array of IR transmitters and receivers could work for you.
If you put the transmitters/receivers in an recessed tube with (black, non-ir reflectant) separations, you can avoid crosstalk.
You should be wary that it may require some tweaking to find the right sensitivity.

Here is a video (and here) that shows this in practice. I like the fact that you don't need sensors on either side of the object.
You may also consider video-processing, but that's out of scope for Arduino.
Or use a Lidar.

There are many solutions to the problem.  For a free moving ball confined to a square flat surface with sides:

Choose IR LEDs mounted at such a height and distribution to be
blocked by the rolling ball.  Make sure at least 1 IR LED is blocked by the ball no matter where it is located.
Line two adjacent sides with strips of these IR LEDs.
Use the Arduino to light each LED one at a time at a frequency of about 40KHz.  Scan all LEDs within a second.  This should be adequate to locate a slow moving ball in 2D space.
On the two opposite sides mount a ASK Remote Control receiver.  A common device easily harvested from old entertainment equipment or bought from electronics part supply houses.
Use the Arduino to sense when the ASK Remote Control receiver detected or did not detect the flashing IR LED.
When the Arduino finds an IR LED that is not detected, the ball can be assumed to be between the IR LED and the ASK Remote Control receiver.

Note, the patter of intersecting lines will look more like two sets of bicycle tire wheal spokes.  Not like a checker board.  It may be better to confine the ball to a smaller square then that of the square where the transmitting IR LEDs and ASK Remote Control receiver are mounted on.


text:
SPI conflict with two shields - IOREF?
Update:
I've refactored the code to be very resilient to boards missing or not being able to talk to them. Then I tinkered with a bunch of pins and learned that it all comes down to the IOREF pin being connected to the USB Host shield or not. If it's connected, the USB shield "takes over", allows communication with it, but the CAN shield does not work. If the USB shield IOREF pin is not connected, but the rest of the shield's pins are, CAN works. If I disable the IOREF pin going into the CAN shield (and thus the USB shield also since it's on top), the CAN shield works fine still, but the USB shield does not.
Something happens when the IOREF is powered into the USB board and if it's not powered, you can't talk to it.
Original post:
I have the following setup:

Yourduino RoboRED board
Seeed CAN Bus Shield v1.2 http://wiki.seeed.cc/CAN-BUS_Shield_V1.2/
USB Host Shield https://www.arduino.cc/en/Main/ArduinoUSBHostShield

My issue is that if I connect only the CAN bus shield, I can initialize it without any problem, but when I connect the USB host shield on top of the CAN, the CAN shield becomes unresponsive.
I looked into the wiring and per the specs, the following is how the hardware is set up:

SPI bus runs on ICSP header for both shield, not on D11, D12 & D13. I could switch it for the CAN bus shield if I wanted/needed to, but I don't believe I shoudl be.
The trigger pin for the USB host is D10
The trigger pin for the CAN bus is D9 (since it's v1.2 of the board)
Both boards have power. USB board is on top since it does not have an ICSP male connector on the top side, only female on bottom.

I started to debug the code and traced down to this CAN bus function in mcp_can.cpp, which I've instrumented with debug:
INT8U MCP_CAN::mcp2515_setCANCTRL_Mode(const INT8U newmode)
{
    Serial.print("mcp2515_setCANCTRL_Mode with newmode = ");
    Serial.println(newmode);
    INT8U i;

    mcp2515_modifyRegister(MCP_CANCTRL, MODE_MASK, newmode);

    i = mcp2515_readRegister(MCP_CANCTRL);
    i &= MODE_MASK;
    Serial.println("i & MODE_MASK");
    Serial.println(i);
    Serial.println(MODE_MASK);

    if ( i == newmode )
    {
        return MCP2515_OK;
    }

    return MCP2515_FAIL;
}

The output when it fails is:
USB started ok
past SPI begin
mcp2515_init called
mcp2515_setCANCTRL_Mode with newmode = 128
i & MODE_MASK
0
224
Enter setting mode fall
res = 1

For reference, this is the mcp2515_modifyRegister function:
void MCP_CAN::mcp2515_modifyRegister(const INT8U address, const INT8U mask, const INT8U data)
{
    #ifdef SPI_HAS_TRANSACTION
        SPI_BEGIN();
    #endif
    MCP2515_SELECT();
    spi_readwrite(MCP_BITMOD);
    spi_readwrite(address);
    spi_readwrite(mask);
    spi_readwrite(data);
    MCP2515_UNSELECT();
    #ifdef SPI_HAS_TRANSACTION
        SPI_END();
    #endif
}

The whole file is here: https://github.com/Seeed-Studio/CAN_BUS_Shield/blob/master/mcp_can.cpp. I've tried setting SPI_HAS_TRANSACTION to true with no change in the outcome, though I also don't know exactly what this does.
This is my init:
void setup (void)
{
    Serial.begin(115200);

    // init can bus : baudrate = 500k

    if (Usb.Init() == -1)
        Serial.println("OSC did not start.");
    else
        Serial.println("USB started ok");

    delay( 200 );

    while (CAN_OK != CAN.begin(CAN_500KBPS)) {
        Serial.println("CAN BUS Shield init fail");
        Serial.println(" Init CAN BUS Shield again");
        delay(10000);
    }

    Serial.println("CANbus ready");
}

It seems to have something to do with the registers available for write by the CAN bus library whenever the USB board is or isn't present. The write fails when the USB board is there. Any thoughts as to why or other things to try would be greatly appreciated.

There's a hardware conflict between these two boards which seems to not be resolvable. The solution was to buy the Keyes USB shield, make sure only it has access to pins 9 and 10 from the Arduino and then wire pin 7 (or 8) into pin 9 of the CAN shield, while also properly initializing the CAN shield with that new pin.
Lastly, the Keyes USB shield's ICSP header isn't long enough, so you need to cut 2 mm off the male non-ICSP pins in order to seat it properly on the CAN shield.


text:
Software PWM implementation on ATTiny44 screws up timing functions
I've came up with a poor man's implementation of software-based PWM for the ATTINY44 and I'm kinda stuck now. It works but it screws up the timing functions badly (delay, delayMicroseconds) no matter what timer I use for the ISR (timer 1 or 0). The delay in my example is more like 1 second than 100ms. Can somebody point out what I'm doing wrong? :)
uint8_t pwmled[11] = {0};
volatile uint8_t currentStep = 0;
uint8_t p[11] = {PORTA0, PORTA1, PORTA2, PORTA3, PORTA4, PORTA5, PORTA6, PORTA7, PORTB0, PORTB1, PORTB2};

void initTimer1() {
  cli();
  TCCR1B = (1 << WGM12) | (1 << CS10);
  OCR1A = 64;
  TIMSK1 = (1 << OCIE1A);
  sei();
}

ISR(TIM1_COMPA_vect) {
  if (currentStep < 100)
    currentStep += 1;
  else
    currentStep = 0;
  for (uint8_t x = 0; x <= 10; x++)
    (currentStep < pwmled[x]) ? (x < 8 ? PORTA |= (1 << p[x]) : PORTB |= (1 << p[x])) : (x < 8 ? PORTA &= ~(1 << p[x]) : PORTB &= ~(1 << p[x]));
}

void setup() {
  initTimer1();
  for (int i = 0; i <= 10; i++) {
    pinMode(i, OUTPUT);
    pwmled[i] = 1;
  }
}

void loop() {
  pwmled[random() % 11] = random() % 100;
  delay(100);
}

What speed is your ATTiny44 clocked at? Any way to confirm this?

I've solved the issue, look in the comments below :) The attiny is clocked @8MHz using the internal oscillator.

What you are doing wrong is:
The problem is your interrupt handling routine lasts too long. Since inside ISR() interrupt flag is automatically cleared, timer0 interrupts are being missed and delay() depends upon timer0 interrupts.
To confirm the problem is ISR, remove the for loop and just toggle one pin instead. I bet the delay will then be as it should.
Try to put sei() at the beginning of your ISR to see what is going to happen with the timming of the delay - but that is not the right way.
Instead of using delay() (based on timer0) you can count the number of timer1 interrupts but ISR routine must not last longer than the time between two interrupts and your ISR spends quite a few T-states inside the for loop. A rule of a thumb is ISR has to be very short (fast) - unless you really know what you are doing. For example, in one of my devices I am using a very long ISR routine (in fact the firmware consists of only the ISR - there is only sleep_mode(); in main) for which I know it sometimes lasts longer than the time window between interrupts and I know some of the interrupts are occasionally being missed. However, these few missed interrupts are not critical to that particular application and I am sure the interrupts are being missed rarely.
You could change OCR1A value to increase the time between interrupts but then you would have lower PWM frequency.

Thanks a lot for the clarification and help! I've come to a solution that works well enough for my needs (driving a bunch of LEDs). I have no idea how one's supposed to reply with a block of code but there's the link, now the timing functions work as usual. Indeed, the first code was more shitty than this one, the ISR overlapped with itself causing either timing to go nuts or a substantial amount of flicker (depending on what timer I've set to trigger the interrupt).
Again, thanks a lot :D

I usually just set a flag in the interrupt routine (or use the interrupt flag itself) and handle it in my loop. If the interrupt has a substantial amount of code/looping/calculations.


text:
How to fix 12V RGB LED Strip connection to NodeMCU?
I am trying to hook 12V RGB Led Strip (LTROP SMD 5050 RGB LED Light Strip) to a NodeMCU unit. I know there are many different tutorials on this and I am very new to wiring and electric circuits.
I used BUZ91A n-MOSFETs and 150 Ohm resistors for each of the RGB channels, and the board is using it's own power supply via usb.

I use very simple code to check if the setup works:
#define REDPIN D3
#define GREENPIN D1
#define BLUEPIN D2

#define FADESPEED 5     // make this higher to slow down

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);
  Serial.begin(115200);
  Serial.println("Finished setup");
}

void loop() {
    analogWrite(REDPIN, 800);
    analogWrite(BLUEPIN, 1020);
    analogWrite(GREENPIN, 400);
    delay(100);

  Serial.println("Finished loop");
}

I suspect nothing works because NodeMCU and the LED are using different power sources and the fact they have common ground doesn't seem to be everything required.

What happens when you try to PWM the built-in LED? BTW, you don't have to execute analogWrite() again and again in the loop, it is enough to do that only once in setup() but that isn't the problem.

It works fine with D0 - it changes the brightness based on value in analogWrite()

The connection is OK. Which NodeMCU board/version do you have? The pin mapping may be different from the Arduino defines. For example my NodeMCU (LoLin) has built-in LED on pin 2 which is D4. D0 is pin 16 so the other pins might differ too on your board.

Looks like version 1.0 to me. The Arduino IDE "Get Board Info" does not tell much: VID: 10C4, PID: EA60

I would first try to blink a LED using digitalWrite() on D1, D2 and D3 (one by one) to see if these outputs are really associated with the pins where you connected the PWM outputs (just don't forget the current limiting resistor, max source current is 12 mA and max sink current is 20 mA). And you might first try to change the PWM frequency, for example try with analogWriteFreq(200);. The default PWM frequency is 1 kHz and that should work but nothing to loose if you try.

I connected a 3V LEd to D1 (used for G channel in my setup) pin and ground and it stays led all the time. Changing the analogWriteFreq() did not help, but the onboard led changes it's brightness with either.

If I just try to digitalWrite(pin, HIGH);, the 3V led works fine while the RGB leds on the strip are not reacting

Did you use PWM to light the LED on D1 or did you toggle the output with some delay to confirm that really is D1 pin? Next I would try to connect a jumper wire from one of the 3.3 V pins on NodeMCU board to the resistor connected to MOSFET's gate to see if that will trigger the transistor and light up the corresponding LED strip channel.

I am sure it's the right pin. I think it's something about the wiring or maybe the mostef is not the right type or something.

The MOSFET should be OK, I checked the datasheet. Try to trigger the MOSFET by connecting NodeMCU 3.3 V pin directly to the resistor at the transistor's gate, as I suggested in the last comment. Or try to trigger it with external 3.3 or 5 V. Double check if the strip is connected correctly - remove the MOSFET and use a jumper wire to short the breadboard contacts where source and drain were before you removed the transistor.

I haven't figured it out but I noticed that sometimes when I unhook the nodeMCU from the ground, the leds on the strip go bright.

Wow, I think I got it now - when I swap the D0 pin to Vin (5V in my case since I am using USB power), the leds on the strips work. Does it mean that the D* pins aren't giving the MOSTEF enough current?

No, MOSFET's (not MOSTEF, I can see you are repeating the same 'typing' mistake) gate current draw is near zero. The problem could be the voltage but I still can't tell because you still didn't try what I suggested already twice :-) To say one more time: There are a few pins on NodeMCU board marked with 3 or with 3V3. Connect one of these pins to the resistor in transistor's gate to see if 3.3 V from NodeMCU can trigger the transistor. Only then we could know what's going on.

Nope, the 3v3 does not trigger it - only the 5v does

So now we finally know the reason is MOSFET's threshold voltage is too high. The solution is to drive the gate with NPN transistor (you can use BC547 or 2N5551 or similar). You have to connect it's collector to 5 V and it's emitter to GND. Put 10k or 100k resistor between 5 V and the collector, connect the collector to MOSFET's gate and GPIO to the base of NPN transistor. Put some resistor between GPIO and the base of the transistor, maybe 4k7 or similar.
Note:
HIGH from GPIO will switch off the LED strip and LOW will switch it on.
Another solution is to use MOSFET with lower threshold voltage.
EDIT:
If you want to avoid adding NPN transistor you can use NTD5867NL MOSFET which has max threshold voltage 2.5 V so it will for sure work with 3.3 V at the gate but is rather expensive (about $4). Much better solution is adding cheap NPN transistor.
EDIT:
Here is the schematic:

simulate this circuit – Schematic created using CircuitLab
EDIT:
Here is the correct wiring:

Can you please advise on a fitting MOSFET model to use?

I'll take a look through some other MOSFETs and write you a note if I find the one which might work.

I've edited the answer and added the data about MOSFET which will for sure work with 3.3 V.

Thank you so much for following through on this problem with me. I wanted to ask one last question. Are there any sort of Led Strip Driver Boards I could just purchase and wire to my nodeMCU? I suck at all this wiring and circuits (you can tell) and the further I go the better I understand I'd rather stick to the programming side of things. Also, I am trying to finish by project on time for someone's Christmas gift. Again, thanks a lot for your kind help.

I'm not aware of such driver board. What I've found is only this and this RGB LED strip controller, but that is another way of controlling the strip. It has the onboard IC for PWM and you have to send the data using clock&data signals. This is the IC's datasheet. But you really don't have to run from adding just one more transistor, you can do that in a minute. BTW, you may accept the answer if you liked it :-)

I will try to connect the transistor - haven't figured the wiring yet. Base, collector, all that - have to do some reading first :)

Here you are the schematic. NPN transistor is just like MOSFET except instead of G, S and D you have B, E and C. Emitter is marked with an arrow and base is where you connect the signal from GPIO. Resistor values are not critical but if the values are to high you might need to lower the PWM frequency.

I guess I failed to wire these correctly. I did the wiring and the led does not work BUT if I unplug the wire from transistor base and grab it with my bare hand, the led will shine :)

I tried without resistors - didn't work
I tried to check the voltage on the 5V pin - it's 4.6V
I also checked continuity between different wires on the board (just to make sure everything is connected) and it appears so, I am now out of options :)

I also tried a different power supply for the nodeMCU, this one gives 4.9V and 3A - hasn't helped; I also tried hooking up a different LED strip (regular one color) - hasn't helped either.

You didn't wire the circuit correctly. You connected the base of NPN transistor directly to the MOSFET's gate (the result is as if there isn't NPN transistor), one resistor is missing and you connected the collector of NPN transistor to 3.3 V instead to 5 V. If that even is the collector. Which NPN transistor did you use?

Here you are the wiring diagram. You can use the same 12 V which you are using to power the LED strip instead of 5 V to avoid using 3 different voltages. But, as you are probably getting 3.3 V from 5 V then it isn't a problem if you use 5 V. Of course, a MOSFET must be n-channel and not as in the picture.

BTW, why would you unaccept the correct answer just because you did not wire the circuit according to the schematic I gave you? :-)

I only unticked it because people normally ignored answered questions and since I hasn't gotten it resolved yet, I wanted to sort of let others tip in seeing an answered question, that's all. It actually works now. Thanks a bunch. I now realize I need to stick with programming and get OTB hardware as much as possible :) Again, many thanks!

One thing I noticed is that it works in inverted mode - like when I plug it in, without even getting the nodemcu powered up, the leds are led. And then when the nodemcu commands HIGH to the pin, the led turns off. And if I remove the connection between the third leg of 2N5551 and the +12V, it keeps working the same way without any difference. I know I most likely messed up the wiring and I can't stop laughing at how much time I spent with this and all the trouble I cause people with my stupid questions but I just had to share this :)

You did not mess the wiring this time :-) Take a look at the note I wrote in my answer already before I gave you the schematic where I said: 'HIGH from GPIO will switch off the LED strip and LOW will switch it on'. That is because NPN transistor works as inverter. As for avoiding hardware - do not avoid it!! Being a programmer means you learn fast and your SO reputation confirms you have that ability. So, instead of avoiding - learn it, it's as much fun as programming. I am glad your circuit finally works and hope you'll finish the gift on time, before Christmas! :-)

On the above circuit mosfet switching will depend on collector current as I have 24v/5A source connected to the drain, for switching I am give 5v on gate