How do I use I2C devices with Arduino? I have a few useful I2C components, such as a 16-bit port expander (MCP23017), which I'd like to use in various projects.

What do I need to do to make these work with Arduino? Will it work with any Arduino, or do I need a specific board or shield?

Arduino have the Wire Library that communicate with I2C.

  This library allows you to communicate with I2C / TWI devices. On the
  Arduino boards with the R3 layout (1.0 pinout), the SDA (data line)
  and SCL (clock line) are on the pin headers close to the AREF pin. The
  Arduino Due has two I2C / TWI interfaces SDA1 and SCL1 are near to the
  AREF pin and the additional one is on pins 20 and 21. As a reference
  the table below shows where TWI pins are located on various Arduino
  boards.

Board   I2C / TWI pins

Uno, Ethernet    A4 (SDA), A5 (SCL)
Mega2560 20 (SDA), 21 (SCL)
Leonardo 2 (SDA), 3 (SCL)
Due  20 (SDA), 21 (SCL), SDA1, SCL1

You can take a look at , this examples.

Like @TheDoctor said:

  The I2C data lines both need resistors to 3.3V. This keeps them from
  drifting if they are disabled. Andy resistor value should work, but it
  is recommended to use one between 10k ohm and 47k ohm.


Unable to compare char from radio (RF24) The code below is receiver code using nRF24L01. In the loop section I'm comparing the char that was being sent from the Arduino transmitter. In this case the char array says "I'm off" just like the char array compare below. Even though the text is the same, it does not do what it is supposed to do.

Basically the if function below does not seem to work for some reason, both are char arrays (the text[32] and compare[32]) and both will have the same value which is "I'm off" yet it is not registered as the same thing. I cannot figure out what is wrong with the code, please help.

This is the receiver code. The question is about the if function in the loop below.

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

RF24 radio(7, 8); // CNS, CE
const byte address[6] = "00001";

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    char text[32] = "";
    char compare[32] = "I'm off";
    radio.read(&text, sizeof(text));
    Serial.println(text);
    Serial.println(compare);
    // this is the problem  -->
    if (text == compare) {
      // it is supposed to print this but it does not -->
      Serial.println("not on");
    }
  }
}

This is the transmitter code

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CNS, CE
const byte address[6] = "00001";
const int button = 5;

void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
  pinMode(button,INPUT);
}

void loop() {
  int reading = digitalRead(button);
  if(reading == HIGH) {
    // send a message to the radio
    const char text[] = "I'm on";
    radio.write(&text, sizeof(text));
    delay(1000);
  }
  if(reading == LOW) {
    // send a message to the radio
    const char text[] = "I'm off";
    radio.write(&text, sizeof(text));
    delay(1000);
  }
}

That is not a good way to solve it.  That is a hack.  The String class does bad things on microcontrollers and it is something you should try to stay away from.  What you need to compare two char arrays is the strcmp function.

if(strcmp(someCharArray, anotherCharArray) == 0){
    // the strings are the same
}

Use google to find out more about strcmp.


Understanding transistor datasheets I'm trying my best to understand and utilise questions that already exist as well as other websites, however I just wanted to check the circuit I've come up with (which is a very simple switch circuit) will work.

I plan on using a BD139 transistor, although I haven't purchased anything yet, so can change to anything really.

The fans are each 0.09A at 12V. I've calculated that R1 should be 360ohms. The 5V control will be coming from an Arduino. I believe it's within the specs of the transistor. Ic max is 1.5A.

Does the circuit look correct? Are there any changes I should make?

For saturation you should assume hfe to be 10. This gives:

(5V − 0.85V) / ((0.09A ⋅ 3) / 10) = 154 Ω

Consider using a 150-220Ω base resistor instead. And since a fan is an inductive load, don't forget the flyback diode from the collector to the +12V rail. A 1N4000 series diode should be fine for this small a load.


Is there a way to make a function take an exact number of clock cycles? Is it possible to use something like a compiler directive to pad a function with do nothing instructions so that as you add lines of code or take them away it always executes in the same amount of time?  I know there is the blink without delay style of writing a loop, but I want something a little more exact.

To the best of my knowledge, there is not. What you speak of is possible, but it must be done manually by counting cycles, and I suspect it wouldn't actually help you. (And then you get into CISC issues where instructions can take different amounts of time to execute, potentially depending on arguments. Arduino (the actual one) is kinda safe from that, but branch instructions still take multiple cycles, for instance. This says nothing about all the boards that work with, but aren't, Arduinos.)

There are two potential routes for this.

If this is for crypto, where you want to avoid side-channel attacks by detecting the length of an authentication or hashing function, it's not a good idea. Use a well-known library to do it instead, since in practicality it's not a good or safe idea to write your own (although if it's for a homemade door lock or safe lock, it's probably not a relevant issue since there are larger and more important security issues that will likely be found first despite your best efforts).
If, as I suspect, you simply want a piece of code to run at very precise time intervals, I suggest you look up something like the FreeRTOS port for Arduino. That will let you schedule a task to run preemptively so that it will always run at intervals. The BWOD sketch is still quite accurate, mind you, and below is a self-correcting version that compensates for any times that it might run a bit late (meaning that it should ALWAYS execute with millisecond precision, repeatably):

  unsigned long currentMillis = millis();//and you could always use micros()

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis += interval;//adjustment for additional accuracy

    //The task you want to run would go below:
    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }

The caveat to your stated goal is that any microprocessor WILL NOT execute code exactly when you want. Arduino too is incapable of this, since even a blank sketch runs several interrupts that will take over the processor for short periods of time, causing your hypothetical sketch to be delayed. You HAVE to use a reference method like BWOD or a scheduler like FreeRTOS. These use a reference or set up their own interrupt to make sure that they run on time, with the only interrupts that could be an issue being the ones that run during that instance of the task.

What this means is that they have a bit of overhead to add spacing between tasks so that if one is delayed, it won't cause the next to run late. So do mind that you'll lose a quite small percentage of CPU time to your scheduler, but if that's really an issue, find a better board (like TI TIVA/Energia IDE).


Nesting loops - if statement in a while loop I have been trying many variations of code like this, cannot seem to get this to work with how I logically would think it would work.  Am I missing something with syntax or breaking some rules?  Everything works independently but not jointly.

int switchS = 0;
int var = 1;

void setup() {
    pinMode(1,INPUT);
    pinMode(7,OUTPUT);
    digitalWrite(7,LOW);
}

void loop() {
    switchS = digitalRead(1);
    while(var == 1)
    {
        digitalWrite(7,HIGH);
        delay(100);
        digitalWrite(7,LOW);
        delay(100);
        if(switchS == HIGH)
        {
            var = 0;
        }
    }
    delay(5000);
    var = 1;
}

I guess you want the while loop to exit, when the switch goes to HIGH. (You didn't explain this in your question)

Currently the variable switchS cannot ever change while the code is in the while loop. The variable var only changes, when switchS is HIGH. So, if switchS is LOW at the start of the while loop, you have an infinite loop.

Instead, you can actually read the switch state inside the while loop, not outside of it. The variable switchS will not automatically track the state of the switch. You have to explicitly read it. Like this variant of your code:

int switchS = 0;
int var = 1;

void setup() {
    pinMode(1,INPUT);
    pinMode(7,OUTPUT);
    digitalWrite(7,LOW);
}

void loop() {
    while(var == 1)
    {
        digitalWrite(7,HIGH);
        delay(100);
        digitalWrite(7,LOW);
        delay(100);
        switchS = digitalRead(1);  // I moved this line in the while loop, to read the switch on every loop iteration
        if(switchS == HIGH)
        {
            var = 0;
        }
    }
    delay(5000);
    var = 1;
}

Note: You are using pin 1 as input pin. On the Uno this is a Serial (UART) pin, which is used to communicate with the PC. If you have enough pins, that are free, you should not use pins 0 and 1, so that you don't block the serial communication, unless you really need it and know, what you are doing.


Interference at digital input (UNO) I was trying out a basic button tutorial on my new Arduino UNO. But for some reason, the Arduino was detecting the button as on (pressed) even when it was off (unpressed).

After some experimentation, I found that the digital pins were flickering between HIGH and LOW, even if there was just a loose wire plugged in with nothing at the other end. And the state of the button, etc. wasn't making any difference. I tried this with pins 5,6 and 7, and it's happening with all of them, even when the neighbouring pins are connected to the ground.

Is this behaviour normal or is there something wrong with my input pins?

Since I'm new to Arduino, there might also be something wrong with my testing code. Here's what I used...

const unsigned int LED_PIN = 12;
const unsigned int BUTTON_PIN = 7;
const unsigned int INDICATOR_PIN = 13;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT);
  digitalWrite(LED_PIN, LOW);
}

void loop() {
  const int BUTTON_STATE = digitalRead(BUTTON_PIN);

  if (BUTTON_STATE == HIGH) {
    digitalWrite(LED_PIN, HIGH);
    digitalWrite(INDICATOR_PIN, LOW);
  }
  else if (BUTTON_STATE == LOW) {
    digitalWrite(LED_PIN, LOW);
    digitalWrite(INDICATOR_PIN, HIGH);
  }
}

This code makes the lights always in opposite states: when one is on, the other is off. When I ran the code, both lights seemed on, which meant they were probably flickering, which meant that there was some interference in the input pin.

It sounds like you're seeing entirely normal behaviour. If you leave a digital input unconnected (or connected to an open button) then it's 'floating'. That means it can pick up interference from all sorts of things, and may appear to drift between high and low.

The usual way to resolve this problem is using a pull-up or pull-down resistor. This is usually a high-ohm resistor (e.g. 10,000 Ohm or more) which will gently pull the pin HIGH or LOW in the absence of any other signal. When another signal comes in (e.g. from a button being pushed), it should have a much stronger effect than the resistor, so that is what the input will see.

Your Uno has built-in pull-up resistors which you can use for this, although it will require a couple of changes. In your setup() function, you can enable the pull-up on your input pin like this:

pinMode(BUTTON_PIN, INPUT_PULLUP);

That will cause the input to appear HIGH when the button is not pushed. That means you'll need to wire the other end of your button to ground (negative) instead of the voltage supply (positive). If you've set it up correctly, the input should appear LOW when the button is pushed.


Help understanding code to build circuit for plant reader I'm working a design project that measures the tiny changes of conductivity in a plant. (To visualize how a plant reacts to its environment) I'm working with Arduino to realize that. Two wires are hooked up to the plant to measure the changes and are connected to the Arduino. I haven't worked with Arduino before but a friend got me the code from his plant reader (he got help too and doesn't know how to build it anymore). I do understand most of it but I just don't manage to translate the code he gave me into a circuit on the Arduino bread board. I use processing to visualize the measurements afterwards.

Who can help me building the circuit. I don't get what's happening at pin13. Thank you for helping me :)

Pin13 is attached to the onboard LED.

So when you see a reference to it, it means that the program is turning the light ON/OFF. You do not need to do any wiring with it.

But the logic seems strange: it turns the LED off only when the analog reading is out of range (and it resets the stress).

It seems to imply that once the plant is stressed, it will stay stressed :-)

Btw, as side note: posting the code in ASCII form would allow people to quote/comment on it. The screenshot is not very good for that purpose.

What cannot be figured out from the code, is how to instrument your plant.
If your friend has a working setup, you could try to replicate it.
At least post a few pictures.


Connecting an arduino uno to an arduino due So I am trying to get my arduino uno to talk to my arduino due but I'm having issues getting the data outputted on the due side. My arduino uno is the master while the due is the slave. The sensor is connected to the uno and I just require the arduino due to receive and spit out the data as it has a faster sampling rate than the arduino uno. I connected them along the serial (Tx and Rx) lines. And I'm using Serial3 on my arduino due to receive the transmitted data. Both arduinos are grounded together. But powered differently by usb cables connected to my machine. On the arduino uno end ( for brevity sake) the data is sent in binary with the $ sign as the starter bit. Here is the code for the receiving end ( the slave). I just can't seem to get the data out on the serial monitor.

    byte b = '$';
    unsigned char buffer[12];
    int count =0;

    void setup() {
    Serial.begin(115200);
    Serial3.begin(115200);
    delay(5);

    }

   void loop() {
   if(Serial.available())
   {
    if (b == Serial.available())
   {
    while(Serial.available())
    {
      buffer[count++] = Serial.read();
       if(count == 12)break;
      //Send the byte to serial port three
      Serial3.write(buffer, count);
    }
 }

 if (Serial3.available()){
  //get a byte from serial port 3
  if(b == Serial3.available()){
    buffer[count++] = Serial3.read();
    //Send the byte to the USB serial port
    Serial.write(buffer, count);
  }
 }
 Serial.println("lyca");
 }
  }

if(Serial.available())
{
 if (b == Serial.available())
{
 while(Serial.available())
 {

I think you may be getting your knickers in a twist there.

... Is serial available? Yes. Is serial available? Still yes! But yes doesn't equal '$'!!!... WHAT?!

You really really need to rethink your understanding of serial communication.

Read this: http://hacking.majenko.co.uk/reading-serial-on-the-arduino


What does serial monitor send with 'Both NL & CR' There is something I don't understand about serial monitor.

As far as I know the Newline option is \n.

The Carriage return option is \r\n.

But does that make the Both NL & CR option \n\r\n?

Newline is \n

Carriage Return is \r

Both NL & CR is \r\n


How to filter data of ultrasonic sensor using arduino I am working on a project that uses ultrasonic HC-SR04 sensor to measure distance. I've connected the sensor to the Arduino Uno board, I am also using Arduino IDE to program the Arduino. The problem is that I am not getting stable readings, there is the presence of some noise in the readings. How should I filter out this noise.

Circuit connections are as follows:

Ultrasonic sensor | Arduino
VCC                 5V
GND                 GND
Trigger             12 (digital)
Echo                11 (digital)

I am using new ping to measure distance.

Having noise in the sensor data is common and normal, especially on low end sensor.

As you can imagine there is a "data science" to clean up the values, mostly based on statistic.

One of the easiest trick is to remove all values that have a difference > Xt from previous value; as you can imagine the tolerance Xt is calculated by a factor X, let's say a bit more the maximum speed you think the system will operate in time multiplies by the time since the last valid measure.

For example you expect a max distance chance of 10m in one second, so we use as tolerance 15m/s. If we don't read valid value, after 6 seconds our tolerance is 15m/s * 6s = 90m

Of course after much time maybe you just want to accept the first reading that seems valid, so you analyze 10, 100, 1000 value and see if they seems correct.

Then for a quick and dirty smoothing and cleaning if the remaining data, you can run a average on the value, there are different forms, and more value you use more stable are your output, but also less fast to follow changes.

A kallmann filter is the most common but also complex way to clean the data, but I guess in most hobbyist application is just overkill.


How to manage two alarms with one interrupt? I have a datalogger using the RTC DS3231 as an interrupt generator. I am able to have the interrupts work but here is my problem. I would like to take 2 separate measures from 2 different sensors (one for humidity, temperature and the other for accelerations), one every 30 min et one every hour, the thing is that because I use the same pin (only one pin from the DS3231) for both of these alarms I cannot use a simple counter in my interrupt function otherwise one measure will not be taken when both of the alarms will trigger...

For example I just did a quick test with one alarm each min when seconds are 00 and an other alarm each minute when seconds are 20. The problem as I said is that I cannot increment counters for each since I use the same interrupt function (because of the single pin).
Here is my loop function and interrupt handling function :

void loop() {
  delay(1000);
  sleepNow();
  if (alarm == true){
    handleAlarm(); // reset the possibility to trigger alarm
    if (counter_dtphl == COUNT_DTPHL){
      take_measure_DTPHL();
      counter_dtphl = 0;
    }
    else if (counter_accel == COUNT_ACCEL){
      take_measure_ACCEL();
      counter_accel = 0;
    }
  }
}

void wakeUpNow() {
  Serial.println("In wake up now");
  delay(100);
  alarm = true;
  //Serial.println(counter);
  sleep_disable();//Disable sleep mode
  byte sec = get_date(SEC);
  Serial.println(sec);
  if (sec == 0){
  counter_dtphl +=1;
  }
  else if (sec == 30){
  counter_accel +=1;
  }
  detachInterrupt(digitalPinToInterrupt(interruptPin)); //Removes the interrupt from pin 2;
}

void handleAlarm() {
  alarm = false;
  rtcObject.LatchAlarmsTriggeredFlags();
}

COUNT_ACCEL and COUNT_DTPHL are constant having the value of minutes corresponding to the trigger for the measure.

Has anybody an idea how to manage this situation ?
For the acceleration I need to save the data for a period of 30 sec. One solution I tried is to increment the counter according to the time in second that corresponds each minute but I cannot put it in the wakeUpNow function since only fast processing should be done there (it is the function executed by the interrupt).

Thank you for your time !

Consider it is good practice to leave as little code in an interrupt as possible.  In this case, as the time in question is much greater then how often the loop() function is called, setting a single flag indicating an interrupt occurred would be sufficient.

Each time in your loop() function test for this flag.  If TRUE, immediately set it to FALSE so as not forget to do so later.  Next, while still in the scope of the IF statement, assuming the RTC DS3231 has been configured to create an interrupt every 30 minutes, take your "30 minute sample".  Next, while still in the scope of the IF statement, increment a counter.  Make sure this counter is defined as a global variable in order to persist between calls to the loop() function.  If this counter has reached the value of 2, clear this counter to zero and take your "60 minute sample".

Consider the following pseudo code:

// Global variable defined outside of functions to track state & time.
bool state_interrupts;
int counter_interrupts;

void setup()
{
  // Initialize RTC to generate an interrupt once every 30 minutes.
  <RTC initialization code.>
  // Call attach interrupt to identify interrupt function name "wakeUpNow".
  attachInterrupt(...)
  // Initialize state & counter;
  interrupts_state = false;
  interrupts_counter = 0;
}

void loop()
{
  // Check if interrupt occurred.
  if(interrupts_state)
  {
    interrupts_state = false;
    interrupts_counter++;
    // Sample 30 minute sensor.
    <Sample 30 minute sensor code.>
    if(interrupts_counter >= 2)
    {
      interrupts_counter = 0;
      // Sample 60 minute sensor.
      <Sample 60 minute sensor code.>
    }
  }
}

void wakeUpNow()
{
    interrupts_state = true;
}


Reprogram CH341A chips VID PID etc I know it's possible (in theory) to reprogram the VID PID details back into a chip. It is however way beyond me.

Recently I learned that Microsoft distributed a piece of malicious software as part of their Windows update service. This virus was written by the FTDI chip makers to brick any chips such as the CH341's found in many cheaper Arduinos et al.

The virus attacked my CH341A serial to USB chip by writing 0's to the VID PIC and probably other locations. This makes the hardware 'Unknown' and even if you have the correct driver software, the device is never associated with it.

Does anyone know a solution to get the zeroed information back into the CH341A?

Here's the guide I used to correct the problem :-

HOW TO FIX THE USB-FTDI PROBLEM

(on arduino nano, usb ttl, ft232, ...)

There must have been a production of faulty ftdi drivers (version 2.12.0.0 or later) on august 2014 that makes some arduino boards and other usb devices not readable from the computer. The problem is random, meaning that it is possible to program the arduino a couple of times and then it comes out the ftdi problem, at that point the board isn't accessible anymore.

Once you come up with this problem, upgrading/downgrading the drivers, the IDE or the bootloader is just a waste of time, as the ftdi driver installed leaves some wrong data. This guide followed step by step will completely fix the driver problem thus making your board working again.

Step 1: check if you have a faulty ftdi chip driver

Not every ftdi chip has faulty drivers, so the first step is to check the chip's driver version. In order to check the version you need a software like usbview or usbdeview (both freeware and don't need any installation). Run the software and look for the "USB serial converter" device which is the one related to the ftdi driver, then read the vendor-id and the Product-id whose values should be 0x0403 for the vendor and 0x6001 for the product. The goal is to modify that 0x6001 value with 0x0000, and to do that we need some other software.

Step 2: modify values

Unplug your arduino nano or usb device. In order to modify the driver values you need CDMUninstaller (no installation needed). Fill the vendor and product fields with the values found with usbview (0403 and 6001) and click 'add', finally click 'remove devices'.

Step 3: download the 2.10.0.0 ftdi driver

Go to the ftdi website and download the 2.10.0.0 virtual driver choosing between 32 or 64 bit version, voiding the 'setup executable' file: just download the folder. After downloading the folder, we have to overwrite some files inside of it. Click FTDI.rar to download the files already modified, and place them inside the 2.10.0.0 folder overwriting the old ones.

Step 4: connect your arduino board

connect your arduino board, and stop windows from looking for new drivers. Go to device manager and look for FT232 USB device, then right click on it, select Properties and click on update drivers. Manually select the place in which scan for the new drivers and choose the 2.10.0.0 driver folder with the modified files. Now windows will prompt you saying that it can't certificate the new drivers. Ignore the alert and proceed with the installation. Once installation has finished, windows should recognize the connected board as 'USB recuperacion'.

Close the window and go to device manager, and look for the COM ports device. The connected device is now showing up like USB recuperation by ElectroHobby.es

Step 5: modify the chip eeprom

This is the last step and you need to restore the initial vendor and product values inside the ftdi chip eeprom. In order to do that you need to download and install Ftprog, click on the magnifing glass icon, select 'USB device descriptor' and again select 'custom pid'. Finally click on 'ftdi default'.

A new window shows up and you just need to check flag the device list and then click on 'program'.


Is possible to concatenate integers? It's a basic one: I have two values from two different analogRead pins:

int val1;
int val2;

For example, val1 = 10 and val2 = 10. How could I put these two values into a variable val3 = val1 + val2 that will give the answer 1010, instead 20 ?

If you are reading from the analog pins then the values are 10 bits (not 8 as suggested above).  Are you looking at concatenating 2 10 bit numbers or 2 16 bit numbers or are you using a zero or duo in which case they could be 12 bit numbers.

In any case:

const int BITMASK = 0x3FF;  // 10 bits = 0x3FF, 12 = 0xFFF, 16 = 0xFFFF
const int BITWIDTH = 10;
long result = ((value1 & BITMASK) << BITWIDTH) | (value2 & BITMASK);

I suspect it won't give you the answer you want, but...


Question of proper usage for F Macro Here are three use cases. Are all preferred or is the use of the F() macro pointless on some?

1.

Serial.println(F("some string"); // definitely useful here

2.

String str = F("some string");
Serial.println(str);

3.

int num = 5;
String str = F("some string with int ");
str += (String)num;
Serial.println(str);

Any time String is involved F() becomes pointless. Avoid String like the plague if you value your memory integrity.


clkI/O 256 & 1024 (From prescaler) not working with driving PWM on Nano board I've been working with PWM in TIMER0 of my nano board.

So, it's working now and I know how to set OCR0A or OCR0B.

Then, I went to play with Clock Select Bits CS02 CS01 CS00 in TCCR0B.

0, 8 and 64 prescaler configurations worked as I also don't see the effect on the LED fade speed.

But the more problem I get is that 256 and 1024 prescaler don't work at all and the LED goes on all the time.

What is the problem?

The code:

void setup() {
    DDRD |= (1<<DDD6);
    TCCR0A |= 0xC1;
    TCCR0B |= 0x00; // this works for 0x01, 0x02, 0x03 only
    }

    void loop() {
    uint8_t i;
    for (i=0;i<256;i++)
    {
      OCR0A = i;
      _delay_ms(1);
    }
    }

regards,

The main problem is the prescaler on Timer0 is already configured to divide clock source by 64 CS01 and CS00 are set (0b00000011).

And you are using bitwise OR to "change" prescaler: TCCR0B |= 0x05; or TCCR0B |= 0x04;. But this'll result into the clock source 7 (0b00000111) - clock source is expected on T0 input counting on rising edge.


Neopixle animation help Ok I'm stupid when it comes to coding. I have a simple project that I need some help with. Is it possible to make neopixle change what animation runs via multiple switches. Example they stay off till switch is flipped then if a different switch is flipped they run a different animation and vice versa.

Yes absolutely it is possible. As a beginner, I suggest something like this:

simulate this circuit – Schematic created using CircuitLab

In your setup you will need to declare D4 - D7 as inputs. I have used D4 - D7 but you can choose whatever pins are available.

Then in the loop part of the code you want to look for the rising edge on the input (ie when the switch is pressed). Switch debounce is less important for this application as it is not a counter but rather a mode change.

I have written a good answer for detecting a button press here.

Nick Gammon has an excellent switch tutorial gammon.com.au/switches that covers all kinds of conceivable situations (high or low, GND or +5V, internal pull-up or pull-down, capacitor debounce or software debounce, etc.)

I would imagine the code would look something like this:

if( digitalRead(SW1) == HIGH )
    mode = 1;

if( digitalRead(SW2) == HIGH )
    mode = 2;

if( digitalRead(SW3) == HIGH )
    mode = 3;

if( digitalRead(SW4) == HIGH )
    mode = 4;

You could then use a switch-case statement to run the various NeoPixel patterns.

For more programming reference see: https://www.arduino.cc/reference/en/


How can I declare an array of variable size (Globally) I'd like to make three arrays of the same length. According to the documentation, Arrays must be defined as int myArray[10]; where 10 can be substituted for a known length (another integer), or filled with an array {2, 3, 5, 6, 7}.

However, when I attempted to declare a value int arrSize = 10; and then an array based on that size int myArray[arrSize];, I get the following: error: array bound is not an integer constant.

Is there a way to variably determine array sizes, or do I just need to hardcode them? (I was taught hardcoding is bad and something to avoid at all costs.)

Your question has 2 parts actually.

1/ How can I declare the constant size of an array outside the array?

You can either use a macro

#define ARRAY_SIZE 10
...
int myArray[ARRAY_SIZE];

or use a constant

const int ARRAY_SIZE = 10;
...
int myArray[ARRAY_SIZE];

if you initialized the array and you need to know its size then you can do:

int myArray[] = {1, 2, 3, 4, 5};
const int ARRAY_SIZE = sizeof(myArray) / sizeof(int);

the second sizeof is on the type of each element of your array, here int.

2/ How can I have an array which size is dynamic (i.e. not known until runtime)?

For that you will need dynamic allocation, which works on Arduino, but is generally not advised as this can cause the "heap" to become fragmented.

You can do (C way):

// Declaration
int* myArray = 0;
int myArraySize = 0;

// Allocation (let's suppose size contains some value discovered at runtime,
// e.g. obtained from some external source)
if (myArray != 0) {
    myArray = (int*) realloc(myArray, size * sizeof(int));
} else {
    myArray = (int*) malloc(size * sizeof(int));
}

Or (C++ way):

// Declaration
int* myArray = 0;
int myArraySize = 0;

// Allocation (let's suppose size contains some value discovered at runtime,
// e.g. obtained from some external source or through other program logic)
if (myArray != 0) {
    delete [] myArray;
}
myArray = new int [size];

For more about problems with heap fragmentation, you can refer to this question.


Problem using Optiga Trust X I2C Did someone ever used the Infineon Optiga Trust X module with Arduino using any I2C library ?

Here is the technical documentation of the Trust X module.

I'm trying to get the I2C_STATE register data but I don't receive anything after the Wire.requestFrom().

I also tried with the DSS Circuits I2C Master Library, same results.

Thanks

Full code :

#include <Wire.h>
#define PIN_RST 8
#define PIN_VDD 9

void setup() {
  pinMode(PIN_RST, OUTPUT);
  pinMode(PIN_VDD, OUTPUT);
  digitalWrite(PIN_RST,LOW);
  digitalWrite(PIN_VDD,LOW);

  Serial.begin(115200);
  delay(2000);
  Wire.begin(); // join i2c bus (address optional for master)

  digitalWrite(PIN_VDD,HIGH);  // sartup the Trust X module
  digitalWrite(PIN_RST,HIGH);

  delay(15);  // startup min delay
}

long val = 9999;

void loop() {
  Wire.beginTransmission(48); // transmit to device #48 (0x30)
  Wire.write(byte(0x82));            // sends instruction byte
  Wire.endTransmission();     // stop transmitting

  Wire.requestFrom(48, 4);
  while(Wire.available()==0){}

  val = Wire.read(); // Reads the data from the register
  Serial.print("val = ");
  Serial.println(val);

  delay(5000);

}

So I finally succeeded to read a register value. I don't really know where was the problem. Here is the code if it can help someone (the scanner still does not work btw) :

#include <Wire.h>

#define DEVICE_ADDRESS 0x30

#define PIN_RST 8
#define PIN_VDD 9

void printOutput(byte *out, int out_len){
   int y=0;
  Serial.print("out = ");
  for(;y<out_len;y++){
    Serial.print(out[y],HEX);
  }
  Serial.println("");
}

void coldReset(){
  pinMode(PIN_RST, OUTPUT);
  pinMode(PIN_VDD, OUTPUT);
  digitalWrite(PIN_VDD,LOW);
  digitalWrite(PIN_RST,LOW);
  delayMicroseconds(2000);
  digitalWrite(PIN_VDD,HIGH);  // sartup the Trust X module
  digitalWrite(PIN_RST,HIGH);
}

int I2C_get(byte reg, byte *out, int out_len){
  int i=0, nbSend=0, nbAvailable=0, ret=0;
  Wire.beginTransmission(DEVICE_ADDRESS); // transmit to device #48 (0x30)
  nbSend=Wire.write(reg);            // sends instruction byte
  Wire.endTransmission();     // stop transmitting
//  Serial.print("nb send = ");
//  Serial.println(nbSend);

  delayMicroseconds(50);
  Wire.requestFrom(DEVICE_ADDRESS, out_len);

//  nbAvailable=Wire.available();
//  Serial.print("nb available = ");
//  Serial.println(nbAvailable);

  if(Wire.available()==out_len){
    for(;i<out_len;i++){
      out[i]=Wire.read();
    }
  }
  else ret=-1;

  return ret;
}

void setup() {

  Serial.begin(115200);
//  Wire.begin(); // join i2c bus (address optional for master)
//  coldReset();
//  delayMicroseconds(15000); // Startup time
}

void loop() {
  int y=0, out_len, ret;
  byte res1[]={0x00,0x00,0x00,0x00};

  Wire.begin(); // join i2c bus (address optional for master)
  Wire.setClock(400000);
  coldReset();
  delayMicroseconds(15000); // Startup time

  out_len=4;
  ret=I2C_get(byte(0x84),res1,out_len);
  if(ret!=-1){
    printOutput(res1,out_len);
  }
  else{
    Serial.println("Error I2C_get");
  }

  Wire.end();
  Serial.println("");
  delay(5000);
}


How to run my IDUINO Yun Shields stand-alone? Experts,

How can I power and communicate with the IDUINO shield stand-alone? In other words, without any additional uC for it to plug into.

Failing in that, can a Nano (cheaper, smaller) be wired to give the Yun what it needs?

Yes, you can. All you need do is provide it with a regulated 5V supply on the 5V pin and it should power up and boot.

There's not a lot of IO on it though, so connecting to sensors and such would be hard, which is where the Arduino comes in handy. You communicate using the UART, so any microcontroller with a UART can be connected to it.


What difference makes resistance of thermistors? Following this thermistor tutorial i used 1k thermistors (and resistors) instead of 100k as in video.

What difference does it make?
What about 10k thermistors?
Is it good idea to use 1k/10k/100k potentiometer instead of resistors to tune up readings?

The standard way to measure a resistive sensor is to make a voltage
divider with the sensor and a fixed resistance between Vcc and GND, like
this:

Vcc
 │
 Rb
 │
 ├─── analog input
 │
 Rx
 │
GND

where Rx is the resistance you want to measure and
Rb is a known bias resistance. The only unknown is the choice
of the bias resistance.

The simple rule of thumb is to choose a bias resistance close to the
typical values of the resistance you want to measure, as this will
optimize your measurement resolution. More specifically, the relative
measurement resolution, which could be stated as the number of ADC steps
you get per percent change in resistance, is maximal when Rx
= Rb, and decreases only slowly as Rx gets
further from Rb.

Now, one could argue that the relative resistance resolution is not
always the best performance metric. You may want to maximize the
absolute resistance resolution instead, or maybe the absolute
conductance resolution. Each of these choices would lead to a different
choice of bias resistor. For the case of a thermistor, however, the
choice is pretty clear: the resistance varies almost exponentially with
temperature, which means that the absolute temperature variations are
practically proportional to the relative resistance variations. If you
want to use temperature resolution as a metric, you could go through a
tedious calculation only to find out that the optimal Rb is
darn close to Rx.

In short, if your thermistor is 1 kΩ at 25 °C, and you will
use it near 25 °C, then a 1 kΩ pullup will give you the best
temperature resolution.

Now, measurement resolution may not be the only issue you care about,
and you may want to sacrifice some of it in order to improve something
else. For example:

Current consumption: a 1 kΩ thermistor in series with a 1 kΩ
pullup will draw 2.5 mA (assuming Vcc = 5 V), which
could rise to near 5 mA if it gets really hot. If you are running
off battery power this could be an issue.
Self heating: in that 1 kΩ + 1 kΩ configuration, the
thermistor will dissipate 6.25 mW. I've seen the datasheet of a
typical thermistor stating a thermal dissipation constant of
7 mW/K. This means the measurement current would heat the
thermistor to 0.9 °C above ambient temperature, which you would
need to take into account in your temperature calculations.

Both of these issues would be mitigated by using a larger value for
Rb, only at the cost of measurement resolution. Switching to
a 10 kΩ thermistor would mitigate these issues without sacrificing
resolution.


Error while saving data in text file I created a function that saves the timestamp in a text file, but it saves unreadable. Full of invalid characters, example: Ÿ@Â   O   ƒº!¥ Ÿ@Â   O   ƒº!¥ Ÿ@Â   O   ƒº!¥ Ÿ

#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include "RTClib.h"

RTC_Millis rtc;
File txt;
const char * getCurrentTimestamp()
{
    char dateBuffer[40];
    DateTime now = rtc.now();
    sprintf(dateBuffer,"%02u-%02u-%04u %02u:%02u:%02u", now.day(), now.month(), now.year(), now.hour(), now.minute(), now.second());
    return dateBuffer;
}

void saveLog()
{
  txt = SD.open("dados.txt", FILE_WRITE);
  txt.print(getCurrentTimestamp());
  txt.close();
}

void setup() {
  pinMode(53, OUTPUT);
  SD.begin(4);
  Serial.begin(9600);
  rtc.begin(DateTime(F(__DATE__), F(__TIME__)));
}

void loop() {
  Serial.println(getCurrentTimestamp());
  saveLog();
  delay(1000);
}

My code is very simple, do not understand where I went wrong. if I copy the following code snippet for saveData() function and save the dateBuffer variable, everything works normally.

char dateBuffer[40];
DateTime now = rtc.now();
sprintf(dateBuffer,"%02u-%02u-%04u %02u:%02u:%02u", now.day(), now.month(), now.year(), now.hour(), now.minute(), now.second());

how to save the timestamp correctly in the file through the function getCurrentTimestamp() ?

Your function, getCurrentTimestamp() saves the date string in an automatic variable - it is on the function's stack frame which gets freed as soon as that function returns. Either Serial.println() or savelog() is overwriting it.

The proper way to do what you're trying to do is to make the buffer live for the duration of both function calls. One way is to use a global buffer. Another is to declare the buffer in loop() and pass it to both functions.


Difference in Arduino pin distance I have an Arduino Uno rev 3. Today i tried to mount a breadboard as a shield for my Arduino on top of it. I plugged in the pin headers i bought and was surprised that the breadboard won't fit. As you can see in the picture below the distance between Vin and A0 is exactly the size of a pin, but the distance between pin 7 and 8 is less than that and so the breadboard won't fit on this side. What's the reasoning behind this (in my eyes) bad design ?

It is a mistake that became a feature for polarizing the shields: forum.arduino.cc/index.php?topic=117441.0

In an 2008 discussion Massimo says:

  "I made that mistake, when I made the first arduino board."

at http://forum.arduino.cc/index.php?topic=22737.msg171839#msg171839
with:


Control Android Camera using Arduino over Bluetooth I want to Control Android Mobile Camera shutter using Arduino over Bluetooth. So i can click photos using arduino.

I have HC-05 Bluetooth Module and Arduino Nano/Arduino leonardo.

The Connection as shown in figure.

The Android mobile successfully connected to Bluetooth Module but i am not found any code to control camera or any button on android mobile.

I am trying out Camera Pro. It allows shutter control on Android over Bluetooth. I just got an Uno R3 and and HC-05 so I have not wired it up to try it.

There are example sketch and detailed docs here.


Measure audio frequency through pulse duration Hello dear StackExchange users,
i want to develop an Infrared blaster which i can plug into the headphone jack of a phone or console of choice. In order to communicate what frequency to modulate the diode with and how long to send pulses, i simply generate tones for the Arduino to read and interpret.
My problem is that i can't reliably measure the frequency with it. In order to measure the frequency i use an Analog Comparator Interrupt and trigger at falling edge, thus getting always the interrupt after a full pulse occured. I called micros() at every interrupt in order to get the pulse duration, but it was too imprecise. Then i tried using Timer0 with a prescaler of 8 to measure the frequency, but it only counts to 255.
Now i switched over to Timer1 because of it's bigger TCNT register. However for some reason it already overflows at 255 even though i didn't set the OCR1 registers.
This is my current code. Please note that the actual frequency calculation happens in the main loop to not mess with the measurements gained in the ISR.
const int setFrequencySound = 1000;
const int receiveDataSound = 2000;
const int receiveDataEndSound = 3000;

const int readyMode = 0;
const int setFrequencyMode = 1;
const int receiveDataMode = 2;
const int sendDataMode = 3;

volatile unsigned long timeBefore;
volatile unsigned long timeNow;
volatile unsigned long delta;
volatile float audioFrequencyBefore;
volatile float audioFrequency;

volatile float irFrequency;
volatile int irData[100];
volatile int irDataIndex;

volatile int mode = 0;

ISR (ANALOG_COMP_vect)
{
timeNow = TCNT1;
Serial.print (timeNow);
Serial.println (" TCNT1");
//TCNT1 = 0; //reset timer register
}

void setup ()
{
Serial.begin (115200);
Serial.println ("Started.");
ADCSRB = 0;           // (Disable) ACME: Analog Comparator Multiplexer Enable
ACSR =  bit (ACI)     // (Clear) Analog Comparator Interrupt Flag
      | bit (ACIE)    // Analog Comparator Interrupt Enable
      | bit (ACIS1);  // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge)

TCCR1B |= (0 << CS12) | (1 << CS11) | (0 >> CS10); //Activate timer and set prescaler to 8
TCNT1 = 0; //Reset timer register
}  // end of setup

void loop ()
{
//Calculate frequency by using the period duration
//determined through the timestamps captured in
//ISR method.
//delta = timeNow - timeBefore;
audioFrequency = 1000000000.0 / (float(timeNow) * 2.0);

if (millis() % 1000 == 0)
{
  Serial.print (audioFrequency, 5);
  Serial.print (" Hz, ");
  Serial.print (timeNow);
  Serial.println (" TCNT0");
}

//Do not process the same frequency multiple times
if (audioFrequency != audioFrequencyBefore)
{
  switch (mode)
  {
    case readyMode:
      if (audioFrequency == setFrequencySound)
      {
        mode = 1;

        Serial.println ("Start setting IR frequency.");
      }
      else if (audioFrequency == receiveDataSound)
      {
        mode = 2;

        Serial.println ("Start receiving IR data.");
      }
      break;
    case setFrequencyMode:
      irFrequency = audioFrequency + 25000;

      Serial.print ("IR frequency set to ");
      Serial.print (irFrequency, 10);
      Serial.println (" Hz.");

      mode = readyMode;
      break;
    case receiveDataMode:
      if (audioFrequency == receiveDataEndSound)
      {
        Serial.println ("Stop receiving IR data.");

        mode = readyMode;
        irDataIndex = 0;
      }
      else
      {
        irData[irDataIndex] = audioFrequency;

        irDataIndex++;

        Serial.print ("IR pulse received: ");
        Serial.print (irData[irDataIndex]);
        Serial.println (" microsecs.");
      }
      break;
    case sendDataMode:
      Serial.println ("Sending IR data...");
      break;
  }
}

audioFrequencyBefore = audioFrequency;

}  // end of loop

Timer 1 overflows at 255 because that's how it has been configured by
the Arduino core, as it is intended to provide 8-bit PWM. If you want
to use the timer in normal mode, you should undo the Arduino's
initialization by setting TCCR1A to zero.
Two comments on the ISR:
ISR (ANALOG_COMP_vect)
  {
    timeNow = TCNT1;
    Serial.print (timeNow);
    Serial.println (" TCNT1");
    //TCNT1 = 0; //reset timer register
  }

First, as has been stated in a previous comment, you should not print
from within an ISR. Also, if you want consistent timing, you should
never reset the timer. Just keep it freely running and use time
differences to get the signal period. Do not worry about the timer
overflowing: if you do the computation with unsigned 16-bit integers
(uint16_t), you will be immune to the overflows. If you reset the
timer you will likely loose some ticks, as you can not read it and reset
it in the same clock cycle.
Lastly, I recommend you read about the “input capture” capability of
Timer 1. This is a feature of the timer designed for solving the exact
kind of problem you have here: the timer will automatically record a
timestamp on an external event. You can have this triggered by a rising
or falling edge on input pin 8, or by the analog comparator if you
prefer. This method gives you zero jitter, which cannot be achieved with
code, even running within an interrupt.

Edit: Answering an extra question in the comment.

Could i connect the audio wire [...] directly to pin 8 and use the
input capture functionality?

It depends on the shape of the signal that comes out of this wire.
First, you have to make sure the signal always stays between the
electric potentials of GND and Vcc (i.e. 0 – 5 V), otherwise you risk
damaging the Arduino.
Note that if the signal comes from a high impedance source, it can
safely go somewhat beyond this range, as the Arduino has all of its
inputs protected by diodes. You just have to limit the current in the
diodes to less than 1 mA. In other words, for each kΩ of output
impedance, you can extend the (unloaded) acceptable voltage range by 1 V
on each side. If the source is low impedance, you can make it high
impedance simply by adding a 10 kΩ resistor in series.
Second point is, you have to make sure the signal has a large enough
voltage span to make the digital input switch between LOW and HIGH.
According to the datasheet of the ATmega328P, when powered at 5 V the
input thresholds are typically around 2.1 V for switching LOW and 2.6 V
for switching HIGH. The difference between those thresholds provides
some hysteresis, which can help cancelling noise. Note that those are
typical values. If you want guaranteed switching, the signal should go
below 1.5 V to get a guaranteed LOW reading (this is VIL) and
above 3 V to get a guaranteed HIGH reading (VIH).
Note also that, if the input thresholds of the digital pin do not fit
your needs, you can use the analog comparator as a trigger for the input
capture.


Stack arduino, motor shield and lcd shield I made arduino-stack which consists of arduino r3, robotdf motor shild and robotdf lcd shield. But motor shield and lcd use same pins 4 and 5, so we have a conflict of pins. Can i use other pins?

Stack one shield on top of the Arduino itself and connect the other shield using wires. This way you can pick your own pin assignment for the 'external' shield.

Be careful when using a specific library though, sometimes the used pins are hard-coded in the library itself. Modifying the .h and .cpp files for the library is possible, so you could (hard code) assign your own used pins.


How do I import data from serial monitor to excel document without copying and pasting? I need to be able to import incoming data from a motion sensor and then from the serial monitor (where the data is) import the data to an excel document or file.

Any suggestions would help,

Thanks.

The Arduino IDE's serial monitor is just one of many tools that can open a serial port and collect information from it.

The first step is to make sure the data you are writing to the Serial object in the Arduino is in a format suitable for importing into Excel. Separate multiple values on one line with a comma "," or tab "\t" character.

If you are running windows, you can often just use the built-in type command from a command prompt to write the serial port to a file:

type COM4 >> log.txt

(Assuming the Arduino is on COM4 and you want to write the data to a file called log.txt.)

If you're on a Mac, open the Terminal app and type:

screen -L /dev/tty.usbmodem1441335 9600

(Assuming your Arduino is on serial port named tty.usbmodem1441335 and your port speed is 9600 bps.) The session will be written to a file called screenlog.0.

Then you can open the text/log file in Excel. If you rename it to end in .csv, that may also help Excel recognize it as tabular data.


Else Statement Never Functions As Expected I've been working on a rather simple Arduino-breadboard project, that is supposed to imitate a traffic light intersection. There are two sets of lights, one called the North-South lights, and then the East-West lights (quite similar to the traffic lights your would see at an intersection on the road). The goal is to get the traffic lights to turn their correct colors at the correct times; however, one of my yellow lights is not turning on at all, and the breadboard LEDs I'm using completely skip over the yellow light in question and go straight to the red-green configuratin that is supposed to happen after.
Here is the code I have:
void setup() {

  pinMode(2, OUTPUT); //R-ns
  pinMode(3, OUTPUT); //Y-ns
  pinMode(4, OUTPUT); //G-ns
  pinMode(5, OUTPUT); //R-ew
  pinMode(6, OUTPUT); //Y-ew
  pinMode(7, OUTPUT); //G-ew

}

void loop() {

  for(int count = 0; count<16; count++) {

    if (count<7) {
      digitalWrite(2, HIGH);
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      digitalWrite(7, HIGH);
      }

     else if (count==7) {
      digitalWrite(2, HIGH);
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      digitalWrite(7, LOW);
      }

     else if (7<count<15) {
      digitalWrite(2, LOW);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      digitalWrite(7, LOW);
      }

     else {
      digitalWrite(2, LOW);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      digitalWrite(7, LOW);
      }

    delay(1000);
    }

}

As you can see, the North-South traffic light is supposed to turn on at the 16th second, except I don't see it happen on the physical LED. I don't understand why this is happening; can anyone explain what is happening?

7<count<15 is interpreted as (7<count)<15.  7<count will result in a false or true, which will be interpreted as 0 and 1 when later involved in the < 15 part of the expression, which means 7<count<15 is always true.
What you're probably looking for is 7 < count && count < 15.


Trouble using proximity sensor as input and LED output I was wondering if anyone had any pointers or advice to make this project work. Essentially I would like to have the LED fade (meaning like fade on and off at a calm rate) at one rate when there is nothing close to the proximity sensor, and then to speed up the fade amount when there is something close to the sensor.

#include <NewPing.h>   //include the library

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount;    // how many points to fade the LED by

int triggerPin = 12;   //pin conneccted to the Trig pin on the sensor
int echoPin = 11;       //pin connected to the Echo pin on the sensor
int maxDistance = 200;  //set the max distance for the sensor to read (helps with errors)
int distanceVal;        //variable to hold the distance val

int sampleRate = 200;   //how fast to sample the value
long lastReading;       //used for the timer

NewPing proximity1(triggerPin, echoPin, maxDistance);   //sets up the sensor object

void setup()
{
  Serial.begin(9600);  //start the serial port
  pinMode(led, OUTPUT);
}

void loop() {

    if(millis()-lastReading>=sampleRate) //this very simple statement is the timer,
  {
  distanceVal = proximity1.ping_cm();  //get the distance value in centimeters

  lastReading = millis();

  Serial.print("Distance Reading CM : ");  //print the value to the Serial monitor
  Serial.println(distanceVal);

if(distanceVal<20){

fadeAmount = 5;
}
else{
  fadeAmount = 2;
}

  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
  }
}

https://github.com/sanaalla/Fade-LED-with-Proximity-sensor

Above is my code, which is not working. I am fairly new to Arduino and so would greatly appreciate some more seasoned wisdom!

You want 2 independant loops, one for the measurement and one for the dimming effect. The latter one must also be able to run when not measuring.

if(millis()-lastReading>=sampleRate) //this very simple statement is the timer,
{
  distanceVal = proximity1.ping_cm();  //get the distance value in centimeters

  lastReading = millis();

  Serial.print("Distance Reading CM : ");  //print the value to the Serial monitor
  Serial.println(distanceVal);
}

if(millis() - lastFade >= fadeRate) //other timer
{
  lastFade = millis();
  if(distanceVal<20){
    fadeAmount = 5;
  }else{
    fadeAmount = 2;
  }

  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }
}


boolean always false after 32 seconds I have a boolean expression (I think it's called), and it will always return false after 32 seconds of running, and I'm very confused now.

if (millis() > stepTime+lightCmd[stepe][5]) {
  stepe = (stepe+1)%STEPS; //I'm bad at naming variables, sorry
  stepTime = millis();
  Serial.println("changing"); // debugging
}

This runs inside the main loop.

Also, I've tried using an exponent when trying to get some lights to appear to fade linearly and in about the same amount of time, 32 seconds, it would start fading in reverse.

EDIT:

millis(); wouldn't go backwards after it stopped working

When dealing with millis and micros you must always use unsigned long variables; otherwise, values will be overflow/truncate.

When doing time arithmetic, you must always use differences, not additions, because of the nature of unsigned arithmetic.

Your updated sketch is this:

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

#define STEPS 3
unsigned long lightCmd[STEPS] = {4000, 60000, 90000};
int stepe = 0;
unsigned long stepTime = 0;

void loop()
{
    if(millis() - stepTime >= lightCmd[stepe]) {
        Serial.print(stepe);
        Serial.print(".- ");
        stepe = (stepe+1)%STEPS; //I'm bad at naming variables, sorry
        stepTime = millis();
        Serial.print(stepTime);
        Serial.println(" changing"); // debugging
    }
}


What is causing this 'narrowing conversion' warning? Because I'm still figuring out 'Arduino C' I leave all warnings on.

Recently I got this one:

narrowing conversion of '(int)(((unsigned char)bx_0) | ((unsigned char)bx_1))' from 'int' to 'const byte... etc.

...referring to this line:

const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};

...pointing to the or symbol.

The code in question (much simplified to recreate this):

const int latch[2] = {2, 4};

const byte bx_0 = 1 << latch[0];
const byte bx_1 = 1 << latch[1];

const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};

(This happens whether I use byte, uint8_t, or unsigned char everywhere.)

Without the or operator, no warning. If bx_0 and bx_1 are simple bytes, not shifted into existence, no warning. If I do this:

const byte pinMask[3] = {bx_0, bx_1, (byte)(bx_0 | bx_1)};

...again, no warning.

However, I get no complaints about this:

const byte notMask = !(bx_1 | bx_0);

...so a further condition is that the problem or has to be in an initializer list. Yikes.

I don't get it. There's no way an or of two bytes can force widening, so where did the (int) cast come from? It apparently has something to do with the 1 << latch[0] code, but the result of that is still a byte, by definition.

I have a solution -- the (byte) cast -- but in the real code it's ugly and feels unnecessary. Everything is already just bytes.

That warning message arises when a compiler complies with C/C++ specifications.

According to ISO/IEC 9899:2011 part 6.5.12.2 (“Bitwise inclusive OR operator”),

  Each of the operands shall have integer type

Thus, in the evaluation of bx_0 | bx_1 within the statement const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};, the operands bx_0 and bx_1 are converted to int type before being OR'd together.  This produces an int result, which then must be narrowed to byte before it can be stored in the  byte array.

Knowing that the (byte) cast is necessary because of C/C++ specifications should convert your view of the cast from “ugly” and “unnecessary” to “necessary” and either “ok” or “oh well”.  :)


Is it possible to program Arduino in transpiled JavaScript? Coming from JS, I find it very difficult to program Arduino in C++ (not even knowing which version or what features are supported), being bound to the loop and delay, not being able to (easily) use anonymous functions in parameters or async code.

I know JS isn't natively supported by Arduino, but I know languages can be transpiled.

I have seen many solutions, so just to pick few:
JohnnyFive J5, which runs via cable on a host PC,
NectarJS with their arduino-uno target,
or andrei-markeev/ts2c which converts ES3 to C89.

Each of them come with their own limitations and it's very difficult to find the right without prior experience with IoT. Did anyone walk this path already and found a viable solution?

Even if such a transpiler exists (which I don‘t know) you will still have to deal with the loop structure and the fact that you should avoid using delays. On a microcontroller you have to forget about things like multithreading and even dynamic memory allocation should be used carefully.
Most of those things that make a programmer‘s life easy on bigger systems are usually paid with ram or cpu power, but on a microcontroller with some kB RAM there are only few resources to pay with.

So my recommendation is to learn C++ instead of looking for ways to convert code from another language, which will probably introduce its own problems. You‘ll soon find yourself one layer below and there are exciting things that higher languages hide from you.


Optimizing code to use less Flash Memory and SRAM I'm trying to reduce my sketch size and managed to reduce both SRAM and Flash memory.

From:
1570 SRAM - 32144 Flash memory
To:
644  SRAM - 19458 Flash memory

This are what I've done so far:

✓ Enabling LTO

✓ Using PROGMEM

✓ Dropping string and using char

✓ Dropping bootloader

✓ Using port manipulation

✓ Using registers to declare pins output/input

✓ Removing/Optimizing/Combining; unnecessary/repeated codes in the sketch

Using EEPROM is not an option for me.

What else i can do to take optimization one or two step further?

What you can do in addition to the items you mentioned:

SRAM reduction

Use the smallest amount of data type for integers, e.g. use an 8 bit data type instead of the default integer, this saves you one byte for every variable. See remark below about types. I made my own types (if not existing) for int32_t, uint32_t, int16_t, uint16_t, int8_t and uint8_t and always use the smallest possible.
Use unsigned instead of signed for types that cannot be negative. This might save you one byte if you can prevent using an unsigned byte instead of a signed int because a value can be in range [128..255]. The same for unsigned int instead of signed long.
Use bit fields if you use multiple booleans inside a struct or class. Make sure the bit fields are declared consecutively.
Pack data in smart structures ... I.e. if you have two variables, where one can be 0..7 and another can also be 0..7, store this together using bit fields (in combination with boolean to bit field above).
Prevents float/doubles (see KIIV's comment below), instead:
Instead of using a float, multiply the value by the needed accuracy and store it in an integer (if you don't need high accuracy and it fits in the integer type).
In case you need a lot of strings to be stored, and those strings do not have characters above 128, you can save 1 bit per byte, of course this means quite some programming work to handle 7 bits 'ASCII' characters.
The same, if you have to store a lot of values that can be e.g. 0 to 50, you can use 6 bits instead of 8 bits; you cannot use bit fields, but you can make a smart array and program your own get/set functions to access the 6 bit values.
If you use libraries which declare big buffers, try to minimize those buffers, this might cause to copy them and manually change them yourself.
Prevent your own buffers to be made global, instead use them as a local variable temporarily when you need them. If you have two of such buffers, you don't have both buffers allocated at the same time; note however, that during execution, that buffer still needs space (so you have to calculate or make a guess/estimation what the maximum stack size will be).

Flash Reduction

Don't use duplicated code blocks, but make functions with parameters to differ between the differences of the duplicated code.
Instead of lookup tables, create a function that calculates it (if possible). Of course the gain depends on the length of the lookup table and the length of the function.
Instead of debugging strings, use numbers.

Both SRAM/Flash Reduction

Split your application over multiple MCUs, of course this adds some kind of communication protocol (UART, I2C, SPI).


NRF24L01+ unable to receive data I have 2 Arduino UNO R3 nodes communicating using NRF24L01+ transceivers with the TMRh20 library.

Setup I have original as well as cheaper but 'compatible' arduinos. One of the nodes uses an original arduino Uno whereas the other uses the cheaper one.

Observation

The node with the cheaper Uno can transmit data (sucessfully received by the other node) but is unable to receive data.
I have a number of Rf modules and UNo boards. The observation is similar across.
Using the same configuration (rf module, connection and code) , the original uno board receives data but noot the other types.
Another thing that i observed is that the cheaper uno comes with a 12MHz oscillator on the board whereas the original one has a 16 Mhz one.Can it be the source of problem?

This article mentions something that I could not get but am suspicious of it being a possible direction to the solution to the problem, only if someone could help.

  On Arduino UNO boards SPI pins are connected with some digital pins. While using modem you most remember that these digital pins won't be available.

As it turns out, the culprit was the power supply on the board.

The clone came with AMS1117 based regulator for the 3.3V which it did indeed generate (3.27 measured). Using it, the reception of the RF device failed (although it could transmit data). Also had 10uF and a 0.1uF capacitor hooked up in parallel to Vdd and Gnd of the NRF24L01+, as recommended. I therefore suspected something to do with the SPI configuration.

Finally, having powered the 3.3V to the Rf device from another genuine Arduino solved the problem. Not sure if it was the 3.3V rail from the clone possibly having excessive noise which may be causing the issue, as I did not see a reasonable drop in 3.3V output of the clone while in operation.


Convert C string to C++ string My program is running on ESP32. I'm retrieving some data from Bluetooth, and the Bluetooth string is a C string. I need to save that data in an RTC_DATA_ATTR String, which is a C++ string.

Just doing c++string = cstring.c_str(); won't work, since it will just save a pointer to the location in the memory of the C string, and the purpose is to save the data in the RTC memory, so the ESP32 can go to deep sleep without losing the data.

All other data than RTC gets wiped on deep sleep, so there would just be a pointer, pointing to nothing.

How do I get the data copied from the C string to the C++ string?

Any help would be appreciated. A bit of extra info: this is how it is set up at the moment:

RTC_DATA_ATTR String ssid;

BLECharacteristic *cSsid = NULL;

ssid = cSsid->getValue().c_str();

simply, using strcpy, and using a char with a given length, works

RTC_DATA_ATTR char ssid["dedicated length"];

strcpy(ssid, cSsid->getValue().c_str(), "dedicated length");


Adafruit Huzzah espcomm_open failed I recently bought an adafruit huzzah as well as a serial to usb cable to connect it to my computer running windows 10. I was able to get the board set up in arduino following the directions found here. I copied and pasted this sketch:
void setup() {
  pinMode(0, OUTPUT);
}

void loop() {
  digitalWrite(0, HIGH);
  delay(500);
  digitalWrite(0, LOW);
  delay(500);
}

into the arduino 1.8.2 IDE, followed these instructions:

Hold down the GPIO0 button, the red LED will be lit
While holding down GPIO0, click the RESET button
Release RESET, then release GPIO0
When you release the RESET button, the red LED will be lit dimly, this means it's ready to bootload

and tried to upload only to get an error:
In versions 1.6.5 and 2.0.0 of the esp library I get these errors:
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_open failed

In versions 2.1.0 - 2.3.0 of the esp library, I get these errors:
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

I've tried switching the tx and rx leads, I've tried versions 1.6.5-2.3.0 of the esp8266 library. I've also tried it on the other board that I ordered and got the same errors. Any ideas on what could be the problem?
EDIT: I've now tried it on a generic esp-01 board and am having the same issue

I had to install the SiLabs CP2104 drivers and reboot.
Make sure you don't have 2 connection (Arduino IDEs, VS Code with PlatformIO, ...) open. Also, I kept pressing the reset button the first time.

https://learn.adafruit.com/adafruit-feather-huzzah-esp8266/using-arduino-ide


Arduino calculator: I'm struggling to write a sketch which parses inputted characters I am attempting to make a calculator with arduino using a 16x2 Text-LCD and a 4x4 keypad. I've already programmed the part where the arduino board gets input from the keypad and displays characters on the LCD respectively, but I'm struggling to program the part where the '=' button is pressed and the arduino parses the sum and gives the answer. I'm not using the RW lin to read the LCD, instead I am adding characters pressed to a char[] variable. Can you guys please give me some code to parse the inputted characters? Thanks!

EDIT:
Code:

#include <LiquidCrystal.h>
#include <Key.h>
#include <Keypad.h>

char keys[4][4]={
  '/','x','-','+',
  '=','9','6','3',
  '0','8','5','2',
  'C','7','4','1'
};

byte rowPins[4]={7,6,5,4};
byte colPins[4]={3,2,1,0};

Keypad input=Keypad(makeKeymap(keys),rowPins,colPins,4,4);

LiquidCrystal lcd(8,9,10,11,12,13);
int inputSize=1;
char inputSum[16];

int cursorNum=0;

void setup() {
 lcd.begin(16,2);
}
void loop() {
  char key = input.getKey();
  if(key) {
    if(key == 'C') {
      lcd.clear();
    }else if(key == '=') {
      parseInput();
    }

    else{
    lcd.print(key);
    inputSum[cursorNum]=key;
    cursorNum++;
    }
  }
}

int result;
void parseInput() {
  //Parse code goes here

  lcd.setCursor(0,1);
  lcd.print(result);

}

Characters in a char[] variable may be encoded in ASCII or Unicode. You will want to convert them to numbers in this case. Consider subtracting the ascii value of one less than 0 from each char to get the number. Edit: @Matt informed me that 0 is the lowest ASCII number. As he suggested, you can subtract the character '0' from the digit to get the value. You want to specially handle any addition, division, or other operator symbols.

Then you can treat each number like a digit in a number. If you can break up the array of numbers by the operators, you can successively attach the operands to the operators. Keep in mind that each number to the left is a power of ten (assuming this is how it's implemented. This is called Endianess.)

If you post code I may be able to help further.


Measure movement distance - not sure what sensor? I want to measure the length of a step / stride -not sure what sensor to use.

I am trying to get several people to march a pattern for a band.  I am thinking a Arduino to beep when step is too short or too small.  Thinking the Arduino will be tied to their shoe laces.  IR or Ultrasonic do not seem to be the correct sensor to use.

Ideas?

The sensor to use is an accelerometer. The principle is easy: measure the acceleration, perform a double integration and you have the distance (after the first integration you have the velocity).

The problem is that, because of the double integration, small errors in the acceleration signal lead to big errors in the calculated distance. For example: an error e in the acceleration leads to an error e.t2 in the distance (where t stands for time). For this reason al sorts of filters are used often in combination with gyroscopes and/or gravity sensors. The signals from the gyroscopes and/or gravity sensors are used for the low frequency signals (long term) and te signals from the accelerometer(s) for the high frequency signals (short variations). That's why you find these sensors often combined in one package (for example the BNO055 form Robot Electronics https://robot-electronics.co.uk/bno055.html).

It is a complicated and highly mathematical area of science. In fact you want to do the same thing as fitness trackers do (and I think you are striving to a higher accuracy than they) - and there are not many that do really well.

P.S. Robot Electronics also sell a tilt compensated compass board with this BNO055 chip: the CMPS12 (https://robot-electronics.co.uk/cmps12-tilt-compensated-magnetic-compass.html). With this board you can read out absolute and relative positions straight away without any calculations.


ESP32 millis not working properly I have a program which measures temperatures every 30 minutes and sends them to a database. Immediately after running the program the first measurement is sent, however, the second (which should be sent after 30 min), is sent only after 1 hour. From then on the code works fine. The time is measured in millis. However, if I set the time difference to 28 minutes everything works fine from the beginning. What could be the reason for this? Is there a possibility that it goes to sleep mode? I don't understand why it works fine with 28 minutes and it stops working with 29 minutes?
Thanks in advance!
My code:
if (millis() - sendDataPrevMillis > 1740000)
  {
    sendDataPrevMillis = millis();

//other code

}

The only part I change, so it works is setting millis from 1740000 (29 minutes) to 1680000 (28 minutes).

Although not strictly required, maybe use parentheses around millis() - sendDataPrevMillis for readability;
I guess you will have initialised sendDataPrevMillis to 0 but
the first time you assign sendDataPrevMillis to millis() some time will have elapsed since you evaluated. So calling millis() twice will give different results. That makes it less easy to see what is going on.

Suggestion to try:
long HALFHOUR = 30 * 60 * 1000L;

if ( (millis() % HALFHOUR ) == 0L ) {
    //measure and send
    //....
}

Hope this helps.
NB: % is what is called the 'modulo operator' see: https://www.geeksforgeeks.org/modulo-operator-in-c-cpp-with-examples/


Serial.readString() not working becaue of outdated IDE? I've searched google honestly but can't find an answer nor changelogs for Arduino that might be the answer.

Basically I'm trying to use Serial.readString() to input commands to the Serial Monitor but it shows an error that readString is not a member of 'HardwareSerial'.

I am using Arduino 1.0 as IDE because the device I'm using (Aceduino) seems to have a custom IDE derived from 1.0 so I'm not sure if it will work with newer IDE versions. Wondering if that was what's causing the eror

Stream::readString() is available since version 1.0.1. See:

the changelog, and
the corresponding commit.


I cannot understand the relation between the air and the lenght: in the second example the response is 13 char but the lenght is 11. Why?

The hex numbers may be one or two digits long.  The way the values are being printed does not enable you to discern between 1 2 3, 12 3 and 1 23. Try this:

for(int i = 0; i < 255; i++)
{
  Serial.print(info.eir[i], HEX);
  Serial.print(" ");
}

(Someone already told you this.)

  How can I parse the eir to obtain all the data? For example the name of the device and the manufacturer data?

This works for the only example of the data you have given.  If I have guessed correctly how further data will follow, it'll work for them too.  (If I haven't, it won't.)  I have assumed that the name always starts in the same place, ends with a space, three bytes of stuff we don't care about, and that the data is groups of 8 bytes.  It's very likely that some of the other bytes give details of the data to follow, but with only one example and no spec, it's basically impossible to tell.

// Let's assume the sensor name always starts at element 5...
char *sensorName = &(info.eir[5]);
// ...and ends on a 0x20 (space) - which is probably a risky assumption
char *end = strchr(sensorName, ' ');
if (end)
{
    *end = '\0';
    // Sensor name is now in sensorName

    // Let's assume the data starts exactly 4 bytes after the end of the name
    uint8_t *dataItemStart = (uint8_t*)(end + 3);
    uint8_t *dataEnd = info.eir + info.eir_len - 1;
    while(dataItemStart < dataEnd)
    {
        // We have a data item here, as 'dataItemStart'.
        // You can get bytes within it using, for example
        //   dataItemStart[5]
        // to get the 6th item (the 00 or 02 in your examples)

        // Each data item is 8 bytes long, so the next one starts 8 bytes later
        dataItemStart += 8;
    }
}


Arithmetic types in Arduino I'm looking for a complete list of the arithmetic types in the Arduino framework.
On the Internet I found various incomplete lists: sometimes there is short, sometimes word, but other types are missing.

Could someone please provide an exhaustive list of the arithmetic data types in Arduino, including the C/C++ types and the Arduino-defined types (or aliases, e.g. the one created among others in Arduino.h with typedef uint8_t byte;) with a short description? If two types are identical please include both names in the list but making clear that they are the same.

The Arduino "language" is actually C/C++. GNU GCC and tool chain are used. The Arduino IDE uses a preprocessor to make it easier for beginners by removing some of the C/C++ requirements such as forward declaration of functions.

The GNU AVR GCC data types and representation, and the answer to your question can be found on the project Wiki page; https://gcc.gnu.org/wiki/avr-gcc

For C/C++ there are build-in data types but also a set of standards. One of the standard header files with data types is stdint.h. http://www.nongnu.org/avr-libc/user-manual/group__avr__stdint.html

Arduino.h and additional header files within the Arduino core libary contains the extensions or redefinitions made. The complete reference list; https://www.arduino.cc/en/Reference/HomePage

Cheers!


Temperature Controlled fan using arduino project regarding - LCD not displaying anything I have connected the circuit as per the diagram below and I have got the LCD to display boxes and nothing else. What could be wrong here? Please help!

Circuit diagram below -

Code as follows -

#include<DHT11.h>
#include<LiquidCrystal.h>
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
#define dht11pin 12
dht11 DHT11;
#define pwm 9
byte degree[8] =
{
  0b00011,
  0b00011,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000,
  0b00000
};
void setup()
{
  lcd.begin(16, 2);
  lcd.createChar(1, degree);
  lcd.clear();
  lcd.print("   Fan Speed  ");
  lcd.setCursor(0, 1);
  lcd.print("  Controlling ");
  delay(2000);
  analogWrite(pwm, 255);
  lcd.clear();
  lcd.print("Our Project ");
  delay(2000);
}

void loop()
{
  DHT11.read(dht11pin);
  int temp = DHT11.temperature;
  lcd.setCursor(0, 0);
  lcd.print("Temperature:");
  lcd.print(temp);
  lcd.write(1);
  lcd.print("C");
  lcd.setCursor(0, 1);
  if (temp < 26 )
  {
    analogWrite(9, 0);
    lcd.print("Fan OFF  ");
    delay(100);
  }
  else if (temp == 26)
  {
    analogWrite(pwm, 51);
    lcd.print("Fan Speed: 20%   ");
    delay(100);
  }
  else if (temp == 27)
  {
    analogWrite(pwm, 102);
    lcd.print("Fan Speed: 40%   ");
    delay(100);
  }
  else if (temp == 28)
  {
    analogWrite(pwm, 153);
    lcd.print("Fan Speed: 60%   ");
    delay(100);
  }
  else if (temp == 29)
  {
    analogWrite(pwm, 204);
    lcd.print("Fan Speed: 80%    ");
    delay(100);
  }
  else if (temp > 29)
  {
    analogWrite(pwm, 255);
    lcd.print("Fan Speed: 100%   ");
    delay(100);
  }
  delay(3000);
}

I used the default LiquidCrystal.h library for this project. Is that wrong?

Your constructor doesn't match your wiring:

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

You have:

RS = 7
E = 6
D4 = 5
D5 = 4
D6 = 3
D7 = 2

Yet your wiring has:

RS = 2
E = 3
D4 = 4
D5 = 5
D6 = 6
D7 = 7

I.e., completely backwards.

The constructor prototype is:

LiquidCrystal(rs, enable, d4, d5, d6, d7)

Yet you seem to have chosen to ignore (or misunderstand) that.

Instead you need to specify your pins correctly:

LiquidCrystal(2, 3, 4, 5, 6, 7);

Also, as a side note, you don't have a ground connection to that little 9V circuit off to one side - so you will never be able to control it.  Read this.


Arduino ide vs embedded C for Atmel AVR Is there any difference in the end product when coding the atmel avr using arduino ide and in embedded c are there advantages with embedded c?

Arduino IDE is a tool used to write and upload code to the Arduino. Embedded C (or C++) is a language or a subset of the language. The Arduino IDE is provided with, and runs the GNU g++ - a C++ compiler - so that is the language you would need to write in. If you're asking for a comparison between C++ and the mythical "Arduino language", there is no Arduino language - it is C++. The Arduino IDE does manage a few details of the language for you to make it somewhat more beginner-friendly. The difference between the full-spec C++ language and C++ with a few shortcuts you can take with it in the Arduino IDE are what have given rise to to the myth of an Arduino language.

(Technically it is possible to program an Arduino in another languages by using an appropriate language compiler for your Arduino's AVR chip.)

Your profile suggests you're planning a career around software and the technologies it enables. In that case, it would be very worth your while to learn and write correct C++ and ignore the Arduino IDE's shortcuts, at least once you have a passing familiarity with the process. The Arduino IDE is well suited to learners but it has some real shortcomings that soon frustrate the serious student/programmer/engineer - meaning sooner or later you'll probably want to move on to a more professional level tool that won't hold your hand for you, but also won't hold you back so much. That transition will be easier if you know the full language requirements from the start, than if you have to re-learn some of them later.

Update:

  Can you tell me how I should get started with using c++ with the Avr
  chip,and what software I need.

The only software tool you'll need is the Arduino IDE. It comes complete with the compilers, loaders, basic libraries, and sample programs. Despite my discussion of its shortcoming, I still recommend it as the easiest entry point for getting started. An Arduino Uno board is the only other thing you'd need and you'd be ready to go.

If you want to work with the bare chips, you'll need to provide the basic support circuitry that provides power, clock-pulse generator and USB to serial conversion. (This latter part is easy - it's called an FTDI cable and has the converter built into it). There are lots of articles on the web about home-building Arduino-compatible boards. You can make one on a printed circuit board, Vero board, a breadboard with plug-wires (instructive, but not too reliable because of all the plug-wires). Or one Arduino with a replaceable chip can be a programming host for all of your other (same part#!) chips. But note those chips will still need the support circuits to be able to do anything more than look pretty on your bench.


Connecting a switch and a MOSFET to an Arduino? I have an LED strip that I am trying to turn on with a magnetic switch when a door opens. I want the LEDs to fade on when I open the door and fade off when I close it, which is where the Arduino comes in. I am using PWM for the fading. I can get each component to work separately. The fading LEDs work with the MOSFET without the switch. I tested the switch with serial output on the Arduino and it works fading a single LED without the MOSFET.

I am using:

Arduino Uno R3
Magnetic Switch
N-Channel MOSFET IRLB3034
5 Meter White LED Strip
12VDC 30W Power Supply
10k Ohm Resistors

My setup looks like this:

Schematic:

Code (if it helps):

const int buttonPin = 2;     // the number of the switch pin
const int ledPin =  9;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the switch status
int brightness = 0;
int fadeAmount = 5;

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop(){
  // read the state of the switch value:
  buttonState = digitalRead(buttonPin);

  // check if the switch is ON.
  // if it is, the buttonState is LOW:
  if (buttonState == LOW) {
    // fade LED on:
    analogWrite(ledPin, brightness);
    if (brightness < 255) {
      brightness = brightness + fadeAmount;
    }
  }
  else {
    // fade LED off:
    analogWrite(ledPin, brightness);
    if (brightness > 0) {
      brightness = brightness - fadeAmount;
    }
  }
  delay(30);
}

I have a feeling the problem is with the common ground on the MOSFET and the switch. Any solutions/suggestions are appreciated.

I think you should keep the R2 resistor, but make it 1k and put before it a pull-down resistor of 10k so that any charges stored in the NMOS Cgate capacitance are discharged, whenever there is High-Z at the port D9. Also never forget the resistor limiting the diode forward current, which is typically 20 mA, but you should check that every time in datasheet. In case of LED strip there are usually internal resistors, but if you are using higher voltage still you need to restrict the current. Could you tell us more about why you are using PWM not a simple output port with an integrator for example and what you exactly observe and measure when you turn-on-off (fade-on-off) the LED?

simulate this circuit – Schematic created using CircuitLab

How to make the diagram a bit smaller?


serial is print twice? I have a problem , when send 1 or 0 by Bluetooth module the serial monitor print two time (RECEIVED SMS) . what's the wrong ?

This is my code  :

   char BluetoothData = 0 ;
void setup() {
  // initialize serial communication:
  Serial.begin(9600);
    for (int pin = 1; pin <= 13; pin++)
     {
       pinMode(pin, OUTPUT); // sets the digitals pin  as outputs
       digitalWrite(pin, LOW); // sets the digitals pin off defult intial states
     }
       Serial.println("ALL LEDs NOW OFF \n ");
       Serial.println("Please, Enter : ( 1 to Turn on All LEDs )  or ( 0 to Turn off LEDs ) \n");
}
void loop() {
  // read the sensor:
  if (Serial.available() > 0) {

        BluetoothData = Serial.read();
            Serial.print("*** RECEIVED SMS *** : ==>> ");
            Serial.println(BluetoothData);

        if (BluetoothData == '1'){
        for (int Pin = 1; Pin <= 13; Pin++) {
          digitalWrite(Pin, HIGH);
          }
          Serial.println("ALL LEDs NOW ON");
         }
        // turn all the LEDs off:
   else if (BluetoothData == '0') {
        for (int Pin = 1; Pin <= 13; Pin++) {
          digitalWrite(Pin, LOW);
          }
          Serial.println("ALL LEDs NOW OFF");
         }
  }
   delay(100);
}

This is photo for serial monitor

Probably the first time because you received the character '1' or '0'.
The second character is probably a '\0' or '\d', an end-of-string or end-of-line character.

You can easily check this by printing the value of each received character, like

Serial.println((int)(BluetoothData));

You probably see the value for '0' (48), '1' (49), end of string '0' of end of line '13' or maybe '10' (new line).


Is this class declaration wrong? " Declaration has no storage class or type specifier" error While trying to setup  an ESP32 as mqtt publisher I am getting strange errors. Here is my code:
#include "mqttSetup.h"
#include <WiFi.h>
#include <PubSubClient.h>

static byte httpFailCounter = 0;
byte counter = 0;

const char *ssid = "SSID";
// const char *password = "xxxxx";
const char *passphrase = "xxxxx";

WiFiClient espClient;

const char *mqtt_server = "192.168.1.39";
const int mqttPort = 1883;
const char *mqttUser = "xxxx";
const char *mqttPassword = "xxxxx";

PubSubClient pubClient(espClient);

pubClient.setServer(mqtt_server, mqttPort);

void checkConnection()
{
    if (WiFi.status() == WL_CONNECTED)
    {
        counter = 0; //reset counter
    }
    else if (WiFi.status() != WL_CONNECTED)
    {
        WiFi.begin(ssid, passphrase);
    }
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");

        counter++;
        if (counter >= 60)
        {
            ESP.restart();
        }
    }
}

void reconnect()
{

    while (!pubClient.connected())
    {
        Serial.print("Attempting MQTT connection...");
        // Create a random client ID
        const char *clientID = "ESP32D-MQTT";
        // Attempt to connect
        if (pubClient.connect(clientID))
        {
            Serial.println("connected");
            // Once connected, publish an announcement...
            pubClient.publish("outTopic", "Hello from ESP");
            // ... and resubscribe
            //   client.subscribe("inTopic");
        }
        else
        {
            Serial.print("failed, rc=");
            Serial.print(pubClient.state());
            Serial.println(" try again in 5 seconds");
            // Wait 5 seconds before retrying
            delay(5000);
        }
    }
}

I don't understand why the compiler is spitting out the following two errors:
this declaration has no storage class or type specifier (referring to my pubClient declaration)

expected a ';'

It doesn't have any issue when I declare the pubClient but at the line :
pubClient.setServer(mqtt_server, mqttPort);
where I use the pubClient it gives the error.
Besides I don't see any ; missing in the code.
Could you please help me figure out the source of error?

Header file for this code chunk
#ifndef MQTTSETUP_H
#define MQTTSETUP_H

void checkConnection();
void reconnect();

#endif

------------ Main sketch---------
#include <Arduino.h>
#include "Wire.h"
#include "tempSensor.h"
#include "mqttSetup.h"

void setup()
{
  Wire.begin();

  Serial.begin(115200);
  while (!Serial)
    ;

  shtBegin();
  checkConnection();
}

void loop()
{
  uint32_t newTime = millis();
  static uint32_t oldTime = 0;
  static uint32_t t2 = 0;

  float temp = 0.0;
  float humid = 0.0;

  char senVals[50];

  if (newTime - oldTime >= 10000)
  {
    oldTime = newTime;

    readsht(temp, humid);
    snprintf(senVals, 50, "Temp: %.2f Humid: %.2f", temp, humid);
    Serial.println(senVals);

  }
}

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

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


Extracting data from Arduino MultiWii Flight Controller I am new to the world of Arduinos but have a new project going with a MultiWii Flight controller. With the MultiWii comes a software for showing all data that is measured from the sensors (acceleration, velocity, roll, pitch, etc) which is nice but I would like to have/extract this data (call raw data or something) from all sensors (i.e. the data plotting everything, in numbers). Maybe it is the simplest thing to do, and I guess I have to set up some serial connection between the controller and tell it to send this data somehow but I do not know where to start so any guidance and help is appreciated.

Since you're new to Arduino, I'd suggest beginning with a basic interfacing arduino activity. Once you understand reading and writing digital and analog signals it's pretty much plain sailing from there. You may want to invest some time and a bit of cash in a beginners course on Udemy (try PEter Dalmaris' course https://www.udemy.com/arduino-sbs/) it's a good start. From there, talking to the MultiWii should be a piece of cake. Also, check out http://www.multiwii.com/connecting-elements


Can I connect a PWM pin on one Arduino to an analog input on another? I was considering several different ways to send simple data from one Arduino to another when I though, why not connect a PWN pin of one Arduino to the analog pin on another?  I could send simple messages for one to the other by setting different values on the PWM pin.  This seems like it would work, except for the fact the the PWM pins mimic voltages with pulses.

Is this a reliable way to link two Arduinos, If I only want to communicate 4 states?  Also, will I need to include some additional components in the connection (resister, capacitor, etc.)

All it needs to do is send a 2v pulse for yes and a 5 v pulse for no. It needs to do this about 6 times an hour.

Yes, you can do this with "a little programming"  or more easily by adding two cheap components.

If you connect a say 47k resistor from PWM_Out to Analog_In and a say 100 uF capacitor from Anaolg_In to ground you will be able to read the equivalent analog value to an accuracy of around 1%. Read it N times (maybe 10 times) with a delay of say 12 ms between reads and average it for a better result. This works because the PWM period is about 1 mS so delaying for a period of multiple cycles but not an exact multiple means you sample semi randomly.

For the sort of resolution that you want (4 levels) a MUCH smaller capacitor could be used (maybe 1 uF.) But even a 100 uF capacitor is cheap.

You could instead use PWM out (analogWrite) and a digitalRead.
Perform say 100 digital reads with say 12 ms between reads (so about 1.2 seconds total) and keep two counts - PinWasHigh and PinWasLow for (obviously) high or low conditions. The contents of PinWasHigh tells you what % of reads was high. Due to random sampling you cannot rely on this for 100 levels but determining say 10 levels should give good accuracy. The sum of PinWasHigh and PinWasLow should total 100 as a sanity check.

While use of a serial port (hardware or software) or SPI allows more data transfer per time and without much effort, this simple analog method is good enough for many applications.


Move robot through the waypoints My arduino robot has two dc motors as two wheels and have mounted an IR led on it. I get current position of the robot as (x,y) coordinates in the arena using camera which is mounted at the top of the arena..

My robot communicates with PC through bluetooth. I can read current position of robot on pc with the help of camera. Robot uses arduino motor shield to drive DC motors.

Which is the best method to move robot through the waypoints for a robot with DC motors without encoders?

With the arrangement you have described I would say it's very very hard to do what you want.

You know where the robot is
You know where the robot has to get to
You can easily calculate the direction the robot has to go in (simple trigonometry from school)

But:

You don't know what direction the robot is facing, so you don't know how to turn the robot to get it to drive in the direction you need.

So either you need some kind of calibration procedure whereby the computer moves the robot in different directions and watches what the IR LED does to determine what direction the robot is facing so it can move it to face the right way (tricky to do, and rather messy), or some way for the computer to visually calculate the direction of the robot.

The latter is probably the easiest.  Instead of just one IR LED on the top of the robot you would need an array of IR LEDs on top of the robot forming a shape.  What that shape is can be up to you, but there is one big constraint: It must have a clear direction to it (i.e., it must have no rotational symmetry.  Triangles are good since they only need 3 LEDs.  An equilateral triangle though wouldn't work since in three different rotations it would look the same.  However, a single LED at the front of the robot, with two LEDs at the back of the robot, with the two back LEDs closer together than the distance from the front to the back, would not have any rotational symmetry.

You could then, (theoretically, assuming you have control over the camera software), get the three points from the play area and calculate the direction the robot is facing (tangent from mid-way between the two close points passing through the distant point) so you can then calculate the angle the robot would need to turn through so it is facing the direction you need it to.

Remember in math class, doing trigonometry (sin, cos, tan, pythagoras, etc) thinking "Why the hell do we need to know this stuff?!", well, now you know.


ESP8266 with Arduino Uno and HTTP POST Im currently new on this and sucessfully made a sound-activated alarm with Arduino Uno and a microphone sensor. (If sound is detected, then it will alarm). Now, I am adding a ESP 8266 module into it so it can perform a HTTP GET or POST to IFTT Maker link.

My problem with it is how can I program the esp with arduino uno? Do I do something like this

  https://github.com/bportaluri/WiFiEsp/blob/master/examples/WebClient/WebClient.ino

(and add the threshold for the microphone sensor, buzzers and LEDs)??

Thanks for helping

Yes, the library

https://github.com/bportaluri/WiFiEsp

Is suited for your task because it implements talking to a ESP8266 over a software serial. On this serial connection, AT+ commands will be sent. This also means that you must have the AT firmware flashed onto your ESP-01.

If that is not the case you can download the binary image here and flash it with a serial adapter, as instructed with the tools on that page. You can check whether your ESP8266 has the firmware flashed by attach a UART adpater to the TX output. It should print a "ready" on bootup.

For your wire-up, you will just have to add VCC (+3.3V), GND, TX and RX connections to the ESP-01 board, preferable with a big capacitor between VCC and GND, as the ESP8266 draws a lot of power when sending data over WiFi.


problem using GSM shield and GPS shield in one Arduino UNO R3 i try to program use the GSM shield Arduino with Arduino UNO i did it successfully but after that i try to use GPS shield but when i add the #include  for the program i got the error

#include <GSM.h>
#include <TinyGPS.h>
#include <SoftwareSerial.h> // when i add that one i got the output eroor
// PIN Number for the SIM
#define PINNUMBER ""

i got this error out put

Arduino: 1.6.6 (Mac OS X), Board: "Arduino/Genuino Uno"

libraries/SoftwareSerial/SoftwareSerial.cpp.o: In function `__vector_3':
/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/SoftwareSerial.cpp:227: multiple definition of `__vector_3'
libraries/GSM/GSM3SoftSerial.cpp.o:/Applications/Arduino.app/Contents/Java/libraries/GSM/src/GSM3SoftSerial.cpp:499: first defined here
libraries/SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::read()':
/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/SoftwareSerial.cpp:392: multiple definition of `__vector_4'
libraries/GSM/GSM3SoftSerial.cpp.o:/Applications/Arduino.app/Contents/Java/libraries/GSM/src/GSM3SoftSerial.cpp:487: first defined here
libraries/SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::read()':
/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/SoftwareSerial.cpp:392: multiple definition of `__vector_5'
libraries/GSM/GSM3SoftSerial.cpp.o:/Applications/Arduino.app/Contents/Java/libraries/GSM/src/GSM3SoftSerial.cpp:487: first defined here
collect2: error: ld returned 1 exit status
exit status 1
Error compiling.

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

It appears the GSM library has its own conflicting copy of SoftwareSerial, and not necessarily a matching version unless you're lucky.

Not sure how well this would work but you can try removing the library reference to SoftwareSerial, and fiddle about to use the GSM library's SoftwareSerial.