How Do I Properly Ground my Arduino Leonardo using Capacitive Sensor?

The documentation for that library is recommending that you place a 100 pF capacitor between the sense pin and ground.

However, I personally suspect you will get the best results when the user's presence affects at small mutual capacitance between a sense surface and a ground surface.

One idea could be to have a large ground plane, and on it a smaller insulated "sense" plate.

Another could be to run two parallel traces in a spiral filling a large area

Do take care to secure you wires - they are part of your sensor too, and if they move relative to each other they will alter the baseline.  Any other mobile cables in the vicinity can have the same effect, especially if they contain a ground that can exhibit capacitance to the sense node.


Is there any way to create some AI with Arduino?

If for IA you mean just decisions based on some inputs (sensors), yes.
The main problem on that kind of applications is the memory. The Arduino has a limited quantity of flash and Ram. Really limited.
A way to improve it, is to have a Web server and use the Arduino to send the data to your server over a WiFi module.
As said, the only limit on Arduino is the memory.


You can either use the 3.3V pin to supply power to the board, or use the Vin pin.

By using the VIN pin to power goes through a (step down) voltage regulator, that provides a nice stable 3.3V to the board. The regulator in the Nano 33 IoT is the MPM3610, which requires an input voltage of at least 4 - 4.5 Volt. Which is more that a LiPo or LiFePo single cell can supply. You could use a multi-cell battery pack. Or a USB power bank. So this solutions is not really ideal.

The other option was to connect the battery directly to the 3.3V pin. The voltage of a LiFePo however changes as it is being discharged. The voltage is around 3.65V when full, and 2.5-2.75V when "empty". The 3.2V rating is called the nominal voltage (kind of an average voltage).
So it's a bit too high when full, and too low when empty. The voltage also isn't regulated, so it can fluctuate a bit, based on the amount of current that's being used.

The maximum voltage for the SAMD21 on this Nano is 3.63V. Maximum voltage for the gyro (LSM6DS3) is 3.6V. The absolute maximum voltage for the radio (NINA-W10) is 3.6V.

So a full LiFePo is slightly too high for the Nano. Though I think you should be fine. But don't try this with a regular LiPo of Lion battery (4.2V when full).


Measure low current with variable voltage

What you want is called a constant current source. You can actually build a simple one using one transistor ; but a better one uses two transistors - as in the left example below - see this page for explanations.

Here the leds would be your load, R=680 Ohm would give you about 1mA - and you would need to increase the value of the 2k2 resistor to somewhere around 22k.

The problem is that, as John Williams noted, forcing 1mA through a high resistance requires high voltage : 1MOhm would need 1kV, 10MOhm needs 10kV etc. That's very dangerous voltages! and quite some power as well : 10kV at 1mA means 10W.

I think you need to define your needs first :

What is a tolerable error on the absolute value of current? (Would constant 1.1mA be OK?)
What is a tolerable error on the current variations? (Would current varying between 1.19mA and 1.21mA be OK?)
Do you absolutely need 1mA right from start? Or can you accept a lower current at start, growing with increased conductivity until 1mA is reached and then being held nicely constant?

If the above examples are fine, a current source as described above would do the job nicely for less than 1USD.

If you really need a constant current source right from the start, then be prepared to work with expensive and dangerous pieces of equipment.


How to set "IPAddress ip" using a variable?

Here's how I do it (for an Arduino that connects to my Mosquitto server) using wired ethernet (WiFi works the same way):

#include <Ethernet.h>
#include <PubSubClient.h>
EthernetClient ethClient;
PubSubClient client(ethClient);

byte mac[]    = {
  0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe
};
IPAddress ip(192, 168, 1, 75);
IPAddress server(192, 168, 1, 11);
void setup() {

  client.setServer(server, 1883);
  client.setCallback(callback);

  Ethernet.begin(mac, ip);

}


error: invalid conversion from 'char' to 'char*' [-fpermissive]

You're calling your function with a single char, specified by phoneNumber[i], but your function is expecting an array.

If you change your call to:

LcdString(phonenumber)

then that will pass the entire array.

Are you trying to say that you're storing multiple phone numbers?  i.e. a two dimensional array?  Check out the String reference for more details: https://www.arduino.cc/en/Reference/String


character input for an integer variable?

A0 and A1 are not characters or what you mean probably: strings.
Because it would be written as "A0" and "A1".
The types of A0 and A1 are probably integers or another numeric type.

However, these are probably defined as (constant) integers, e.g.:

const int A0 = 100;
const int A1 = 101;

(note 100 and 101 are random numbers)

or defined by a macro. e.g.:

#define A0  100
#define A1  101

So the variables A0 and A1 are actually integers (or assigned as numeric values by a define).


Arduino Uno: Driving a small LED strip with 2N3904 NPN

The analogWrite works only on PWM pins (in your scheme it's marked by ~). On the other pins it's possible to set only LOW/HIGH (values under 128 are translated to the LOW)

Not to mention weirdly used NPN with LEDs as negative feedback. But that's why it doesn't burned out yet. The usual way is connect the Emmiter to the ground and base is driven over current limiting resistor (about 1k).
This is how we usualy use PNP transistor (again with 1k resistor and emitter to the Vcc, not the collector). But PNP won't work with 5V logic and higher Vin than 5V as there will be current flow from 0V or 5V to the Vin.


When using

if(BT.available())

that's doing the same as

if(BT.available() > 0)

But then you are reading 2 bytes, though you cannot be sure, that there are 2 bytes to read. The data is transmitted serially, so even when you send it on your phone in one bunch, it does not get transmitted as bunch.

Try to use

if(BT.available() >= 2)

Also makes sure, that nothing else gets send over serial besides the numbers (often there is a line ending send implicitly depending on the used app).


Problems reading I2C sensor when using a Xbee module

I have solved the problem by adding a delay just before I select the continuous measurement mode.

void setup(){
  //Initialize Serial and I2C communications
  Serial.begin(9600);
  Wire.begin();

  //Put the HMC5883 IC into the correct operating mode
  Wire.beginTransmission(address); //open communication with HMC5883
  Wire.send(0x02); //select mode register
  Wire.send(0x00); //continuous measurement mode
  delay(100);
  Wire.endTransmission();
}


You could look into buying an ESP8266 WiFi module (cca. 7$) and add it to your existing Arduino. If you're not constrained with money that much I would then recommend look up Arduino Industrial 101, which comes with WiFi out of the box. You could then use MQTT protocol to send messages to a broker and your phone. There are alot of nice tutorials online on MQTT.


How can I automatically get the time from the computer into an alarm clock (starts at 00:00 when plugged in)?

There are several ways, and they are covered in the comments above.

The answer to your question. Via Arduino USB to serial interface. and a simple batch file on a windows computer example:

@echo off

set datetimef=%time:~0,2%.%time:~3,2%:%time:~6,2%

echo %datetimef% > COM5

COM5 is used as a example, your serial port can be another number.

The format in the example is hour.minute:second


How to start serial monitor on Windows startup

You can't.  You would need to have some way of telling the Arduino IDE to open the serial monitor and connect to a certain serial port. That can't be done.

Instead you would need to use some other third party serial communication program. How you would configure that depends on what the software is.

For Windows 10 you can make a program run at startup by following these instructions. You still need to configure the software to automatically connect to the right port at the right speed, of course.


Is it possible for Arduino firmware to recognise only one computer?

No.

However, it is possible to place unusual and/or secret requirements on the computer's drivers or application software - however those software components could be present on multiple computers unless you also take measures to node lock them.

You could customize the USB VID/PID and descriptors, causing the device not to be recognized by a usual driver
You could alter the behavior of the USB interface (or bootloader and sketch) to require unusual operations - either obscure, or even secret to the level of unique-per-unit cryptography
Or most simply, you could just use a board without a USB interface and bring your own.  Especially if you lock the flash, there's not a whole lot others can do except entirely erase your work and be left with an unusually expensive ATmega evaluation board.

Do note also that most operating systems make it possible to easily intercept the raw USB traffic going to/from devices, so someone who can see it in operation can learn a lot about how it is working.

If you want to play games with odd USB implementations, you'll probably do better with a direct USB board like a Leonardo - and you will certainly want to have an ISP setup to recover it, as your efforts will no doubt break it many times before you get something on there which works as intended.


Is setting clock divider worth changing on delay() to save power?

Reducing the CPU frequency should work, but I would expect better
savings by sleeping during the busy loop:

#include <avr/sleep.h>

void sleepy_delay(uint32_t duration)
{
    uint32_t start = millis();
    while (millis() - start < duration) {
        sleep_mode();
    }
}

Note that the sleep will be interrupted at least on every Timer 0
overflow interrupt, which happens every 1024 µs (that's what
increments the value returned by millis()), so there is no risk of
oversleeping. You could add some power_*_disable() calls for better
savings.


Reverse engineering of a bluetooth sensor

Looking at the datasheet, I interpreted it as:

Byte 1 - 0x46

Indicating this is a unidirectional device (bit7=0) that uses fixed time sending (bit 6=1 which doesn't seem correct) and it is of type 'door contact' (bits 0-5=0x06)

Byte 2 - 0x00/0x02

Indicating that the door is open or closed (bit 1 = 0 or 1). I also think that it indicates there is 'enough battery power' (bit 2 = 0), and the 'anti-tamper' has not been activated (bit 0 = 0)

Byte 3 - 0xXX

This is the 'Frame ID' - counting up for 0x40, to 0x5F then looping ?

Byte 4 - 0xXX

Checksum.

I'd do three things to test this theory:

Run the battery down a lot and see if the battery power indicator changes (byte 2, bit 2).
Open the case and see if the 'anti-tamper' bit changes (byte 2, bit 0)
Do sufficient switching to determine if byte 3 loops around as expected.

This these don't work out then you're likely looking at a different model.


If you are sure to disable pull up on arduino side you are safe, as i2c works in open-drain mode, but the logic level "high" of arduino is about 3.2v, so it would be unstable.

Otherwise i2c pin of rasp are NOT 5v tolerant, so you must be sure the voltage on the bus does not exceed operative limit; as you calculated ~3.5v should be good on raspi, but please check on datasheet.

Also, you should check the total current on the bus, but as atmega resistor as so high,it should not pose a problem with raspi (but may give problem with passive i2c, that you can solve with a external pull up)


how to solve Varing duty cycle value while using Pulsein()

I would start by removing Serial interrupts from the pulseIn period.

void loop() {
    pwm_value_H = pulseIn(PWM_PIN, HIGH);
    pwm_value_L = pulseIn(PWM_PIN, LOW);
    Serial.println(pwm_value_H);
    Serial.println(pwm_value_L);
    D = ((pwm_value_H) / (pwm_value_H + pwm_value_L)) * 100.0;
    Serial.print("D=");
    Serial.println(D);
    Serial.print("D=%");
    Serial.flush();
}

For higher accuracy I would then look to the Timer based Input Capture.

Cheers!


As jsotola has pointed out, there is a mistake in your code. Remove the line

buttonstate = digitalRead(C)

and replace

if(buttonstate == HIGH)

with

if(C == HIGH)

Moreover, I suggest you take a look at the debouncing example in order to make the sound "smoother" ie no jitters because of the button


Trying to Pulse an LED a number of times outside of the main loop

You'll want a class function that decides whether 'now' is time to toggle the LED or not, and returns quickly. Call that function frequently from your loop function. Your other class functions will set or clear the whether the LED is to toggled, and when, how many times, etc.  Something like the following pseudo-code, which is not a full solution but should point out the essential details:

void loop()
{
   myStatusLights.updateLED();     // call this frequently
}

...

void StatusLights::updateLED(){
  if LED_active,
     if it's time to change the LED,
        toggle LED on/off;
        if LED has toggled enough times,
           set LED_active false;
        endif;
     endif;
  endif;
}

Update:

  How would you refresh the count, track the pulses, and refresh the state of the status light without any parameters?

Some class-function must initiate the blinking, whether it knows to do it itself or it is called from your application code. That class-function will need to set those parameters. If it to be called from outside, perhaps the outside sets them - ? Only you know that. Either way, they will need to get saved in the class' private data so the .updateLED() function can have access to them. The .updateLED() function will, for instance, count down the remaining number blinks to display, keep track of whether the LED is on or off, actually turn it on or off, etc., until there is nothing left for it to do. In that case it just quickly returns without doing anything.


Lua is an interpreted language. That is, the compile phase turns Lua source code into intermediate "pseudo-code" which the Lua interpreter then runs. It doesn't compile into machine code, and therefore there is nothing that could be uploaded to your Uno as a "hex" file.

In any case, with only 2 KB of RAM, it wouldn't be very practical to attempt to run Lua on a Uno. I like Lua personally, but running it on the (AVR) Arduinos just isn't practical.


What is the proper way to send data through http using sim908?

You mention two different error messages.

1. AT+HTTPINIT fail

You get +CME ERROR 3. Which means "operation not allowed".

This can be due to an improperly closed HTTP setup.
If you get this error (or just always do before setting up), call AT+HTTPTERM to be sure that it's closed.

2. AT+HTTPACTION=1

I notice you're trying to do a POSTmessage, while your variables are in the URL (which is GET style afaik).

I've found a source that states you need to call AT+HTTPDATA with apropriate values.

  Tell the module that you will be sending 192 bytes of data and it can timeout after 10 seconds of inactivity.

After that, the device will say DOWNLOAD, and you can send the POST body.

  After this command you get the DOWNLOAD URC then you can type in 192 bytes of data within 10 seconds. The typed data is filled in a local buffer of the module and is not yet posted to the server. In the post body is the multi part form data which contains the necessary headers and data to post a file with name data.txt with 10 bytes of data.
  AT+HTTPDATA=192,10000

And after that you can send the POST message.

  Execute the HTTP POST command so that the buffer contents are POST to
  the server AT+HTTPACTION=1 OK

You will get a return message that states the HTTP code (200 'OK') and the amount of bytes received in the return message.

  +HTTPACTION:1,200,141
  This URC means that the data was successfully posted to the server and received 141 bytes of data.
  which is the server response to your HTTP POST

You can use AT+HTTPREAD to receive these bytes.

  The below command tells the module that we want to read the received data AT+HTTPREAD The below is the data
  received from the server
  +HTTPREAD:141 Successfully dumped 0 post variables. View it at http://www.posttestserver.com/data/2015/10/07/07.41.291690063480 Post
  body was 0 chars long. OK

(Scroll a fair bit down in the source, the first part is on HTTP GET: http://www.raviyp.com/embedded/194-sim900-gprs-http-at-commands)

You could also omit this by using HTTP GET since it's somewhat easier.

If all else fails, you can set up a TCP IP connection with the GSM module and manually set up the HTTP GET/POST message.


Data type explanation regarding analogRead of a photoresistor

You should keep it uint16_t.
See: analogRead.
It shows the return value is a 10 bit number, which means a value of 0 to 1023.
If you use uint8_t, which is an 8 bit value, it only can store values from 0-255.
This means if the value is higher, the most significant bits are clipped/removed, and you only have the value module 256 left.
With a 16 bit value, you will have the left 6 bits unused, but this does not matter. It has the 10 bits you get from the analogRead function.
Example
Assume the value is 1000, which is in binary:
11 1110 1000

Written in 16 bits (using uint16_t), move it to the right and prefix with zeros you get:
0000 0011 1110 1000

However, if you try to store this in 8 bits (using uint8_t) you get:
(removed) 1110 1000

Which is the value 232 instead of 1000.
Some guidelines:

Always use a type that fits the value you want to store (in worst case).
If you know for sure your value will be non-negative, use an unsigned type (e.g. uint8_t).
If you want to preserve memory (or good practice) use a value that is not necessarily big (thus if you know a value will never be more than 1023 like in your case, don't use uint32_t).


How can my library source code instantiate an object from another library?

Why not have your class just extend the MFRC522 class?

#include <MFRC522.h>

class UltimateRFID : public MFRC522 {
    private:
        MIFARE_Key key;

    public:
        UltimateRFID(uint8_t ss, uint8_t rst) : MFRC522(ss, rst) {}
        // your other methods
        void initialize();
};

void UltimateRFID::initialize() {
    //digitalWrite(49, HIGH);
    digitalWrite(2, LOW);
    for (byte i = 0; i < 6; i++) {
        key.keyByte[i] = 0xFF;
    }
    PCD_Init();
    if ( ! PICC_IsNewCardPresent()) {
        return;
    }
    if ( ! PICC_ReadCardSerial()) {
        return;
    }
}

UltimateRFID rfid(53, 5);

void setup() {
    rfid.initialize();
}

void loop() {}

Your class then becomes a "flavour" of MFRC522 with additional functionality. It can access all the public functions of the MFRC522 class, since they are now a part of your class.

Anything you can do with an MFRC522 object you can now do with your object. As well as your extra functions.


Built-in LED turns on when I touch the input port

When you are reading digital data through a pin you must make sure that you are steering that input pin to a stable state when no input is present.
You can do this by using either a pullup or a pulldown resistor which you can connect externally or you can use the in built pullup.
You can use a 10k ohm resistor to pulldown by connecting it to the button end where your digital pin is connected and the other to ground.
By doing this your above code must work fine.
I think by touching the pin you are actually pulling the voltage state down.
Hope this helps


If the LED is ON when LOW and OFF when HIGH then chances are the LED is connected between +3.3V and the IO pin with a suitable resistor.

When HIGH the IO pin is at +3.3V, so the voltage across the LED is 0V (3.3 - 3.3 = 0) and it is turned off.  When LOW the IO pin is at (nearly) 0V and the voltage across the LED (and its resistor) is 3.3V (3.3 - 0 = 3.3), so it lights up.


I'm trying to understand your code.

It looks like x is a state variable, with the following values:

2 = "Looking for start brace (`{`)"
1 = "Found! Now accumulating `day` until stop brace (`}`)"
0 = "Finished!"

If so, you may instead want to use the following:

enum States { Looking, Adding, Done };

// int x = 2;
States state = Looking;

// x = 1
state = Adding;

// if (x==1){
if (state==Adding) {

If you follow the flow of code, when number is still 0 and x finally becomes 0, you:

Print out number - the first line of your output;
You then miss the main if (number is not greater than 0);
And enter the else (which is satisfied);
And then you immediately clear your hard-earned day.

The second time through, after x becomes 0 again, this time you:

Print out number - the second line of your ouptut;
You do enter the main if:

You assign day to Combo[1]
You print out only the first seven entries in the the array (you want <=7, not <7)

This should print out 0{?}000000 (I don't know what day should be).
The fact that it doesn't seems to imply that your concat() failed. Can you please change it to

// day.concat(sym);
if (!day.concat(sym)) {
    Serial.println("concat() error!");
} // if

You then print out the row of dashes - and start a new line.

The third time through, it seems to work - you get your {$ "first string" $} (where $ represents \n and/or \r - can you strip those out?)

      // if (x==1){
      //    day.concat(sym);
      if (x==1 && sym>=' '){ // Don't concat new line characters!
          day.concat(sym);

And the final few times concat() seems to have failed again.

The reason I say "concat() has failed" is that it looks like day is still "" when it is assigned to Combo

Edit

You've changed the code so that the main if now does the following:

Assigns day to Combo[number-1];
Prints out day - this seems to work;
Assigns day to Combo[number-1] again;
Prints out a line of hyphens - this works;
Prints out Combo[number-1] - this does NOT seem to work;
Prints out two lines of hyphens - this works.

Since 5 is printing out nothing, it implies that 3 failed. This really does look like you're in a low-memory condition, and the system is failing to allocate memory from the heap.

You don't say what Arduino you're working on - note that most don't have much memory, and if you're already parsing a JSON file you've probably used a lot of it. You also don't say which version of the Arduino IDE you're using. There was a String bug in the earlier versions.

Rather than trying to use the String class (a renowned heap hogger), you should try to use normal char arrays and work the buffer management yourself.


Pin 53 is just the default "slave select" pin. There is nothing special about it. You can use any other pin as slave select, as long as the libraries for your devices allow it (check the documentation and tutorials for those libraries).
You cannot transmit information with analogWrite() since it isn't really analogue (it's PWM), and analogue doesn't have enough definition for reliably representing more than a handful of discrete values anyway.


To understand this you have to start thinking in binary.

The | operator is "Perform a binary OR on these two values".

The <<8 is "Shift this value 8 bits to the left".

If you have two 8-bit values, say (in hex) 0x37 and 0x42, and you OR them together you get:

0x37 = 00110111
0x42 = 01000010
--------------- |
0x77 = 01110111

In each column where there is a 1 in either value you get a 1 in the result.

Now if you shift the first number 8 bits to the left, you end up with:

0x3700 = 0011011100000000
0x0042 =         01000010
------------------------- |
0x3742 = 0011011101000010

You do this when a 16-bit value has been split into two 8-bit values and you want to join them back together again into the original 16-bit value.


Where is all of the Arduino Documentation?

I'd like to add to what JRobert said of finding the information the "hard way"(i.e. looking into the datasheet of the chip it used, and understand how it works from schematic).
In the Arduino world, a lot of hardware/shields are so called Open Source Hardware, meaning that many companies can produce the same hardware with the schematic that is released under Open Source hardware license. China happened to be the country where it has the complete value-chain from components, to manufacturing and cheap labour. They are good in producing such products at large quantity and selling at low price, and they are not necessary good in developing original product, and certainly not in documentation (especially in English). These products are not necessary China "knock-off" as many people call it.
Since it is open hardware products, there are multiple vendors producing it and there are many information available on the internet, and take the example you provide, it is "1602 LCD Keypad Shield", and if your google it with this phase, you will soon find this pdf which is not exactly from the same company of your shield, but it is remarkably similar that you can try.
This applied to many hardware/shields that are available in the market. I hope this provide a general guidance and an "easy way" to find the information in your tinkering journey. Of course, if you want to learn more, go dig out the datasheet and schematic as JRobert mentioned.


Change max and min read value of potentiometer

You cannot declare that the min and max values of a potentiometer are x and y. What you can do is map() the values of the potentiometer to your own desired scale.

To do this, you'll have to get the following values:

Minimum value of the potentiometer, pMin
Maximum value of the potentiometer, pMax

But these values aren't what you want. For example, what you want is pmin to be 0 and pMax to be 100. So, you'll have to scale pMin and pMax to those values.

For this, you use the map() function. What map() does is changing the value in a given scale, to that of another scale. Let's get some example code:

int pMin = 14;  //the lowest value that comes out of the potentiometer
int pMax = 948; //the highest value that comes out of the potentiometer.

int x = 0;  //we will use this value to store the readings of the potentiometer

void setup(){
  Serial.begin(9600); //Serial monitor can be used to check the values
}

void loop(){

  x = analogRead(A0); //connect the potentiometer to the A0 pin of the Arduino

  Serial.print(x);  //prints the original reading

  x = map(x, pMin, pMax, 0, 100) //take the value of x, compared it to the scale of the potentiometer pMin to pMax, and translate that value to the scale of 0 to 100

  Serial.print("\t"); //a tab to make the reading more easy
  Serial.println(x);  //post mapped value, println is a linebreak as well
  delay(100); //so we don't post to much in the serial and you can read data better.
}

With this example you can clearly see how your potentiometer behaves and how you can use the 'weird' values from its readings in a useful way for your projects.


Arduino NANO (CH340) error while flashing bootloader

Hit reset randomly in the first few seconds of uploading/burning.


The standard avr-libc does not have float support enabled in the printf family of functions. This is because float support would bloat your code massively, and most people don't need it.
It is possible to enable it through some black magic (I don't know what, but someone else may), but in general you don't want to since there are better ways.
Typically you would use dtostrf() to format your float into a char array separately. Or if all you are doing is printing to serial then you wouldn't even format it into a string in the first place.
Serial.print(F("Temp = "));
Serial.print(temp);
Serial.print(F("  Humidity = "));
Serial.println(humid);


In Arduino parlance the word "Verify" is used (erroneously) to mean "Compile the code into a binary or HEX file, but don't upload it to the board".

To compile (and thus "verify") the code just pass the compile command to arduino-cli with the board you want to compile for and the sketch you want to compile.


Why does the pin 2 of arduino Mega stay always HIGH?

Pin 2 connects to the controller's PE4, which is a GPIO pin, which can also be used for PWM. You should be able to use it either as input or output, and both high and low. It could be that setup initializes it as output high, while you would usually have uninitialized pins as input.

Have you tried to make it low, or make it input?

digitalWrite(2, LOW);

should make it low, while

pinMode(2, INPUT);
int pin2Status = digitalRead(2);
digitalWrite(13, pin2Status);

will copy the status of pin 2 to the on-board LED.


Is there a way to pause Program execution?

This article gives a great example of multitasking by using FreeRTOS.

I am pasting the sample code snippet which is pretty much self explanatory.

#include <Arduino_FreeRTOS.h>

// define two tasks for Blink & AnalogRead
void TaskBlink( void *pvParameters );
void TaskAnalogRead( void *pvParameters );

// the setup function runs once when you press reset or power the board
void setup() {

  // Now set up two tasks to run independently.
  xTaskCreate(
    TaskBlink
    ,  (const portCHAR *)"Blink"   // A name just for humans
    ,  128  // Stack size
    ,  NULL
    ,  2  // priority
    ,  NULL );

  xTaskCreate(
    TaskAnalogRead
    ,  (const portCHAR *) "AnalogRead"
    ,  128 // This stack size can be checked & adjusted by reading Highwater
    ,  NULL
    ,  1  // priority
    ,  NULL );

  // Now the task scheduler, which takes over control of scheduling individual tasks, is automatically started.
}

void loop()
{
  // Empty. Things are done in Tasks.
}

/*--------------------------------------------------*/
/*---------------------- Tasks ---------------------*/
/*--------------------------------------------------*/

void TaskBlink(void *pvParameters)  // This is a task.
{
  (void) pvParameters;

  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);

  for (;;) // A Task shall never return or exit.
  {
    digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
    digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
    vTaskDelay( 1000 / portTICK_PERIOD_MS ); // wait for one second
  }
}

void TaskAnalogRead(void *pvParameters)  // This is a task.
{
  (void) pvParameters;

  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);

  for (;;)
  {
    // read the input on analog pin 0:
    int sensorValue = analogRead(A0);
    // print out the value you read:
    Serial.println(sensorValue);
    vTaskDelay(1);  // one tick delay (15ms) in between reads for stability
  }
}


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


As the page Sharp Memory LCD Breakout A2 shows, it seems that you need some additional circuitry to drive the display, such as capacitors and resistors. This is why breakout boards are usually employed. Quoting the page:

  This is a simple breakout board for Sharp’s new Memory LCD displays (
  LS013B4DN02 and LS013B4DN04). It brings all pins to a 0.1″ header and
  provides necessary caps and resistors. The new revision A2 also adds
  an optional boost converter for those wanting to run 5V display from
  sub 3.3V supply.The footprints are there, but parts are not populated
  to save cost. I’ve also added silk labels to the header pins on the
  back. This is an open design under CC BY SA license.

Of course, you can always make your own breakout circuit. For example, you could reproduce the breakout board using a breadboard and some resistors and capacitors. The schematics are provided on that page for A1

and A2

So, in short, either purchase a breakout board, or make one. Once you have done that , you can use the CraftyCoders Arduino Library

Hope that helps.


Is code in a class repeated for each instance?

No, it is not repeated. Unless you are using templates, each method of
each class is stored only once in the compiled program. Or even not
stored at all if the optimizer notices it is not used.

Just to demystify the classes a bit, you can consider them as a kind of
“syntactic sugar” over an “object oriented” programming pattern. The
following C++ code:

class MyClass {
public:
    int aMember;
    long anotherMember;
    int aMethod(short);
};

int MyClass::aMethod(short theParameter)
{
    return aMember + theParameter;
}

void some_function()
{
    MyClass objects[2];
    objects[1].aMethod(42);
}

is interpreted by the compiler as being roughly equivalent to this C
code:

typedef struct {
    int aMember;
    long anotherMember;
} MyClass;

int MyClass_aMethod(MyClass *this, short theParameter)
{
    return this->aMember + theParameter;
}

void some_function()
{
    MyClass objects[2];
    MyClass_aMethod(&objects[1], 42);
}

Can you spot the differences and the similarities?


Play .Wav sound only once on switch change

Make a variable to hold the "last state" of the switch. Compare that last state to the current state as obtained by switchValue = digitalRead(8).

Only call the play function if the old value and the current value are different.


Float magnet switch interrupts atmega328p and RN2483 sends data

float is already defined for floating point number, so you cannot use it for your function that detects when the sensor is floating on water.  Try calling it something else.

Also, instead of detaching and reattaching the interrupt, use a state machine.  When the interrupt is triggered, you will be able to run different code in the main loop.

unsigned int state;
void setup(){
  state=1;
  attachInterrupt(0,changestate,RISING);
}
void loop(){

switch (state) {
case 1: // do something
// add code here
break;

case 2: // do something else
// add code here
break;
}
}

void changestate(){
if(state==1){state=2;} // interrupt changes state
}


Using Arduino to pass data from a coin collector to android app

Here are a couple of opitions for you:

1- Bluetooth - if in close range, an HC-05 will work great.

2- Wifi - wifi can work good. It is a little more complex then bluetooth but its range can get further. For example, a Tweet can be sent each time a coin is detected.

3- GSM - it is pretty much texting. You can make it so the coin collector texts you or someone there is a coin.

All of these solutions work great with the MIT app creator. It makes the data you receive much easier to process.


I wonder if there is another pin on the board I could read

I guess that would depend on the particular doorbell. The transmitter must send some representation of a button press to the receiver - a pulse train for the duration of the press, or perhaps just CW: carrier on, carrier off - which the receiver somehow passes on to trigger the audio. Look at the receiver's output side to identify that trigger signal and pass it, or a processed version of it, to the Arduino.


Electret microphone board strange offset using Arduino

An electret microphone is like a resistor which changes its value according to the sound.

To use it you must form a voltage divider with it, as if it were half of a potentiometer.

Thus you add a resistor to +5V (which is already on the board).  This means that when it is silent the voltage you get is the ratio of the resistor and the resistance of the microphone.

If the resistance has been chosen correctly then the output you get should be roughly half the supply voltage when silent. Any sound will cause that output to swing around that "zero" point.

It's just like a potentiometer.  When silent the potentiometer is in the central point. When you make noise you're moving the potentiometer in both directions.

To get rough values you should first get the "silent" reading from analogRead. You can then subtract that value from all subsequent readings.

Note that the results will be non-linear. To do it properly you should calculate the resistance of the microphone by using the supply voltage, the "upper" resistor value, and the sampled voltage to calculate the resistance value like you would for any other resistive sensor (such as an LDR or force sensitive resistor).


You can change the address of the GY-521 by pulling the AD0 pin to Vcc. After that the address will be 0x69 instead of 0x68.


The 'Initializing' printout happens because that is sent directly to the UNO's hardware serial port.  The rest doesn't happen because it is directed to the SIM card via SoftwareSerial pins 7 & 8, and the SIM card apparently isn't responding.

Cut the problem in half:  Connect pins 7 & 8 together, and run your program again.  If you get "AT" and the rest, then you know the 'MySerial' port is active and working correctly, and the problem is in the SIM 'half'.  Maybe you have an incorrect wire connection there, or maybe the SIM card's default serial rate isn't 9600, or something like that.  YMMV ;-).

As a test, I ran your program on a UNO, with a jumper wire between pins 7 & 8.  Unfortunately this did not work, but now I knew that the problem had nothing to do with the SIM shield. The result wasn't what I expected, but now I had 'cut the problem in half'.

Now that I had determined that the SIM card wasn't a factor (so far, anyway), I could concentrate on the 'UNO half'.  After some web research I found that 'Software Serial' doesn't support 'loopback' (looping the transmit line back into the receive line) because it cannot simultaneously transmit and receive.  Fortunately, the 'AltSoftSerial' library by Paul Stoffregen does support simultaneous transmit & receive, and so will support loopback.

So, I installed the library on my Arduino setup, and compiled and uploaded the example shown below.

#include <AltSoftSerial.h>

// AltSoftSerial always uses these pins:
//
// Board          Transmit  Receive   PWM Unusable
// -----          --------  -------   ------------
// Teensy 3.0 & 3.1  21        20         22
// Teensy 2.0         9        10       (none)
// Teensy++ 2.0      25         4       26, 27
// Arduino Uno        9         8         10
// Arduino Leonardo   5        13       (none)
// Arduino Mega      46        48       44, 45
// Wiring-S           5         6          4
// Sanguino          13        14         12

AltSoftSerial altSerial;

void setup() {
    Serial.begin(9600);
    //while (!Serial); // wait for Arduino Serial Monitor to open
    Serial.println("AltSoftSerial Test Begin");
    altSerial.begin(9600);
    altSerial.println("Hello World");
}

void loop() {
    char c;

    if (Serial.available()) {
        c = Serial.read();
        altSerial.print(c);
    }
    if (altSerial.available()) {
        c = altSerial.read();
        Serial.print(c);
    }
}

After uploading the code, I 'looped' pin 9 back to pin 8, and found that when I sent characters to the UNO via the hardware USB port, they showed up again 'echoed' to the serial output after having traversed the AltSoftSerial port 8/9.

So at this point I have solved the UNO 'half' of the problem; the rest is up to you! ;-)


How to control the power of attiny13a via pin change interrupt?

#define F_CPU   1200000UL

#define LED     PB2 // PB2
#define BUTTON1 PB1 // INT0
#define BUTTON0 PB0 // PCINT0

#define HIGH         1
#define LOW          0
#define INPUT        0
#define OUTPUT       1
#define INPUT_PULLUP 2
#define FALSE        0
#define TRUE         1
#define _BV(bit)    (1 << (bit))

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <util/delay.h>

void pinMode(uint8_t pin, uint8_t mode){
    if(mode == OUTPUT) // Pin as output
        DDRB |= _BV(pin);
    else // Pin as input or input pullup
    {
        DDRB &= ~_BV(pin); // Set pin as input
        if(mode == INPUT_PULLUP)
            PORTB |= _BV(pin); // Enable pullup resistors
    }
}

void digitalWrite(uint8_t pin, uint8_t val){
  if(val)
    PORTB |= _BV(pin);  // Set pin high
  else
    PORTB &= ~_BV(pin); // Set pin low
}

uint8_t digitalRead(uint8_t pin){
  return !!(PINB & _BV(pin));
}

//wake up
ISR(INT0_vect){
   sleep_disable();
   //cli(); // Turn off global interrupts
   digitalWrite(LED, HIGH);
}

void blink(){
    digitalWrite(LED, LOW);
    _delay_ms(1000);
    digitalWrite(LED, HIGH);
    _delay_ms(1000);
}

// go to sleep
ISR(PCINT0_vect)
{
   //cli(); // Turn off global interrupts
   if(!digitalRead(BUTTON0)){
        cli(); // Turn off global interrupts

        blink();

        digitalWrite(LED, LOW);

        sei(); // Turn on global interrupts
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);
        sleep_enable();
        sleep_cpu();
    }
}

int main(void)
{
    //enabled external interrupt
    MCUCR=0;
    //MCUCR=0b00000000;
    GIMSK|=_BV(INT0); // enabled external interrupt INT0 - PB1

    // Sets the Pin change interrupt mask
    GIMSK|=_BV(PCIE);
    PCMSK|=_BV(PCINT0);//PB0

    pinMode(LED, OUTPUT);
    digitalWrite(LED, LOW);

    pinMode(BUTTON1, INPUT_PULLUP);//INT0 - PB1
    pinMode(BUTTON0, INPUT_PULLUP);//PCINT0 - PB0

    //Enables Interrupts globally after setup
    //SREG |= _BV(SREG_I);
    sei(); // Turn on global interrupts
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_enable();
    sleep_cpu();

    while(TRUE){}

    return 0;
}


XBEE coordinator WITH or WITHOUT Arduino?

If you want just to control and receive data from your end user, option 2 is easy to implement.

You can use any programming language that supports serial communication such as python, node.js, etc.

What you have to is to note how your coordinator is recognized by your operating system (in windows as com1 port, unix-like as ttyACM or similar) and open it from your preferred language.

After that, you establish a protocol that should be agreed with your Arduino. For example. Suppose you want to collect data from end user, so, you send a message from the coordinator connected in your PC with a code #data through the serial. When the Arduino receives it, it decodes the message and return something like #d125 where it says it is sending the data and the value is 125 (supposing integer values).

Making sure you already have configured the XBees in the same network by setting Same PAN id and cross setting the destination address of each one so they send packates to each other.

I am supposing you are using AT transparent mode where they just send whatever comes in the serial interface, in this mode they work basically sending chunks of bytes and it is up to you to establish a protocol to provide a good flow of data. In this mode there is no guarantee that your packet will reach the destination. In order to fully extend the XBee usage, you'd need the API mode where all the transmission checks are done.

But for you purpose, AT mode seems enough.


There are only two errors I can spot in your program:

A block of code should be delimited by curly braces:

for (count=0; count<8; count++){
    pinMode(pinArray[count],OUTPUT);
}  // ← ‘}’ instead of ‘]’

If a function expects to be passed arguments, these should be
declared as parameters in the function prototype:

void ledDisplay(byte x){  // ← mind the “byte x”
    // ...
}

Other than that, here a few suggestions to make the code look nicer, and
hopefully more maintainable:

indent consistently
use const to qualify constants
use named constants instead of magic numbers
keep variables local if possible
note that an int that is either 0 or 1 is equivalent to a boolean
use pinArray[] for accessing the pins

Applying those suggestions, I get the following:

const int PIN_COUNT = 8;
const int pinArray[PIN_COUNT] = { 2, 3, 4, 5, 6, 7, 8, 9 };
const int CODE_COUNT = 6;
const int code1[CODE_COUNT] = {
    B10101010, B01010101, B10101010, B01010101, B10101010, B01010101
};

void setup() {
    for (int count = 0; count < PIN_COUNT; count++) {
        pinMode(pinArray[count], OUTPUT);
    }
}

void loop() {
    for (int count = 0; count < CODE_COUNT; count++) {
        ledDisplay(code1[count]);
    }
}

void ledDisplay(byte x) {
    for (int split = 7; split >= 0; split--) {
        if (bitRead(x, split)) {
            digitalWrite(pinArray[split], HIGH);
        } else {
            digitalWrite(pinArray[split], LOW);
        }
    }
}


How can I get my Attiny85 interupt to trigger

You main problem is that you have wired up your MCU wrong.

Pin 5 (PB0) is not the external interrupt pin. Pin 7 (PB2) is the external interrupt 0 (INT0) pin.

As a result your code will not do anything when the hall sensor changes because it is not looking at it.

I would suggest not trying to use the attachInterrupt() abstraction. Instead I would simply enable the external interrupt directly:

GIMSK |= _BV(INT0);

And use a proper ISR handler:

ISR(INT0_vect) {
    //Your ISR code here.
}


Saving byte array in PROGMEM instead of SRAM

See Putting constant data into program memory (PROGMEM) for tips about putting stuff into PROGMEM. However personally I wouldn't get too excited about saving 6 bytes.

Example code:

Declare data globally:

const byte mac [6] PROGMEM = { 0x90, 0xA2, 0xDA, 0x0F, 0xE1, 0x85 };

Get a copy for use into a temporary variable:

  char foo [6];
  memcpy_P (foo, mac, sizeof foo);


Cannot upload program to Arduino Duemilanove w/ Atmega328

You may have wrong port:  /dev/tty.usbserial-A9007LXq works with Duemilanove on my Mac.


Verifying the timing between relay activations

You could use sigrok with one of the many supported devices.
For example, you can find on ebay an 8 channell 24MHz probe for less than $10.

It's a nice tool to have laying around. For example you can use it as less-invasive-than-serial-print way to detect when internal states of a program change value: just toggle some unused GPIO.


When using strcmp(), strings should be terminated with a NULL character.  Which, by the way, is a zero. Your code should work as is if you replace the Line Feed character (10 or 0x0a) with a NULL (0 or 0x00). That is assuming the string you are getting back is 0x4f, 0x4b & 0x0a.  Or you could play it safe and replace strcmp with strncmp.  Then explicitly state the number of characters to compare:

if(strncmp((char *)sigfox_rd_buf,"OK",2) == 0 )


My GY-MAX30100 pulse oximeter issue with Arduino Uno

There are 2 newer libraries you can try. I have used both with a MAX30102 and they work.

The first one is here: SparkFun_MAX3010x_Sensor_Library. There are several sketches included, and this one worked for me: Example5_HeartRate.

The other library I had success with is this one: Protocentral. It has a test sketch that writes the data to the serial port, but you can add Serial.println() statements to it to see if the data "makes sense".


Using two sensors with delay concurrently

There is a non-blocking library that works similar to delay() Virtual Delay. This sketch turns your Uno's built-in LED ON for 1 second, then OFF for 200ms, repeatedly.

#include <Arduino.h>
#include "avdweb_VirtualDelay.h"

VirtualDelay delay1, delay2;

void setup(){

  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

}

void loop(){

  // This sequence has a deadlock.
  if(delay1.elapsed()){
    digitalWrite(LED_BUILTIN, LOW);
    delay2.start(200);
  }

  if(delay2.elapsed()){
    digitalWrite(LED_BUILTIN, HIGH);
    delay1.start(1000);
  }

  // This breaks the deadlock. You can start with any
  // delay object you want e.g. delay2.start(0);
  DO_ONCE(delay1.start(0));

  // Your code here.

}

The library's author has an excellent tutorial on their website: avdweb Virtual Delay timer for Arduino.


client.connect() fails except the first time

You have to disconnect before being able to connect again otherwise the controller will crash due to memory starvation. Every connect you do takes some memory to register state information. Not sure of the exact commands involved, but it'd look a bit like this:

   if (client.connect(server, port))
     {
       .......
       client.disconnect( .... );
      }
  else
........

Alternatively you can check if you are already connected, and only do a reconnect when necessary, but I don't know which library you are using, let alone if there is a proper check available in it.


Emulate non-standard keyboard from Arduino

Emulating a keyboard matrix is actually harder than you would at first think. It's not just a case of setting certain combinations of pins as HIGH or LOW - you need to actively monitor one side of the matrix as it sweeps across each row and control the other side depending on the buttons that are pressed or not pressed on the current row. And all that has to be done fast enough that the C64 doesn't see buttons constantly bouncing up and down.

Further, you really need all your outputs to be open drain so as not to interfere with each other or the rest of the system (depending on just how the C64 system works), and Arduinos can't do open drain natively - instead you have to emulate it by switching between INPUT and OUTPUT + LOW which adds extra latency.

If you only want access to a few of the buttons a better arrangement would be to add a small N-channel (logic level) MOSFET or an NPN BJT between the two sides of the matrix for whichever button(s) you want to control (check the schematics for which pins and which way round to connect it). Activating the transistor would then be the same as pushing the button down. It can even be in parallel to the existing button so as to not break the keyboard.


How can I use wifi to wirelessly communicate (and wirelessly code if possible) between multiple arduinos?

Sending data to a computer using WiFi is simple enough and there are plenty of examples. The simplest way is to set up a web server on the computer and use HTTP POST to send the data. There are "lighter" ways but entail more coding.

You won't do OTA updates on a normal Arduino. Yes, you could use a Yún, but they aren't always the best choice - the Linux side of things does make it a very "heavyweight* board.

You may be better off using an ESP8266 based system (not wired to an Arduino, but standalone) and programming it direct. Maybe a NodeMCU or something similar.  The Arduino core for ESP8266 supports OTA programming direct from the Arduino IDE.


Why can't the new Arduino IDE 1.6.7 compile extern "C"?

I can't reproduce your problem still. See this:

However if you are having problems (and frankly I expected you to) then you should read this:

How to avoid the quirks of the IDE sketch file pre-preprocessing

How the IDE organizes things

I can reproduce your problem in IDE 1.6.5 (not 1.6.7). The code generated by the IDE preprocessor is this:

#line 1 "sketch_jan11a.ino"
#ifdef __cplusplus
#include "Arduino.h"
void start_timer(void);
void setup();
void loop();
#line 2
extern "C" {
#endif

void start_timer(void);

#ifdef __cplusplus
}
#endif

void start_timer(void)
{
    Serial.println("2");
    Serial.begin(9600);
    delay(2000);
}

void setup()
{
    start_timer();
    Serial.println("4");
}

void loop()
{
    Serial.println("1");
    delay(2000);
}

You can see that in the automatic function prototype generation that the IDE "helpfully" generates for you, it puts the prototype for start_timer outside the extern "C" declaration. Thus one function prototype has a declaration in C++ format, and the other in C format.

Why are you even doing this? I presume this is a small example of a larger problem.

If you follow the suggestions in my link How to avoid the quirks of the IDE sketch file pre-preprocessing - did you read that? - the problem goes away, because .cpp files in IDE tabs are not subjected to this extra processing.


Problem with nodemcu esp-01 can't connect to wifi

ESP-01 modules use 26 MHz crystal. Set the Crystal frequency in IDE to 26 MHz.

Both io pins (0 and 2) on esp-01 have pull-up circuit. That is why you think you measured 'inverted' logic.


How to use arduino IDE to compile .s files

The IDE should be able to accept .S files (not .s - the difference is very important: .S will be preprocessed, .s won't).

Just create a new sketch, and create a new tab called whatever.S (obviously rename the whatever to whatever you want to call it.

Then in the main sketch .ino file put something like:

extern "C" void myAssemblyMain();

void setup() {
    myAssemblyMain();
}
void loop() {
}

That will then call the function myAssemblyMain: in your assembly file and not much else.

(Note: I haven't tested this since I don't use the Arduino IDE).


Digital Pin won't ground when set to LOW

Never directly connect a motor to an Arduino IO pin
You will destroy the Arduino.
An Arduino cannot source (or sink in your case) enough current to drive a motor, and if the motor did manage to turn the huge amounts of EMI it generates would literally blast holes in the silicon inside the chip.
You must use a motor driver of some form. If you only want one direction that driver can be a single NPN Bipolar transistor or N-channel MOSFET.  If you need it to change direction then an H-bridge is what you want.


As the function prototype you have show suggests, the data needs to be in a uint8_t array format.

void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y,
            const uint8_t *bitmap, int16_t w, int16_t h,uint16_t color)

So your array data would look like:

const uint8_t myBitmap[] = { 0xff, 0xff, 0xc0, 0x00, 0xc0, 0xff,
    0xc0, 0xc0, 0xff, 0xff, 0xde, 0xad, 0xbe, 0xef,
    .... etc ....
    0xff, 0xff, 0xff, 0xff, 0xff
};

You then call the function with the needed parameters:

tft.drawXBitmap(10, 20, myBitmap, 100, 80, 0xFFFF);

That is assuming you want to place it at (top left corner) 10,20 and the bitmap is 100x80 pixels in size.  It will draw it in white (0xFFFF).


As stated by Majenko, the ADC can in principle have all sorts of
errors. However, if you look at your data, you should notice that the
error is essentially linear with the voltage. This means that the
non-linearity error is quite small, and you are mainly seeing the offset
and gain errors. This is fortunate, because these errors are easy to
remove, given good calibration data.

The table you wrote in in your question happens to be a perfectly good
calibration table. By fitting a straight line to it you can get a
calibration function, and then correct the readings simply by adding
this to your code:

voltage = 0.9848815 * voltage + 0.125354;

Or you could instead figure out the correction at the ADC level and
replace

adc = analog * 1.228 / 1023;

by

adc = (analog + offset) / scale;

where offset and scale are computed from the calibration.

Edit: Here is how I extracted the calibration coefficients from the
data.

First, I saved the data in a text file calibration.tsv and cleaned it up
to remove the units and add a comment marker (#) in front of the column
labels:

#Input | Arduino | Difference
 1      0.89     -110e-3
 2      1.90     -100e-3
...

Then I looked at the data with gnuplot. Since I want to know how to
correct the readings, I plot the amount I have to add (minus column 3)
v.s. the Arduino reading (column 2):

plot 'calibration.tsv' using 2:(-$3)

At this point it appears it's linear with what looks like mostly
quantization noise. I model this as a line of equation a*x+b, and
compare the line with the data:

a = -1e-2
b = 0.12
plot 'calibration.tsv' using 2:(-$3), a*x+b

The line is quite off the data, but it's a reasonable first
approximation. Now I ask gnuplot to perform a least squares fit, then
take another look:

fit a*x+b 'calibration.tsv' using 2:(-$3) via a, b
replot

Now the fit looks quite good. When it completed the fit, gnuplot
displayed:

Final set of parameters            Asymptotic Standard Error
=======================            ==========================
a               = -0.0151185       +/- 0.0002953    (1.953%)
b               = 0.125354         +/- 0.002173     (1.734%)

so now I know I can correct the data with:

voltage += -0.0151185 * volatage + 0.125354;

which is equivalent to what I wrote above.


Alternative Way to Power Components on an Arduino

Using a motor controller to power an Arduino or analog peripherals is probably unwise as the source is liable to be noisy.

Better, probably, is to power the Arduino from the 7.2V supply via a noise filtering resistor into the Arduino's Vin terminal.
NBNBNB 7.2V input MUST be to Arduino Vin.

Use a small series resistor from 7.2V to Vin and a large filter cap at Vin to ground. Then power the sensor from Arduino 5 V output.

Voltage drop in series resistor from 7.2V to Vin must drop under 2V.
Rmz is <= Vdrop / Iload
For say 50 mA load Rseries = V/I = 2V max / 0.05 = 40 Ohms .
For 100 mA R <= 2/.1 20 Ohms.
So probably try about 22 Ohms to start.
If Vdrop is > 2V a smaller R is needed.
If Vdrop is << 2V increase R.

For the capacitor at Vin - the larger the better.
100 uF good. 1000 uF better.

Resistor power dissipation is I^2 x R.
So at even 100 mA Pres = 0.1^2 x 22R = 0.22W
A 1/2 Watt resistors would suffice.
A  1 W resistor would do no harm and would tolerate the heat better.

The 22 Ohm resistor and large capacitor form an RC (Resistor + Capacitor) noise filter.
This greatly reduces motor noise which appears on the 7.2V line.
This is very standard practice in real world installations like this.
An inductor based filter can be better but RC should suffice.


Sharing a Digital Pin / What to do when two components need a specific Digital Pin?

It seems probable that both libraries use SPI which connects to the SPI hardware on the chip via those pins. See How do you use SPI on an Arduino?

You haven't said what libraries, nor what hardware, but you possibly may be able to share those pins between the two devices. They would both need separate slave select pins. Often D10 (digital pin 10) is used as a default for slave select.

Another possible solution is to use "bit-banged" SPI for one device. I have a page on my forum about SPI which includes a bit-banged software implementation.

The library is at https://github.com/nickgammon/bitBangedSPI and is quite short.


Can I set the Arduino board type in code

No, it cannot. Neither the compiler invocation nor the subsequent upload examine the code for the hardware in use, so there is no way of doing what you are asking.

What you can do is to create entries in a new boards.txt and programmers.txt using an existing core that specify all the parameters, and all you would have to do is select them in the IDE for everything to be set at once. See Google Code/Arduino/Platforms for more information.


Reverse engineering LIN bus on E-bike system

As a starter point I would hookup your rigol ds1054z via usb to sigrok
https://sigrok.org/wiki/PulseView this will enable you to log dump and analyze your lin frames . It has a frame decoder for LIN protocol.
This should give you a great view of what is transiting over the lin bus and which slave PID to call .
From there you may use a macchina.cc  to comunicate over lin or use
https://github.com/macchina/LIN with a arduino due and a lin tranceiver.
Cheerz


Motor Shield not giving full power, LED DIMS

According to the Adafruit page the V1 version of the shield is not as powerful as their V2 version.

Where is the 12V coming from to get to the shield? There isn't really 12V broken out on the Uno anywhere. If it comes from Vin then there is a 0.7V drop through the reverse polarity protection diode. Plus, the tracks on the Arduino board may not be thick enough to provide enough current.

It looks like the shield may take an external power source (it is hard to tell because they discontinued it). You could try using that.


How to connect Mg995 and arduino nano since nano can only output 40mA at max?

The servo has 3 Pins to connect: Vcc, GND and PWM. The power, which actually drives the servo is drawn through the power lines Vcc and GND. The PWM pin, which is connected to an Arduino output pin, does not draw mich current. It is only for the PWM (-like pulsed) signal, which tells the servos driver, which angle is requested. But you should not power the servo through the Arduino. You have to connect it directly to a power supply with the correct voltage, because some parts of the Arduino can get fried, when drawing too much current through it.

So all in all: Connect the PWM pin directly to an Arduino output pin and supply the power from the source directly to the servo, not going through the Arduino.


ESP8266 WiFiClient connection always returns 0

I had the same problem with my esp-01. Just download ESPWenServer library from here.

  https://github.com/esp8266/ESPWebServer

And from this try HelloServer.ino example code. If it still does not connects-
1.Either your WIFI is not working
2.You are typing wrong SSID and PASSWORD
3.Spacing between SSID name or PASSWORD is the issue.

For the 3rd one if possible change your Wifi password or name if it has spaces between it.


Are there any standard ways of reporting a runtime error?

As pointed out by Majenko in a comment, you can hardly define a standard
facility for error reporting when you don't know what kind of I/O
hardware will be available on any particular project. Printing to the
serial port is the most common method though, as it tends to always be
available during the development phase, while the Arduino is tethered to
the development computer. I personally tend to just do something like

Serial.println(F("Error: the warp field coil is busted."));

and be consistent with the error prefix, so that a program receiving
this can tell it's an error by matching the line against /^Error: /.

While it is OK for user code, reporting errors through Serial is
certainly not a good practice for library code. Alas, it is done way
too often in Arduino libraries. I've seen at least one library (don't
remember which one) that allows the user to provide a reference to a
Print object (defaulting to Serial) to be used for this purpose.
This is way better, as it allows the user to handle the error messages
any way she chooses. It is also very easy to turn off the error
reporting altogether by implementing a do-nothing Print, which would
be a /dev/null of sorts.

Note that the avr-libc allows you to print to stderr, as long
as you have first implemented stderr->put... While this method is the
closest you can get to the standards you are used to, it may not be
portable to non-AVR Arduinos. And it is worth noting that we tend to
avoid the printf() family of functions on Arduinos, as they tend to be
quite large compared to the print() and println() methods.


The fault lies here:

while(client.available()) {
  serverReturn += client.read();
}

client.read() returns an integer. That integer is either the ASCII code of the next character in the buffer, or -1 if there are no characters in the buffer left to read.

You then append that integer to the end of a String which gets converted to the ASCII representation of that integer before being appended.

So the string HTTP, for instance, which is ASCII characters 72, 84 (twice) and 80 ends up as "72848480".

Instead you need to cast the integer to a char before appending:

serverReturn += (char)client.read();

Or better still don't use any String variables at all and parse the data as it comes in pulling out any information you need to at the time it arrives.


LCD 16*02 I2C shield only shows first character printed

That's definitely a bug appeared in 1.6.6.
For reference, see
https://blog.arduino.cc/2015/11/03/arduino-ide-1-6-6-released-and-available-for-download/#comment-278766
https://forum.arduino.cc/index.php?topic=359652.0
http://forum.arduino.cc/index.php?topic=357312.msg2476987#msg2476987

Last link seems to provide a solution, by a updated version of LCD I2C lib : https://github.com/marcoschwartz/LiquidCrystal_I2C (not yet tried).

The 1.6.6 is a bit messy according some people, but the I2C lib too ;). So the question is : where should it be fixed ?


How to produce rolling count per minute?

If you want to update every second a one minute running average, you
have no choice but store in memory the counts you got the previous
60 seconds. You store them in a ring buffer, so that every new
reading replaces the oldest one. Then, every second:

you add to the CPM count the number of counts you got this second
you subtract the number of counts you got on the second that just got
out of the sliding window.

I would implement that logic this way:
const uint32_t ONE_SECOND = 1000;

uint16_t counts_per_minute;
uint16_t previous_counts[60];
size_t counts_pos;

void loop() {
    static uint32_t previous_second;
    if (millis() - previous_second >= ONE_SECOND) {
        previous_second += ONE_SECOND;
        noInterrupts();
        uint16_t CNT_copy = CNT;
        interrupts();
        static uint16_t CNT_previous;
        uint16_t second_count = CNT_copy - CNT_previous;
        CNT_previous = CNT_copy;
        counts_per_minute += second_count - previous_counts[counts_pos];
        previous_counts[counts_pos] = second_count;
        if (++counts_pos >= 60) counts_pos = 0;
    }
}

Note that:

The timing variable is updated with previous_second += ONE_SECOND
rather than previous_second = now in order to avoid the accumulation
of small timing errors.
The counter that is updated in the ISR has to be read only once,
with interrupts disabled. Otherwise the interrupt may change it while
you are in the middle of reading it.


Here is my take at this - I've followed the example code mentioned by other members and here is "FadeWithoutDelay"

const int ledPin = 11;
unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 100;               // fade interval (milliseconds)
int brightness = 0;                      // how bright the LED is
int fadeAmount = 5;                      // how many points to fade the LED by

void setup()
{
  pinMode(ledPin, OUTPUT);  // set the digital pin as output:
}
void loop()
{
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval)
  {
    previousMillis = currentMillis;         // save the last state
    analogWrite(ledPin, brightness);        // Set the brightness
    brightness = brightness + fadeAmount;   // change the brightness for next time through the loop
    // reverse the direction of the fading at the ends of the fade:
    if (brightness <= 0 || brightness >= 255)
    {
      fadeAmount = -fadeAmount;
    }
  }
}


Sending 4 analog values from one arduino to another with I2C

Why are you limited to sending one value? You can have multiple Wire.write() calls in one transmission.
The slave side just needs to know to expect multiple values in order to accommodate. The best way to do this would be to read in values as long as the master is sending them (check out https://www.arduino.cc/en/Reference/WireRead).
Then your master changes from
Wire.beginTransmission(SLAVE_ADDR);
Wire.write(sendValue);
Wire.endTransmission();

to
Wire.beginTransmission(SLAVE_ADDR);
Wire.write(sendValue);
Wire.write(sendValue2);
Wire.write(sendValue3);
Wire.write(sendValue4);
Wire.endTransmission();

And the slave receiveEvent() becomes
int receiveValue;
int receiveValue2;
int receiveValue3;
int receiveValue4;
int index = 0;
while(Wire.available()){
    if(index == 0){ receiveValue = Wire.read(); }
    else if(index == 1) {receiveValue2 = Wire.read(); }
    else if(index == 2) {receiveValue3 = Wire.read(); }
    else if(index == 3) {receiveValue4 = Wire.read(); }
    index++;
}

I would also consider using arrays as a way to clean up some of your variables, but making the above changes should accomplish what you want if not as cleanly.


Connect multiple pins to same VCC using breadboard

You have basic misconceptions there:

Vcc is the power input (!) for the Atmega, not an output to provide current to other parts. Your power supply (whatever you use as one) should be connected to every Vcc pin at the same time. Sure, the Vcc pins are internally connected, but the Atmega has multiple of them, so that the needed current does not have to flow through a single pin. Also you don't want to draw the current for peripherals through the Atmega chip itself (which would happen, when you connect the power source to one of them and the peripherals to another). So every device in your circuit, including the Atmega, has it's own Vcc pin, which needs to be connected directly to the power supply. That is ok and correct, as long as the power supply can provide enough current for all components. If it doesn't, you need to buy a power supply, that can.
When connecting device to one pin, the number of devices is not imporant. The current draw is what is important. For example let's take simple digital output pin of the Atmega. It can provide up to 20mA (recommended value; max. 40mA for a short time). We must no exceed that value. So we can connect 1 device, that draws 20mA, or 2 devices, that draw 10mA each. Or 100 devices, which draw 0.2mA each. The number is not important, only the total power draw. The current will drop, when you draw more current, that the source can provide. In that case often the source will be damaged or at least go into thermal emergency shutdown (as for the voltage regulator of a genuine Arduino).

So the Todo for you: Connect every Vcc pin, that you have, directly with the power source.


How can configuration values be stored on an ESP8266?

Thanks to Jaromanda X and Juraj for the SPIFFS recommendation. I was able to use this block of SPIFFS code as an example and safely store settings in my project outside of the compiled source.

To upload files to my ESP8266, I followed the installation and usage instructions for the ESP8266 filesystem plugin for the standard Arduino IDE.

First, I created a .gitignore file and added this so that none of the actual values would get added to the repository:

# MQTT config info
data/config.json

Then I created a data folder and added a config.json file that had all the configuration properties that I need to reference:

{
  "cloudmqtt_server": "***.cloudmqtt.com",
  "cloudmqtt_user": "********",
  "cloudmqtt_pass": "************",
  "cloudmqtt_port": 10000
}

Following the example above, I added #include <FS.h> at line #1 (as well as #include <ArduinoJson.h> for parsing the JSON) and have this block to instantiate the variables with dummy values that will be replaced by the actual values from the JSON file:

// MQTT pub/sub for the servo functions
#define CLOUDMQTT_CONFIG  "/config.json"
// these values are loaded from a config.json file in the data directory
char cloudmqtt_server[18] = "***.cloudmqtt.com";
int  cloudmqtt_port       = 0;
char cloudmqtt_user[9]    = "********";
char cloudmqtt_pass[13]   = "************";

Then in the setup I have this block to load the values from the config:

if (SPIFFS.begin()) {
  Serial.println("mounted file system");

  // parse json config file
  File jsonFile = GetFile(CLOUDMQTT_CONFIG);
  if (jsonFile) {
    // Allocate a buffer to store contents of the file.
    size_t size = jsonFile.size();
    std::unique_ptr<char[]> jsonBuf(new char[size]);
    jsonFile.readBytes(jsonBuf.get(), size);

    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.parseObject(jsonBuf.get());
    if (json.success()) {
      strcpy(cloudmqtt_server, json["cloudmqtt_server"]);
      cloudmqtt_port = json["cloudmqtt_port"];
      strcpy(cloudmqtt_user, json["cloudmqtt_user"]);
      strcpy(cloudmqtt_pass, json["cloudmqtt_pass"]);
    } else {
      Serial.println("failed to load json config");
    }
    jsonFile.close();
  }
}

I'm not sure if there's a better way, but this way works for me:
https://github.com/dieseltravis/esp8266-projects/tree/master/servo-demo


I2C LCD Serial Interface Board not displaying text

This can be due a lot of reasons, among:

Most common:

Backlight is set too low (there should be a small dial)
Circuit problem (recheck), and post it.
The I2C address is wrong, there are sketches to check it.

Less common:

Broken LCD
Broken Arduino
No power on Arduino (check LED)


Can I implement a LFM method on an Arduino?

Since you are talking about Arduino, I suppose you want to do it digitally.

The answer is: it depends.

It depends on:

Desired frequency of the carrier
Desired maximum frequency of the input signal
Desired accuracy (compared to the equivalent done with analog components)

But in general I'd say that it's unlikely it will have sufficient computational power. I'm assuming the question is for the 16MHz 8 bit UNO.
The Cortex M3 on the DUE might stand some chance, being a 32bit core @ 84MHz.

It might be possible to do some trick using a PWM signal and a digital output with a wired AND, but I'll leave to others to comment about its feasibility.


How to input keyboard commands using Arduino Mega 2560?

You are right, the mega can't do what you want unless something in the middle catches the serial/IO and translates to a keystroke command.

Another option, more expensive, is to buy an Arduino Leonardo which is also available as a small usb stick type of device. Then use serial/analog or ano from the mega to the Leonardo.

The Leonardo boards can emulate any usb device such as keyboard, mouse, joystick etc.

Maybe not of interested but also look at Teensy 3.1. It can do what the Leonardo does but is 32 bit and very flexible. The only benefit of the mega is the massive number of pins. Teensy costs about $20.

It all depends on what your project requires.


HDOP can be less than 1 according to this article.. I am no expert in this area, but according to the article, the HDOP=1 limit is based on 4 satellites; visibility and use of more than 4 satellites can reduce HDOP below this limit. When you think on it, this makes sense.

GPS specifications limit the inherent accuracy of a position solution through timing errors and vagaries in rf propagation through our atmosphere. Imagine drawing a vector from a GPS satellite to your receiver. The length of that vector represents the distance from the satellite to your receiver, but we depend on signal timing to infer distance/vector magnitude. In other words, we can only measure distance as accurately as we can measure time.

Now think about the accuracy of a position solution based on a single satellite. If we assume the receiver is confined to the surface of the earth (and the satellite is geostationary), the single vector of length L1 will intersect the surface of the earth forming a circle. Your position could be anywhere on that circle - which could be quite a large range of values!

Now imagine a 2nd satellite, a 2nd vector of length L2 tracing a second circle. Now your position is constrained to be those points where the two circles intersect - two points! With a third satellite, a 3rd vector of length L3, one of these two points will be eliminated.

Now replace those sharp lines with bands or swaths of some width D. In this case, the intersection describes a polygon instead of a point. We know our position is within the polygon, but with only three satellites that is the best we can do.

As you can see, adding more satellites will begin to "slice off" sections of the original polygon, making it progressively smaller. So: HDOP=1 represents the limit with 4 satellites; more satellites yield a smaller polygon, and smaller HDOP.

While writing this, I found a video that does a far better job than my words at describing the position solution process with multiple satellites.

This video is quite good also!


read first line from sd card and save the position for again reading from sd card

You should not need to save the position, the file knows where you last read from. You'd only need to manually save such information if you close the file and re-open it again, which unless you have a good reason is actually a very wasteful operation.
If you really do need to you can use the .position() and .seek() functions:
Save the location:
uint32_t pos = myFile.position();

Recall the location:
myFile.seek(pos);

Documentation:

https://www.arduino.cc/en/Reference/FilePosition
https://www.arduino.cc/en/Reference/FileSeek


PWM water pump flow control - in percent

Expanding on dannyf's answer, if the pump datasheet does not feature a graph, then you will have to experiment. If a flowmeter is not readily available, an excellent approximation can be calculated by pumping water into a large, known receptacle (e.g. 10 litre bucket) and timing how long it takes. Do this for 20%, 40%, 60%, 80% and 100% Pulse Width Modulation modes, and you will have a plot of flow rate vs PWM that will help you interpolate the PWM required for a desired flow rate (e.g. 50% flow rate).

Below is an example of Rotations Per Minute of a 12V computer CPU cooler water pump for a given PWM input. It is assumed that this would be under load (of pumping water), but not stated explicitly.

Note that it may not be physically possible for the motor to operate with 10% or less PWM duty cycle. At this point I imagine that the internal friction of the motor and forces required to push the water along are greater than the force provided by a "10%" duty cycle.

Source: ekwb


Why PJ0 and PJ1 are not reporting as PCINT pins

Majenko was very close but seems to have missed the explanatory comment from the source code:

// (I've deliberately left out pin mapping to the Hardware USARTs - seems senseless to me)
// Pins: 10, 11, 12, 13,  50, 51, 52, 53,  62, 63, 64, 65, 66, 67, 68, 69

#define digitalPinToPCICR(p)    ( (((p) >= 10) && ((p) <= 13)) || \
                                  (((p) >= 50) && ((p) <= 53)) || \
                                  (((p) >= 62) && ((p) <= 69)) ? (&PCICR) : ((uint8_t *)0) )

Which seems like it may apply to the fact that the USART3 pins PJ1 (14) and PJ0 (15) are missing.

As for why providing mappings to the hardware USART pins "seems senseless" a little playing with git blame will show that these lines were added to this file in commit f179794  in response to issue 490:

  The SoftwareSerial library defines macros that map Arduino pin numbers to the pin changes interrupts on the pins.  We should pull this up into the board-specific pin definition header file so that the SoftwareSerial library can work on any AVR for which those macros (and the pin-change interrupts) are defined.

Which is to say that David Mellis didn't write those lines for generic interrupt use as part of pins_arduino.h, but rather moved code originally written as part of the software serial library to this file to make things more portable (and, though perhaps incidentally, generally usable for other purposes).  It's not exactly clear who the original author speaking as "I" in the comment is - the Mega-specific code in question appears to come most immediately from Mikal Hart's extension of Ladyada's Uno-only interrupt soft serial code (which did not have it) but there's also a comment in that seemingly crediting Paul Stoffregen (Teensy boards) for at least some aspect of the macro...

It does kind of make sense that someone writing a software serial library could consider using it on hardware serial pins pointless.  But counterarguments could also be made - for one example, the 16u2 core either uses or has experimented with software serial at some baud rates, and for another a software serial implementation could be a plausible way of overcoming swapped RX & TX wiring, or a way of implementing inverted signalling logic when using simplified level shifters or talking to something which expects to.

Given that in its current location the code is no longer necessarily only for software serial use, it seems plausible that a carefully written and fully validated patch to make it more general might be favorably received.


What is the best vehicle platform to begin with (e.g. tracked, four-wheel drive)

SparkFun's Magician Chassis is a very simple, very flexible chassis for starting out. Also comes as part of the RedBot Kit.


How to get each byte in byte array out and be able to work with them on their own?

Sorry if this sound patronising, its not meant to, I'm just trying to cover all aspects.

byte[] myByte = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};
WriteAsync(myByte);

You are assigning 4 strings to the array mByte.  A string (lets ignore the Arduino type string for now) is a char* or a char[], so:

char hello1[] = "HelloOne";
char hello2[] = "HelloTwo";
char hello3[] = "HelloThree";
char hello4[] = "HelloFour";

(You don't need to do this in the code, how you have done it is fine, it just shows what you are really saying)

In English mByte should be an array of strings which in code is

char* mByte[] = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};

You could do it as

char mByte[][] = {"HelloOne", "HelloTwo", "HelloThree", "HelloFour"};//ERROR

But this won't compile, because the inner array (the text) is different length and the compiler doesn't like that.

Assuming that writeAsync takes a byte as a parameter then the code to write the data becomes this:

for (int stringCounter = 0; stringCounter < 4; ++stringCounter)
{
    // get a pointer to the first element of the string
    // & means get the address (so the value can be set to a pointer)
    // (byte*) means cast (change) the value into a byte pointer.
    byte* currentLetter = (byte*)(&mByte[stringCounter][0];)
    // currentLetter != NULL means the pointer is not equal to NULL, because looking at a null pointer will crash the code.
    // *currentLetter != NULL means the thing pointed to by currentLetter is not the end of the string.
    while (currentLength != NULL || *currentLength != NULL)
    {
        // Write the thing pointed to by the pointer to the function.
        writeAsych(*currentLetter);
        currentLetter++;  // Move on the pointer
    }
}

Sorry I can't compile that at the moment, but it looks about write.  I hope it helps you understand it.


As I mentioned in the comments, one way to do this is to use a multiplexer.

You haven't said which temperature sensors you are planning to use, so I'll illustrate this example using the TMP36 Analogue temperature sensor.

Now, if you were using just one of these, the connection would be trivial:

But you want more sensors than available pins. That's where the multiplexer comes in.

I'm going to illustrate this using 16 sensors and the Sparkfun 16-channel multiplexer breakout board which is based on the 74HC4067 multiplexer. For 25 sensors, you could use a 32-channel multiplexer (like the Analogue Devices ADG732, for example), or just combine two 16-channel multiplexers (which is probably cheaper, but requires a little more care in the wiring).

[If your soldering skills are OK, I wouldn't even bother with the Sparkfun breakout board myself. It's pretty simple to connect something like this on protoboard, or make your own PCB.]

The 16 sensors are connected to pins Y0 - Y15 on the 74HC4067 (pins C0 - C15 on the Sparkfun board). Take care to note which sensor is connected to which pin!

With 16 inputs, we need 4 bits to address them. The address pins are labelled S0 - S3. The Sparkfun datasheet for their breakout board includes a Truth Table mapping the addresses to the inputs:

The input from the selected device becomes the output from the multiplexer (pin Z on the 74HC4067; the SIG pin on the Sparkfun breakout board).

The diagram below shows one way of connecting 16 TMP36 analogue temperature sensors to an Arduino Nano using the Sparkfun breakout board:

Note the mapping chosen for the address pins:

D5 -> S0
D4 -> S1
D3 -> S2
D2 -> S3

This makes the drawing layout simpler, but may not be the most intuitive mapping when you come to write your code. My advice is to assign meaningful labels to the pin-mappings in your code, and document that decision with comments! (I'm sure that I'm probably preaching to the choir here, but this may help someone reading this in the future to avoid some of the pitfalls.)

Now, you cycle through a loop:

while true {
    increment the address to be written to pins D5-D2 (note the order)
    read the input on A0
    <do whatever you need to do with the temperature reading>
}

And Robert is the male relative of your choice.


What happens if an interrupt is triggered while sending data via serial?

If you are on the ardruino platform, and are using the hardware serial port, you basically don't have to do anything.

The Serial library interface already uses a outgoing data-buffer (it's varies between versions, 1.5.5 has it set to 64 bytes. The arduino people keep changing it's size for no reason), where the call to Serial.print() or Serial.write() only places the bytes in question into the outgoing buffer, and the buffer is then emptied asynchronously in the background by the TX-ready (UDRE) interrupt (which is then disabled when the buffer is emptied).

Basically, all you have to do is ensure that you're not placing data into the transmit buffer from both an interrupt and the main loop(), because it's then possible for the message from the interrupt to be inserted into the middle of the message from the main loop thread.

This can be easily enough done by either guarding the call to Serial.print() with cli() sei() interrupt guards in the main loop() section (or the useless arduino analog: noInterrupts() and interrupts(), which are just named proxies for cli() sei(), which exists for no good reason), or simply not printing from an interrupt (which is a good idea anyways, string formatting can be slow).


The good news is that SATA drivers are fairly generic so you don't have to write the OS side. The bad news is everything else.

just a SATA wire coming from a mother board plugged into a socket on a breadboard

Let me stop you there. The minimum data rate for SATA is sufficiently high that you need a PCB. If you try and do this with wires or breadboards it will simply not get through; it will be lost to parasitic capacitance.

(Many years ago as a student I tried to do something vaguely similar with a wire-wrap board. At just 20MHz you could see a clean signal go in one side and a noisy unreadable mess come out the other side. Actually seeing it on a scope drove home the importance of shielding.)

Do I need flash storage or would I need another kind of chip to handle the data needs

Where would you put the data otherwise? It might be an entertaining first step to create a read-only drive with constant contents, but it's not very useful.

You need a chip with a SATA interface. This will almost certainly be an ARM and almost certainly not in DIP. I can't remember at the moment whether SATA master and slave "PHY" interfaces are different or whether it's all defined in software, someone else can answer that.


The onReceive callback is called from an interrupt service routine (ISR). As the name says, interrupts are "interrupting" the currently executing code almost immediately. And "almost immediately" means that it only will take a few clock cycles. (This is the reason why changing data in an ISR can corrupt data, since the ISR may change a variable, when the main code tries to read it)

So the Arduino will not wait for the loop() function to end. It will interrupt in the line, where it was when the interrupt occured, and return to it after the ISR returns.


To answer your questions in turn:

It is not necessary to connect to the Arduino solely for the purpose of making a GSM network connection.
When the SIM900A is powered on, the Status LED will blink once every second.
When the GSM connection has been established the Status LED of the SIM900A will blink every 3 seconds.

Follow this guide, from Tutorial to interface GSM SIM900A with Arduino:

  Initial startup of SIM900

  Insert your SIM card to GSM module and lock it.
  Power up the SIM900A by connecting it to Arduino's 5V and GND pins
  Connect the Antenna
  Now wait for some time (say 1 minute) and make note of the blinking rate of ‘status LED’ or ‘network LED’ (D6).
  The GSM module will take some time to establish connection with mobile network
  Once the connection is established successfully, the status/network LED will blink continuously every 3 seconds. You may try making a call to the mobile number of the sim card inside GSM
  module. If you hear a ring back, the GSM module has successfully
  established network connection.

  Connection to Arduino

  The SIM900A has the following pins:

  3VR;
  3VT;
  5VR;
  5VT;
  VCC, and;
  GND.

  For serial communication between the Arduino and SIM900A module. you
  have to connect:

  SIM900A 5VT to Arduino D9 and;
  SIM900A 5VR to Arduino D10

  Basic Communication

  To change SMS sending mode: AT+CMGF=1

mySerial.println("AT+CMGF=1");

  To read SMS in text mode: AT+CNMI=2,2,0,0,0

mySerial.println("AT+CNMI=2,2,0,0,0");

  To make a call: ATD+60XXXXXXXXX (replace X with number you want to call, change +60 to your country code)

mySerial.println("ATD+60XXXXXXXXX;");

  To disconnect/hangup call: ATH

mySerial.println("ATH");

  To redial: ATDL

mySerial.println("ATDL");

  To receive a phone call: ATA

mySerial.println("ATA");


Problems connecting reliably using HC-05 (as bluetooth master)

I am using a "BIND" between the PAIR and LINK:

AT+PAIR=98D3,31,FC2D54,5
AT+BIND=98D3,31,FC2D54
AT+LINK=98D3,31,FC2D54

That seems to work for me.

See the docs here:

ftp://imall.iteadstudio.com/Modules/IM120723009/DS_IM120723009.pdf


How do I turn on or off an array of LEDs based on the value of a variable?

Here is a suggestion with the led pins in an array that you loop over.

I suggest making the array global, so put it outside any functions (usually at the top):

byte led_pins[] = {pin1, pin2, pin3, pin4, pin5, pin6, pin7, pin8};

Then put this in your loop (assumes that you have a int called cleanCount that is in scope:

const int increment = 100;

for (int i = 0; i < sizeof(led_pins) / sizeof(led_pins[0]); i++) {
  boolean onOrOff = cleanCount > (i+1) * increment;
  digitalWrite(led_pins[i], onOrOff);
}


You can select, what you want. If you want to build an Arduino Project, you should choose "Arduino Project". If you don't want to use the Arduino Framework, you can choose "AVR Project".


Using a class instance with Wire.onReceive

A non-static class member function has an implicit ClassName *this parameter inserted as the first parameter in the parameter list.

Because the function prototype required for Wire.onReceive() does not have that parameter specified in its parameter list a non-static member function is not compatible with it.

The same goes for attachInterrupt() and anything else that takes a function pointer.


The while() loop in setup() is what gets hung up. Instead of calling odb.init() until it returns true, just call it once just to get it initiated, then call/check in loop() and react accordingly:

void setup()
{
  // start communication with OBD-II UART adapter
  obd.begin();
  lcd.begin(16, 2);
  // initiate OBD-II connection once
  obd.init()
}

void loop()
{
  static int error_count;
  if (!obd.init()) {
    // Not connected
    lcd.setCursor(0,0);
    lcd.print("Connecting");
    lcd.setCursor(0,1);
    lcd.print("Count: ");
    lcd.print(error_count);
    error_count++;`
  } else {
    int value;
    int value2;

    obd.readPID(PID_RPM, value);
    obd.readPID(PID_COOLANT_TEMP, value2);
    lcd.setCursor(0,0);
    lcd.print("RPM = ");
    lcd.print(value);
    lcd.print("     ");
    lcd.setCursor(0,1);
    lcd.print("ECT = ");
    lcd.print(value2);
    lcd.print("     ");
  }
}


Arduino LCD is displaying gibberish, sometimes

Used a pot instead of the PWM from pin 9.  Thanks for the help!!


If your WiFi network doesn't have DHCP, then you must set the IP addresses

example:

  IPAddress ip(192, 168, 1, 8);
  IPAddress gw(192, 168, 1, 1);
  IPAddress sn(255, 255, 255, 0);
  WiFi.config(ip, gw, sn, gw);

gw is gateway. the last parmeter is dns server's IP. sn is subnet mask.


A resistor or a light bulb in parallel with the Arduino will increase the power consumption.


There seems to be no tutorials on how to do anything of the sort.

That's because doing such a thing is not something the manufacturer of a part typically expects you to want to do. Yes, some chips may be capable of other protocols internally, but making them use those protocols would mean direct manipulation of the low level components in the chip.
Chips like the ESP32 or the nRF24L01 are geared towards specific protocols. They expose functionality that is good for those protocols.
There are other chips which are designed with (almost) any protocol in mind, but there's nothing "arudinoy" about using them. To access other protocols you would download the SDK for that chip and create new firmware specifically for the protocol you want to use. In many cases such SDKs and the associated documentation is protected under NDA so you or I getting access to such a thing is not usually possible.
In general though a chip is designed with a specific protocol and application in mind and is optimised specifically to handle the requirements of that protocol.


Make upload stuck on osx 10.10 bare-arduino-project

I'm the maintainer of the Bare-Arduino-Project, thanks for using it :)

Have you installed pyserial and avrdude?

To install avrdude just run brew install avrdude and to install pyserial, you need python installed, then you can run pip install pyserial.

https://github.com/WeAreLeka/Bare-Arduino-Project/blob/master/INSTALL.md#3-install-pyserial

Hope it helps :)

Next time, feel free to open an issue in the Github repo as it might also help others.

EDIT: my bad, I did not read your Makefile carefully!

the problem is with:

BOARD_TAG         = mega328
# it should be
BOARD_TAG         = uno


How to execute commands on Arduino (via PC) without touching the current sketch?

The simple thing would be for your sketch to read from the serial port continuously. If it finds something it stores it and when a newline arrives it sees if that happens to be a password known only to you. So, for example, all you would have to do is plug in the USB cable, activate the Serial Monitor on your PC, type swordfish and the servo opens the box.

You would need to allow for garbage arriving, so make sure that you discard input if it exceeds the size of the buffer you allocate for this purpose.

  I have been told that the power to the Arduino should be disconnected before uploading new sketches (not sure why or if this is true).

I don't see how that can be true as you have to reapply power to upload the sketch. I never do that.

  Is it possible to execute code "command prompt" style?

No, you upload compiled code.

  Or can I somehow detect from within the sketch code that there is a USB connection, and have that trigger the unlock?

Then all the person you give the box to has to notice the USB port, plug something in, and it unlocks. I think not.

An even simpler solution would be to have two locations that unlock the box. For example, your kitchen could be one, so to unlock it you just take the box to your kitchen. The other location would be the "real" one that you want your friend to have to find. All the stuff about "you are 200 km from your destination" would of course refer to the real destination. You just make the code check that if it happens to find itself in your kitchen it unlocks the box.


Why do we need a transistor with a dc motor while we don't need one with a servo motor?

A servo typically has 3 wires: Power, Ground, and Signal

Inside the servo are a bit of electronics that read the input signal duty cycle, the absolute position of the horn, and power the motor in forward or reverse accordingly. There are transistors inside the servo housing to handle the high current of the motor.

A standalone motor doesn't have any other control electronics that separate power from control inputs.

EDIT:

Just to clarify: the signal wire for the Servo doesn't carry any significant power. The IO pins on the Arduino should not be asked to provide more than 40mA of current, and the PWM signal to the servo falls under that current limit.

But to operate a motor, or other device which draws significant operating power, it (the motor) asks for much more than 40mA of current, which can burn out the IO pin and damage it forever. This is why a transistor or other "switch" is necessary: the device which switches the high-current on and off can itself be operated by a very low current.


Read one value from continuous data stream at a lower frequency

You're thinking backwards. You don't want to read slower (which is what delay does), you want to only send every 10th entry.

That is, count the lines as they come in. When you hit 10 you print one and reset your count.

In other words:

static int count = 0;

if(newParoData == true){

  count ++;
  if (count == 10) {
      count = 0;

      // (Why copy the line just to send the copy...?)
      for(int i=0; i<16; i++){
        paroToSend[i] = paroChars[i];
      }
      Serial.print(paroToSend); Serial.print('\n');     //transmit Paro data with a new line for each value
  }
  newParoData = false;
}


esp8266 deep sleep timer slightly inaccurate?

This (now 3 year old) github / esp8266 thread suggests using an external RTC if time tracking is of importance.  It also points at a dead NodeMCU document link.  That document appears to have move here.  This document describes the lengths taken to provide a better account for time passage during sleep.  Which, apparently, includes guessing at the sleeping chip's temperature:

  Time keeping on the ESP8266 is technically quite challenging. Despite
  being named RTC, the RTC is not really a Real Time Clock in the normal
  sense of the word. While it does keep a counter ticking while the
  module is sleeping, the accuracy with which it does so is highly
  dependent on the temperature of the chip. Said temperature changes
  significantly between when the chip is running and when it is
  sleeping, meaning that any calibration performed while the chip is
  active becomes useless mere moments after the chip has gone to sleep.
  As such, calibration values need to be deduced across sleep cycles in
  order to enable accurate time keeping. This is one of the things this
  module does.