why are there odd spikes in the USB serial data transfer rates? I'm trying to use an Arduino for data collection, and hoping to get a consistent sampling rate.

I looked into the serial communication using the simplest program I could, but it produces odd results.

void setup() { Serial.begin(9600); }
void loop() { Serial.println("00000"); }

I use a python script to read the data and create a text file and write the time in seconds before the five zeros.

Using the seconds as a marker, I then count the number of data lines for each second.  for example:

44 00000  // recorded at time 44 seconds
44 00000
44 00000
45 00000  // recorded at time 45 seconds, etc

I was expecting that there would be a somewhat stable value for this.  Using 10 bits per character, printing the 5 zeros should be able to be done about 190 times per second.  When analyzed, it turns out to be lower, which isn't surprising due to overhead, but also unexpectedly variable.

Collecting the zeros for 5000 seconds produced the following results:
most often, there were 137 sets of 00000 collected per second, followed by 138 sets of 00000.  This is easily explainable by not being equally spaced per second, and having one second with 137 followed by one second with 138.

What is harder to explain is when it jumps to 139, 140, 141 and 142 sets of 00000 per second.

Out of the 5000 seconds of data, there were 25 seconds where 140 sets of 00000 were created.  That isn't too bad and could be due to timing.

But, out of the 5000 seconds, there were 203 seconds where 142 sets of 00000 were created.

The percent breakdown is as follows:

137 sets of 00000:  79.15%
138 sets of 00000:  13.8%
139 sets of 00000:  0.39%
140 sets of 00000:  0.51%
141 sets of 00000:  2.05%
142 sets of 00000:  4.11%

the first 4 could be explainable with minor timing errors, the last ones are very hard to explain.  with 137 sets of 00000 there are 685 characters sent serially in one second.

with 142 sets of 00000 there are 710 characters sent serially in one second.

What I am trying to figure out is why the variability is so wide and also so consistent - as in the pattern, which can be seen in the graph.

Is there any explanation for the variability?

Because of the variability in the transfer, it is very hard to sync up data or filters or other uses when a constant sample rate is needed.

I've also added delays in the main loop from 1ms to 7ms, 7ms was the maximum because that would not cause the loop to run slower than the free running speed at 142 loops/transmissions per second (1sec/7ms = 142.8 loops per second discounting all other overhead) and found the same patterns.

Using a delay of 8ms produced another interesting result:
with a delay of 8ms, most of the data was transmitted at 123 or 124 sets of 00000 per second, but every 12 seconds there would be a burst of 128 sets of characters.  this makes sense because the delays add up to less than one second for 11 loops, then get an extra loop for that second, but that adds 15 characters, not just 5.

After re-reading this, it dawned on me that there might be some loop timing/buffering errors, so instead of a delay, I used Serial.flush() to pause the loop until the data was sent.

This resulted in a free-running result of 137 sets transmitted per second for the most common, followed by 138 sets.  The new issue is that every 25 seconds there is a drop down to 133 sets of characters transmitted per second, which seems to be the same issue only causing slowing instead of speeding up.

I thought I found the answer with Serial.flush() but there is still something causing huge changes in the sent characters per second.  What could be causing this? and what can be done to make the transfer rates more constant?

While a serial port "kept busy" can potentially produce data with jitter comparable to its clock's jitter reduced by the number of clocks per word, a USB serial converter introduces a bunching of data into packets that is effectively entirely asynchronous.

As a result, once the data has gone through the USB, you really can't determine much of anything about the timing of its origin just by looking at the timing of its arrival.  That remains true even if you are claiming it via a serial-type API on the host, because the USB bus has already irreversibly de-synchronized it in transit.

A more meaningful experiment would be to timestamp the data at the source, ie, on the Arduino.  That could potentially be more regular, but if you use a high enough resolution timestamp, you will still find that it is irregular, as by default the Arduino's foreground thread of execution is periodically interrupted by the timer, which produces a brief delay.

If you are sending serial data into the Arduino or using other hardware peripherals, those may cause additional sporadic delay-inducing interrupts.


LED staying on after first relay trigger I seem to have a strange issue with a simple circuit involving a relay.

The problem is that the relay appears to work absolutely fine (judging from the onboard led) but the the led stays on after the first pull up on the relay.

It doesn't turn off and match the onboard relay led. I'm sure it's something minor but I can't seem to spot the problem.

I've attached a video and the code below. Thanks in advance

video

#include <Arduino.h>
int Relay = 3;

void setup()
{
  pinMode(Relay, OUTPUT);     //Set Pin3 as output
}
void loop()
{
          digitalWrite(Relay, HIGH);   //Turn off relay
          delay(2000);
          digitalWrite(Relay, LOW);    //Turn on relay
          delay(2000);
}

If using a solid state relay, consider such a device may rely on driving a load using AC rather than DC.  That is, the solid state relay my not turn off until a zero crossing occurs.  Solid state relays intended to switch DC driven loads are normally designed using MOSFET switches.  Solid state relays intended to switch AC driven loads are normally designed using SRC or TRIAC switches.  Read more about this here.


Serial Communication When I send data using

Serial.println()

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

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

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

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

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

Serial.print(123);

Now, you have to understand that the Arduino paradigm is to make programming simple.  So the print method in the Serial class will assume you want to see the characters "123" on the terminal.  So, guessing, the print method will convert each decimal number into an ASCII character and print them out as 3 values to the terminal.  That is, the ASCII value for 1, followed by the ASCII value for 2 finally followed by the ASCII value for 3.

If this is not what you want there are other variations for the print method in the Arduino Serial class.  But all tend to print using ASCII codes.

If you want to print out the binary values, see the Serial.write() method.  This method will send the value of the argument to the terminal with out converting into ASCII code.

Example: If you want to print "1" on most terminals you can use the Serial class method write:

Serial.write(49);

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


Detecting how many button presses(single tap, double tap etc) with two simultaneous buttons noob here

So what I am trying to do is output a different number depending on the number of button presses e.g. for 1 button press it should output 1 and so forth. After that I only really want the outputs for 1 to 4 presses. I am using these inputs for a game.  Right now, it does work and counts up until 4 and then resets back to 0. The problem that I am having is it continues after 1 click to 2 clicks; what I want it to do is count 1 click when its clicked once, twice when its clicked twice etc. I am trying to use a debouncing code to distinguish between single tap, double tap, triple tap etc
@VE7JRO kindly provided a great solution to this problem, albeit it was for one button. I am trying to adjust the code to accommodate 2 separate buttons (on separate pins), but it is giving me an error.

This is the code:

#include <Bounce2.h>

// Connect both buttons in series with one connection
// to GND and the other to a digital pin.
const int buttonPin1 = 2;
const int buttonPin2 = 3;

class Button
{
  private:

    int m_buttonPin1;
    int m_buttonPin2;
    int m_counter;
    unsigned long m_buttonPressTimeout;
    unsigned long m_previousMillis;

  public:

    Button(int button):
      m_buttonPin1(buttonPin1),
      m_buttonPin2(buttonPin2),
      m_counter(0),
      m_buttonPressTimeout(1500), // Button press timeout 500 ms.
      m_previousMillis(0){}

    void Update()
    {
      int valA = digitalRead(button1); // read button stateint
      int  valB = digitalRead(button2); // read button state
       if (valA == LOW &&valB == LOW)
       {
      if(m_counter > 0 && millis() - m_previousMillis >= m_buttonPressTimeout)
      {
        Serial.print("Count from Update() just before it's re-set to 0 = ");
        Serial.println(GetCounter());
        m_counter = 0;
      }
    }

    void IncrementCounter(){
      m_counter++;
      if(m_counter > 4){m_counter = 4;}
      if(m_counter == 1){
        m_previousMillis = millis();
      }
    }

    byte GetCounter(){
      return m_counter;
    }

};

Bounce button1Debouncer = Bounce();
Bounce button2Debouncer = Bounce();
Button MyButton(buttonPin1);
Button MyButton(buttonPin2);

void setup(){

  Serial.begin(9600);

  pinMode(buttonPin1, INPUT_PULLUP);
  button1Debouncer.attach(buttonPin);
  button1Debouncer.interval(5);
  pinMode(buttonPin2, INPUT_PULLUP);
  button2Debouncer.attach(buttonPin);
  button2Debouncer.interval(5);

}

void loop(){

  // Call the Update function as fast as possible.
  MyButton.Update();

  // Button pressed.
  if(button1Debouncer.update() && button2Debouncer.update())
  {
    if(button1Debouncer.fell() && button2Debouncer.fell()){
      MyButton.IncrementCounter();
      Serial.print("Count from Button Debouncer = ");
      Serial.println(MyButton.GetCounter());
    }
  }

}
}

The error is: "'buttonPin1' is not a type", I do not understand this error as it didn't give that error for when a single button was used.

You SHOULD pay attention to the following issues:

1. Floating input problem:

Symptom: the reading value from the input pin is not matched with the button's pressing state.

Cause: input pin is NOT used pull-up or pull-down resistor.

Solution: Use pull-up or pull-down resistor. See Arduino Button (with pull-up/pull-down)

2. Chattering phenomenon

It should be considered in only some application that needs to detect exactly number of the pressing.

Symptom: Button is pressed one, but Arduino code detects several times.

Cause: Due to mechanical and physical issues, the state of the button (or switch) is quickly toggled between LOW and HIGH several times

Solution: Debounce. See Arduino Button Debounce


Arduino MIDI Program Change to Voodoo Labs GCX Converter To define the problem, the L6 Helix can generate 6 immediate MIDI messages. These messages are pretty flexible as to what you want, but the Voodoo Labs GCX needs at least 8 CC messages to properly configure it worst case. Also, I don't want to burn all of my immediate commands to control most of the GCX. So I had the idea to create a Arduino project that would take MIDI PC and MIDI Bank Select to produce a 8 bit value which I could then convert into 8 CC messages between CC#80 and CC#87.

To solve this problem I used an Arduino UNO and a Olimex MIDI shield. I also want to use MIDI PC messages and Bank Selects.

For reference:

A Channel 16 PC 77 with Bank select 0 converts to binary 0x4D => Binary 01001101
A Channel 16 PC 77 with Bank Select 1 converts to binary 0xCD => Binary 11001101

Just to point out, the Bank Select value basically controls bit 8 and the PC value represents bits 6 down to 0

Based on the binary output, I scroll through bits 0 to 7 and send messages on CC 80 to CC 87. If a bit is a 1, I turn the loop on by setting the corresponding CC value to 127 and if it is a zero, I set the CC value to 0.

The Helix can generate a Bank Select and PC as one message, so for the price of one message, this project will make me 8 CC#'s effectively. ;)

It should allow other messages through, with the Arduino's SW loop latency. There maybe some other side effects to, but those should be limited to channel 16 only.

I have tested this on a Arduino UNO board with an Olimex MIDI Shield.

// GCX Editor
// By Rich Maes
// Converts MIDI PC's on channel 16 to GCX CC's starting at 0x80
// Allows everything else to pass.

#define MIDI_PC_CH16 0xCF
#define MIDI_CC_CH16 0xBF
#define MIDI_SYSEX 0xF0
#define MIDI_SYSRT_CLK 0xF8

boolean byteReady;
boolean sendCCMessage;
int ccMsgsToSend;
unsigned char midiByte;
unsigned char capturePCByte;
unsigned char captureCCByte;

// Queue Logic for storing messages
int headQ = 0;
int tailQ = 0;
unsigned char tx_queue[128];

int getQDepth();
void addQueue(unsigned char myByte);
void addCCQueue(unsigned char captureCCByte, unsigned char capturePCByte);
unsigned char deQueue();

static enum {
    STATE_UNKNOWN,
    STATE_1PARAM,
    STATE_1PARAM_CONTINUE,
    STATE_2PARAM_1,
    STATE_2PARAM_2,
    STATE_2PARAM_1_CONTINUE,
    STATE_PASSTHRU
  } state = STATE_UNKNOWN;

void setup() {
  // put your setup code here, to run once:
  //  Set MIDI baud rate:
  Serial.begin(31250);
  sendCCMessage = false;
  byteReady = false;
  midiByte = 0x00;
  state = STATE_UNKNOWN;
  captureCCByte = 0;
  capturePCByte = 0;
  ccMsgsToSend = 0;
}

int getQDepth() {
int depth = 0;
    if (headQ < tailQ) {
        depth = 128 - (tailQ - headQ);
    } else {
        depth = headQ - tailQ;
    }
    return depth;
}

void addQueue (unsigned char myByte) {
    int depth = 0;
    depth = getQDepth();

    if (depth < 126) {
        tx_queue[headQ] = myByte;
        headQ++;
        headQ = headQ % 128; // Always keep the headQ limited between 0 and 127
    }
}

void addCCQueue(unsigned char myCaptureCCByte, unsigned char myCapturePCByte) {
    int i;
    if (getQDepth() < 80) {
        // There is enough space to add our CC messages
        for (i = 0; i < 8; i++) {
            addQueue(0xBF);
            addQueue(80 + i);
            addQueue(127 * ((((myCaptureCCByte * 128) + myCapturePCByte) >> i) % 2));
        }
    } else {
        // This is an error condition.  So reset the queue and pointers
        headQ = 0;
        tailQ = 0;
        byteReady = false;
        for (i = 0; i < 128; i++) {
            tx_queue[i] = 0;
        }
    }
}

unsigned char deQueue() {
    unsigned char myByte;
    myByte = tx_queue[tailQ];
    tailQ++;
    tailQ = tailQ % 128;  // Keep this tailQ contained within a limit
    // Now that we dequeed the byte, it must be sent.
    return myByte;
}

void loop() {
    if (byteReady) {
        if (midiByte >= 0xF0) {
            // This automatically passes all clocks and System Realtime Messages
            state = STATE_PASSTHRU;
        } else if (midiByte >= 0x80) {
            switch (midiByte) {
            case MIDI_PC_CH16:
                state = STATE_1PARAM;
                break;
            case MIDI_CC_CH16:
                state = STATE_2PARAM_1;
                break;
            default:
                state = STATE_PASSTHRU;
                break;
            }
        }  else {
            switch (state) {
            case  STATE_1PARAM:
                capturePCByte = midiByte;
                state = STATE_1PARAM_CONTINUE;
                addCCQueue(captureCCByte, capturePCByte);
                break;
            case STATE_2PARAM_1:
                if (midiByte == 32) state = STATE_2PARAM_2;
                else state = STATE_2PARAM_1_CONTINUE;
                break;
            case STATE_2PARAM_2:
                state = STATE_2PARAM_1_CONTINUE;
                captureCCByte = midiByte;
                break;
            default:
                state = STATE_PASSTHRU;
                break;
            }
        }
    }

    if ((state == STATE_PASSTHRU) && byteReady) {
        // Just pass messages unaltered.  Also don't let any of our modified message through if
        // we are passing though.  Our burst of modified CC# can wait.
        // Serial.write(midiByte);
        addQueue(midiByte);
        // state = STATE_UNKNOWN;
    }
    byteReady = false;

    if (getQDepth() > 0) {
        // We have a byte to send, dequeu and send it
        Serial.write(deQueue());
    }
}

// The little function that gets called each time loop is called.
// This is automated somwhere in the Arduino code.
void serialEvent() {
  if (Serial.available()) {
    // get the new byte:
    midiByte = (unsigned char)Serial.read();
    byteReady = true;
  }
}


Why SD.exists() only looks for inside media/realroot on Intel's Galileo? I'm following a tutorial which says SD.exists() only look for files inside media/realroot on Intel's Galileo board. I just confirmed this using SSH to create e remove files during a loop which was looking for some specific named file. Where's information about this? I searched for cpp files inside SD library and found nothing.

The Intel Galileo runs Linux.  Most Linux distributions (auto) mounts media under specific directories like "/media".  So this is likely not so much a feature of the Arduino paradigm but of the Linux paradigm.  If you really want to change this you will probably have to research how Linux (specifically how the Intel Galileo version of Linux) auto mounts media.

This is a stack exchange question about auto-mounting using a Linux distribution called Ubuntu.  I am not sure how close the Intel Galileo Linux is to Ubuntu.  But it's a starting point.


Location of examples folder in Ubuntu I'm trying to add some additional example files to the Arduino IDE in Ubuntu 14.04. However, I can't for the life of me find where the examples are stored in my system. I checked the Arduino website, but can't find any information there. Does anyone know where I need to put my additional files?

EDIT: I found the location at /usr/share/arduino/examples

After some more searching I found it in /usr/share/arduino/examples.


AVR & PIC 8-bit Microcontrollers - Can you add: external flash memory, external RAM, video & audio output, more address busses? so I was planning on creating a mini PC out of basic ICs and 8-bit microcontrollers such as ATTinys and/or PICs and I have several questions regarding those:

Can you add external RAM, say with SRAM, DRAM chips, so the microcontroller can handle larger programs? (ones requiring more memory to be executed). I've seen an excellent discussion here: External Flash Memory for ATtiny85, which exclaims that I can't do that with AVRs (but why exactly is that? What about PICs, or any 8-bit uCs for that matter).
Can you add external memory, like flash or EEPROM, so that the microcontroller can store some files (sort of a hard drive (but more like an SSD I guess).
Also, how would you go around connecting memory chips together to get more memory out of them? Would there be a difference with memory chips like serial flash and parallel flash?
Can you use them to output and create basic audio & output HDMI? (or communicate with external ICs to do that task)
Can you somehow connect say 2 8-bit ATTinys to get a pseudo 16-bit microcontroller? Would that mean they could process more data at the same time?

Thanks,
some guy on the internet.

Yes, you can connect external RAM chips through the typical interfaces (mainly SPI or I2C). But you cannot execute code from it. The microcontroller is an IC, meaning Integrated Circuit. It is hard wired internally to execute from internal flash. You cannot change that. That is valid for every microcontroller, that executes from internal flash (which is somewhat a definition of a microcontroller). A processor - in contrast- like in a computer, is build to execute code from elsewhere.

If your code, that you want to store externally, isn't that complex, you could save the code there as an own (most likely binary) data format and write code for the microcontroller, that takes that data and executes corresponding functions. So basically an interpreter. Though on the small microcontrollers only code for rather small functionality will fit.
Yes, you can add external storage. Which storage depends on many factors. You can by external flash or EEPROM chips, just like external RAM chips. Common storage devices for microcontrollers are SD cards, because they can easily interfaces via SPI. You can even have a file system there (though the size is somewhat limited by the available RAM of your microcontroller, because it needs to load the file table). Maybe you can even connect an SSD, but you will have to look, if you can set up the corresponding interface for it. A microcontroller does not have SATA interfaces or similar. And adding extra chips for these leaves you fastly with interfacing chips, that are way more capable as the main chip itself (see Wifi and the ESPs: You could add Wifi to an Arduino Uno project with it, but the ESP is way more capable, than the Uno). Then you would need to ask yourself, it this is really a good idea.
I think most memory chips (whichever kind) are not daisy chainable. Mostly they use a Single-Master-Multiple-Slaves interface like SPI. You could connect multiple memory chips to the SPI bus and communicate sequentially with them. The difference between parallel and serial flash chips is their communication interface. Serial can be something like SPI. Parallel communication will send multiple bits at once over the corresponding amount of wires (mostly 8, means 1 byte). Here you need the corresponding number of free pins on your microcontroller. Though parallel interfacing is often not advisable. Especially the small microcontrollers are too slow, to profit from the faster interface. And instead of using at least 9 pins, you could also use 3 for SPI and get the same transmission speed in the end.
Yes, they can. Though it really depends on the used microcontroller and the project topology. When using something like the DFmini player, any microcontroller can play audio (from files on a micro SD card in the player). When the microcontroller should play sounds itself, you can get very different results, depending on the chip capabilities. An ESP32 for example has a dedicated I2S interface, which is build for transmitting sound to an output device.

About video: AVR based microcontrollers (or similar PICs) cannot really handle video. For example: The most, that you can get out of an Arduino Uno (Atmega328p) is a very very limited VGA signal (very small resolution, only a few colors). HDMI is out of range for any of them. Surely you would want to draw on the screen, that is connected to the HDMI interface, to build up a visual interface. I think, that is just not possible with such small microcontrollers. They are not meant for this. Though you might find some very specialized chip, that you could use in such a way. If, that chip would be way more expensive as buying multiple Raspberry Pis.
No, just as 2 32-bit computers do not make 1 64-bit computer. That is just not, how everything works. Each microcontroller can still only process 8 bit at a time out of it's own memory. Depending on the task, you may try to give them different tasks. That would give you more computation power in theory, but it's not the same as a 16-bit controller.

I assume, that you are doing this for fun or for the grind, so I will not say, that you should buy a Raspberry Pi. Though I think, you might look into the wrong way. You cannot make a truck out of parts for a mini, though many of the components work in a similar way. To get all the difficult functionality (audio, video, big storage, ...) out of your self build computer, you need to use computer parts, not microcontroller parts.

If you are happy with much less capabilities, many people in the past have build their own computers out of more basic parts as microcontrollers (down to the big range of logic gates). Microcontrollers live in the world between computers and basic logic components. They are too integrated for extending their capabilities much.


How to stop extra LEDs from lighting in LED cube So I build LED cubes and the way I have it programmed is I use an analog pin for the ground layers and set them to high when i want an led on that layer lit up. So lets say I wanted the following LEDs lit

But in reality the LEDs light up in all the layers that are set to high obviously so this is what actually ends up lighting

What should I incorporate in order to avoid this happening. I am using an Arduino Nano, do I need to edit my code or is it hardware?

Your circuit design has to be used with multiplexing. Multiplexing introduces flicker. Since you seem to be wanting to move the grid of LEDs rapidly that flicker will translate into a very undesirable effect.

So you have a number of choices:

Re-design your system so that you don't use multiplexing. With each LED directly driven you get zero flicker, but you end up with as many wires and GPIO pins needed as you have LEDs (although shift registers could be used to move the bulk of the wiring closer to the LEDs). That's impractical.
Use multiplexing but have the frequency so high that flickering is no longer noticeable. We're talking thousands or millions of loops per second to keep it looking smooth (depending on how fast you are spinning the grid). You would need a high speed multiplex driver chip for this.
Time your multiplexing to the spinning of the grid.

The third option relies on quite a high rate of spin, since your multiplexing increments one column or row for each revolution. With 5 columns to work through it would take 5 revolutions to work through the entire grid.

You need some way of identifying the start of each revolution (e.g., a hall-effect sensor), and each time you start a new revolution you illuminate just one column of LEDs. The faster you spin the smoother the effect will be.

If you want to have LEDs on or off for just part of the revolution it's then down to you to work out when to turn them on or off for that one specific column. That's when the fun really begins.


Run HEX program from SD with another program I want to write a program in which I can select a HEX file recorded on a SD card (via a LED screen, etc.) and run it, i.e. transfer control to it, like launching programs on a PC. Is this possible and if so, how? I only found ways to directly run a sketch from an SD card without that "program"

Not with an Uno, no, it's not possible. Or it's very very hard and the results would be less than desirable. You need a proper MCU with lots of RAM and the ability to run code from it, which you can't with an Uno.
It would be less work to write your own scripting language to control things from a text file.


Adafruit Neopixel Library- only the first 16 LEDs respond I am using Adafruit Neopixel Library to work with a strand of 21 RGB LEDs.
AT this point only the first 16 light up. It is not a soldering problem, battery issue or a short.
This troubleshooting page suggests to

  "confirm that the number of LEDs in the LPD8806() constructor match the
  number of LEDs in the strip (both will be 32 if using the strandtest
  example and a single meter of LEDs)."

But looking at the library code below, I am not certain where to modify. Adafruit_Neopixel master zip has 2 files, which contain source code. One is Adafruit_Neopixel.cpp and the other Adafruit_Neopixel.h.

Thank you.

When something works, but not completely, it's often due to power issues.

Embedded things, microcontrollers/Arduino are fairly robust and "logical".
Hence, if your Arduino program works today, it'll work tomorrow.

Analog devices, or electricity is (in my eyes) often a bit vague. A chip can get enough power to run, but not enough to work properly.

The NeoPixel

Adafruit has an extremely elaborated tutorial/userguide.

  Powering the NeoPixels

This also seems to fit your problem.

You could try powering the strip from the middle.
Since your voltage isn't stable, your amperage might not be as high and the resistance may be a little big. It's actually quite impressive that it works.

  Each NeoPixel can draw up to 60 milliamps at full brightness.

2000mAh does not mean it can (always) deliver 2000mA. It depends on the "C" or discharge rating of the battery. So if your battery is rated 0.5 C it'll only be able to supply 1000mA (for 2 hours).

60*21 would be well over 1000mA, actually 60*16 is just below 1mA, so this would fit your problem.

  The voltage of a battery depends on how much charge it has.

Check google for: "LiPo voltage drop"

  If all else fails

There is a chance that that particular LED is broken. The signal will not continue to the other LED's and thus the light of the strip will end there.
Try to drive the LED's behind the LED that fails. (With the power supply closer).

I'm also not sure if you can supply 3.7V and then use 5V logic. Things like that would often break a microcontroller (when running on 3.3V, you usually can't receive 5V?)


Arduino Serial Communication Between 2 Uno I'm trying to get two arduino uno to communicate. The slave reads a temp sensor as an analog value, then converts it to degrees C, then sends that value to the master, the master then prints the value to the serial monitor. This is the code I have thus far.

for the slave

const int tempPin = A0;

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

  void loop() {

   //read sensor data to a variable
   float volt = analogRead(tempPin) * 0.004882814;
   float degC = (volt - 0.5) * 100.0;
   Serial.println(degC);

   delay(2000); //Not to flood serial port
  }

this is the code for the master

float tempC;
void setup(){
  Serial.begin(9600);
  delay(2000);
 }

  void loop() {
 /**  check if data has been sent from the computer: */
 while (Serial.available()) {
 /* read the most recent byte */
    tempC = Serial.read();     //now byteRead will have latest sensor
                              // data sent from Arduino1

    Serial.println(tempC);
  }
}

My issue is that I am reading on the serial monitor 4 different 2 integer values

Your slave is sending an array of characters and your master is reading the ASCII values of those characters.

If you send 25.43, Serial.println will send 7 characters 2, 5, ., 4, 3, carriage return and a newline.

The master will read them as 50, 53, 46, 52, 51, 13 and 10. Your code then prints:

50.00
53.00
46.00
52.00
51.00
13.00
10.00

On your master, the loop() should look like:

void loop() {
  if (Serial.available()) {
    char c = Serial.peek(); // just look at the next character on the serial buffer
    if (c == '\r' || c == '\n') // ignore the carriage return and newline characters
      Serial.read(); // remove the character from serial buffer by reading it
    else {
      tempC = Serial.parseFloat(); // read and parse the string representing the float value
      Serial.println(tempC);
    }
  }
}


Why is this variable giving me always the value of 0? I am doing a project and here is the code that I am using, but I do not know why the values of duration and sofia is always 0 so the values of distance and monroy are also 0

const int trigPin = 9;
const int echoPin = 10;

const int t = 8;
const int e = 7;

long duration, sofia;
int distance, monroy;
void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  pinMode(t, OUTPUT);
  pinMode (e, INPUT);
  Serial.begin(9600); // Starts the serial communication
}
void loop() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  digitalWrite (t, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  digitalWrite (t, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  digitalWrite (t, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  sofia = pulseIn(e, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2;
  monroy = sofia * 0.034 / 2;
  Serial.print(duration);
  if (distance = 15);
  {
    digitalWrite (3, HIGH);
    delay (5000);
    digitalWrite (3, LOW);
  }

  if ((monroy >= 0) && (monroy <= 5));
  {
    digitalWrite (4, HIGH);
    digitalWrite (5, LOW);
    digitalWrite (6, LOW);
  }
  if ((monroy >= 5.1) && (monroy <= 9));
  {

    digitalWrite (5, HIGH);
    digitalWrite (6, LOW);
  }
  if (monroy >= 9.1);
  {

    digitalWrite (5, LOW);
    digitalWrite (6, HIGH);
  }
}

When I formatted your code for readability and then compiled it I got these warnings:

/tmp/arduino_modified_sketch_71221/sketch_may02a.ino: In function 'void loop()':
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:34:20: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
   if (distance = 15);
                    ^
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:34:21: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
   if (distance = 15);
                     ^
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:41:38: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
   if ((monroy >= 0) && (monroy <= 5));
                                      ^
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:47:40: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
   if ((monroy >= 5.1) && (monroy <= 9));
                                        ^
/tmp/arduino_modified_sketch_71221/sketch_may02a.ino:53:21: warning: suggest braces around empty body in an 'if' statement [-Wempty-body]
   if (monroy >= 9.1);

These are important - you should pay attention to them. For example, here:

  if (distance = 15);  // <-- NO SEMICOLON NEEDED HERE!
  {
    digitalWrite (3, HIGH);
    delay (5000);
    digitalWrite (3, LOW);
  }

Putting a semicolon there means that stuff under the if is always executed - the semicolon terminates the scope of the if.

To see the warnings open the Preferences dialog in the IDE GUI and change "Compiler warnings" to "All".

Also:

  if (distance = 15);

This assigns 15 to distance, so distance will always be 15. You mean:

  if (distance == 15)


Arduino IDE: Board nodemcuv2 (platform esp8266, package esp8266) is unknown I am receiving this error after reinstalling Arduino IDE (everything was working fine [same components, same code]):

  Board nodemcuv2 (platform esp8266, package esp8266) is unknown

I have recently reinstalled ESP8266 libraries. Could that have caused this issue?

Did some digging and found a solution that worked for me:

Uninstall (by logically deleting folders) and reinstall ESP Libraries.

Open Arduino IDE
Go to FILE -> PREFERENCES

Open the preferences folder (this works in Linux, Mac and Windows)
Go to PACKAGES > ESP8266 > HARDWARE > ESP8266

Delete all libraries (if your issue is similar to mine and to others', you should have 2 or more folders, with different versions).

Restart Arduino IDE.
Go to SKETCH > INCLUDE LIBRARY > MANAGE LIBRARIES
Install ESP8266 Community
Go to TOOLS > BOARD and scroll down to your model of NODEMCU

Run compile and your problem should be fixed.


RF24 + High speed pwd I'm using the arduino to generate a 100kHz pwd using timer 1

void setup() {
  // put your setup code here, to run once:

   // Timer 1 Fast PWM mode *toggling* OC1A at 50kHz with *two* OCR1A counts
   // And 7.32 bits 0-159 PWM on OC1B at 100kHz
   // Output on OC1B
   // Set at TOP, Clear at OCR1B
   // WGM =15 0b1111

   DDRB |= bit(DDB1) | bit(DDB2);  // atmega168/UNO OC1A and OC1B (Tested by OP/Luis)

   TCCR1A =  bit(WGM11) | bit(WGM10) | bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
   OCR1A  = 159 ;//79;    // Set TOP count to 16000000/(2*PreScaler*Ftoggle)
                          // or 16000000/(PreScaler *Ftimer)
   OCR1B  = 10;           // 10/160 duty cycle
   TCNT1 = 0 ;
}

void loop() {
  // put your main code here, to run repeatedly:
  OCR1B = 160/4 -1 ; // 25% duty cycle.
}

I used this to test the modules:

Receiver
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
int msg[1];
RF24 radio(9,10);
const uint64_t pipe = 0xE8E8F0F0E1LL;
int LED1 = 3;

void setup(void){
 Serial.begin(9600);
 radio.begin();
 radio.openReadingPipe(1,pipe);
 radio.startListening();
 pinMode(LED1, OUTPUT);}

void loop(void){
 if (radio.available()){
   bool done = false;
   while (!done){
     done = radio.read(msg, 1);
     Serial.println(msg[0]);
     if (msg[0] == 111){delay(10);digitalWrite(LED1, HIGH);}
     else {digitalWrite(LED1, LOW);}
     delay(100);}}
 else{Serial.println("No radio available");}}

Transmitter

#include  <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
int msg[1];
RF24 radio(9,10);
const uint64_t pipe = 0xE8E8F0F0E1LL;
int SW1 = 7;

void setup(void){
 Serial.begin(9600);
 radio.begin();
 radio.openWritingPipe(pipe);}

void loop(void){
 if (digitalRead(SW1) == HIGH){
 msg[0] = 111;
 radio.write(msg, 1);}}

I'm using this library
https://github.com/TMRh20/RF24

And it works ok, now first issue is that both, RF24 and the pwm
are using the pin 10 but the library allows you  to change it, so now I'm using pin 7 instead. I tested it again and still works fine.

But when I add the lines at the setup to use the pwd  the communication doesn't work

   DDRB |= bit(DDB1) | bit(DDB2);  // atmega168/UNO OC1A

   TCCR1A =  bit(WGM11) | bit(WGM10) | bit(COM1A0) | bit(COM1B1)  ; // Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
   OCR1A  = 159 ;//79;    // Set TOP count to 16000000/(2*PreScaler*Ftoggle)
                          // or 16000000/(PreScaler *Ftimer)
   OCR1B  = 10;           // 10/160 duty cycle
   TCNT1 = 0 ;

I try line by line and the issue is here:

TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler

When setting the prescaler at 1.

Which is the dependency of the RF24 on this timer? and which options to I have to make it work

EDIT.

Now I'm using pins 6 and 7 for CE and CS
Also removed  "| bit(COM1A0) " form the register  setting

Still doesn't work

I've this

void setup(void)
{

  /// RF settings

  Serial.begin(9600);
 radio.begin();
 //radio.openReadingPipe(1,pipe);
 //radio.startListening();
 pinMode(LED1, OUTPUT);

 /// end RF settings

  //// pwd settings
 DDRB |= bit(DDB1) | bit(DDB2);
   OCR1A  = max_count;       // 16000000/(PreScaler *Ftimer)
   OCR1B  = 10;
   TCCR1A =  bit(WGM11) | bit(WGM10) |  bit(COM1B1); // bit(COM1A0) | Toggle OC1A, Clear on OC1B
   TCCR1B =  bit(WGM13) | bit(WGM12) | bit(CS10);  // Set /1 prescaler
   TCNT1 = 0 ;

  ////
 }

If I put the settings for the PWM before the settings for the RF24 then the PWM doesn't work, the RF settings at first the the communications doesn't work.

radio.begin() must be overwriting the registers but I haven't found how.

Maybe doing 100kHz PWM with timer2 instead of timer1 would be good.  The registers look similar to timer1, but they are only 8 bit, so you can't go bigger than 255 in the compare and count registers. The prescaler would be the same, and the timer controlled pins would be D11 and D3:

  //// pwm settings for 100kHz on Timer 2
  //// Toggle OC2A/D11/PB3 at 50kHz, PWM OC2B/D3/PD3 at 100kHz:
   DDRB |= bit(DDB3); //Enable output
   DDRD |= bit(DDD3); //Enable output
   // WGM2x=0b111 for fast PWM with TOP=OCR2A
   // COM2Ax=0b01 for toggle OC2A at OCR2A
   // COM2Bx=0b10 for set@bottom-clear@match_OCR2B PWM
   TCCR2A =   bit(WGM21)  | bit(WGM20)
            | bit(COM2B1)  // PWM on OC2B
            | bit(COM2A0); // Toggle OC2A
   TCCR2B =   bit(WGM22) | bit(CS20);  // Set /1 prescaler
   OCR2A  = 159;       // 16000000/(PreScaler *Ftimer)-1
   OCR2B  = 10;        // 6.25% PWM
   TCNT2 = 0 ;

I haven't tested this on an Uno/Atmega328P, but it looks reasonable per the datasheet (p153-157).

If you don't want both the 50kHz toggle and 100kHz PWM outputs, (as in your posted code,) you could disable one or the other and adjust the frequency as needed.


Beetle ble with SD card reader I just started working on a project involving bluno beetle ble. For now, i'm sending the data from beetle to a android app i made.

But, for a fail safe mechanism in case the mobile is not in range or has disconnected from the device, i want to add a SD card reader to the device so i can save the data.

Is it really possible to add SD card reader to beetle ble? If yes, can someone provide any hint on what connections need to be made?

Thanks

Eventually I got it working. The connections that i made are as follows:

SDA pin on beetle -> SDA pin on SD card module
SCL pin on beetle -> SCL pin on SD card module
GND pin on beetle -> GND pin on SD card module
VCC pin on beetle -> VIN pin on SD card module

Then upload the sample code present on arduino IDE, or you can find it here as well: https://www.arduino.cc/en/Tutorial/ReadWrite

There we go!

EDIT: The soldering is tricky for bluno beetle. Detailed instructions can be found here :


How to handle low temperatures using Arduino Uno? I want to create a simple electronic temperature sensor using the Arduino Uno.

The environments I want it to handle is inside a fridge and near a heater.

Although I am sure the Arduino can easily handle a heater; my issue is that the Arduino may not be able to handle a fridge.

A fridge also has the added problem of causing water vapor (and we all know water + electronics is never a good idea).

So my question is:

How would I create a temperature sensor using my Arduino Uno, that I can put in my fridge?
Are there any other problems I have not considered and how do I solve them?
Will I need a special type of casing? If so, which type?
Is an Arduino Uno even the best tool for this task?

Your Arduino does not have to be in the fridge, just the sensor. You can always choose waterproof sensor like this one to use with the arduino. Then you can always store your arduino outside the fridge. Same goes for the heater. Try to keep the arduino at room temperatures to avoid decreasing its life unnecessarily.

As for an actual answer to the temperature ranges, here is a good answer


convert 32 bit long to 4 bytes and back again - CAN Bus So after 2 days attempting this I can't get my head round it.

So I am using CAN bus to transfer accelerometer data and time data (the micros() function if under 71 minutes will output data that can be an unsigned long), however I have to send the data as bytes. I have managed to bit shift a 16-bit int into 2 bytes but I am having trouble extrapolating that method (will add later) to using longs. I am having trouble understanding the union method as I am new to creating my own functions, so, how would you guys accomplish this? As simple as possible please :)

The union type is similar to a struct except that each of the members of the element occupy the same memory. If you define a struct so that it has 2 members -- one 4-byte type and one 4-element array of a single byte type, then you can easily refer to the same data as a whole 4-byte element, or byte-wise as you desire.

union packed_long {
  long l;
  byte b[4];
};

This is the type, so you have to declare the variable to be of that type:

packed_long mydata;

Now, you have two sub-elements of mydata: l and b[].

To save your long value, write to the l part:

mydata.l = myaccel.getY();

To access each of the 4 bytes:

byte1 = mydata.b[0];
byte2 = mydata.b[1];
byte3 = mydata.b[2];
byte4 = mydata.b[3];

On the receiving end, you take each of the 4 bytes:

mydata.b[0] = canbus.read();
mydata.b[1] = canbus.read();
mydata.b[2] = canbus.read();
mydata.b[4] = canbus.read();

As long as you receive the bytes in the same order in which you sent them, you can now access your long value in mydata.l.

The actual size of different types is dependent on the compiler and architecture, so you may also wish to define your value as a definite-sized variable to ensure you are always working with 32 bits: int32_t (signed 32-bit integer) or uint32_t (unsigned 32-bit integer).


Multiple sensor connection help How would you connect multiple HC-SRO4 ultrasonic sensors to one arduino uno? As of now, I have a bunch of jumper cables, 3 u.s sensors, and one arduino uno board. How would one hook up 3 sensors? A schematic would be excellent!

It depends on what you want to do overall.

Using the HC-SR04 works roughly like this:

you generate a strobe on a pin for a minimum amount of time, and this strobe is understood by the sensor as "emit the ultrasound signal"
then you somehow (more on this later) measure how much time passed between your strobe and a change of level on another pin from the sensor - this is how the sensor notifies you that there was an echo and it has returned.
finally, you convert the time measured into distance, using a conversion algo (typically multiplying by a certain factor) that is specific to the sensor.

Mostly the problem revolves around point #2: how to measure the time elapsed between command (strobe) and answer (change of level).

You have various options, each with pros and cons:

busy looping: it's easy to implement, very straightforward and works right away. The problem is that your arduino will do just that.
polling: it's a less aggressive version of polling, where you check the values every now and then. It lets you do more, but the drawback is that in the worst case the line changes level right after you have checked it, so it will be noticed only at the following iteration. The period used for checking is the maximum error you will get.
GPIO interrupt driven: this is harder but lets your arduino do many other things, while not loosing precision (I'll detail it separately)
HW backed: the AVR on UNO has the ability to capture events: basically there is a timer running that will stop when it gets triggered by a certain event (ex: the change of pin level cause by the echo). It is very precise, but you are limited by the number of HW blocks available on the AVR (3 iirc).

Now about the sub-cases of the GPIO interrupt-driven solution:

EXT based: the ATMega328p present on the UNO has what are called external interrupt sources, which is a fancy way to say that if you configure correctly a pin, the processor will notice when the pin voltage level changes and do something about it (in your case, take a time measurement) - this is quite generic solution, but unfortunately it works only on 2 pins, so you are out of lack with your 3 sensors, unless you implement some scheme where you multiplex 2 or more sensors on only one pin.
Pin-change-interrupt based: on AVR most of the PINS are grouped in ports. Each port contains maximum 8 pins and is labelled with a letter (A, B, C, ..). The way this interrupt works is roughly like the EXT type, but with a catch: you will get an interrupt whenever any of the pins that you have enabled on a certain port will change. In your case you could allocate only one sensor on a certain port, so that it would be obvious that if you get an interrupt for that port, it will be because of that sensor.

So now you can see why I said "it depends". If all you want to do is to get the information about proximity, you can go with busy-looping/polling.

But if you decide later on to do more on the same arduino, be aware that you might have to come back to the implementation of the ultrasonic sensor.

Finally, there is a library for this, but its implementation will fall into one of the cases i mentioned before, so be aware that the same catch applies: at some point you might want to do something that conflicts with the library.

Other points worth mentioning, that you should consider in your design (at least experiment with them):

orientation of the sensors: will they interfere with each other?
timing: do you need/want to activate them all simultaneously or do you prefer to have them activated in sequence?


Using a 3V latching relay to power up ESP8266 I'm trying to use a 2-Coil Latching Relay like TXS2SA-L2-3V for  powering up a ESP8266. My idea is to activate the relay by setting the first coil to high and deactivate the coil by setting the second coil to high. In my circuit i will set the second coil to high at the end of the code by the esp8266. I need the latching (holding the power) function of it. Because when somebody activtes the Deep Sleep function to early, I have no electricity to power the esp8266.

My question is:

What kind of circuit I must use? I have no idea where I can start.

I have a regulator that can be enabled via de EN signal.

Thanks in advance!

You use a latching relay of this form in the exact same way as a normal relay - it's just there's two of them.

One coil you want to control with a button (power on) and the other with a transistor (and possibly an "off" button as well).

simulate this circuit – Schematic created using CircuitLab

Press ON to latch the relay into the ON position (NO -> COM). Activate M1 or press OFF to latch the relay into the OFF position (NC -> COM).


Arduino & RPi communication via GPIO so I'm working on communication between arduino and RPi via GPIO pin.
It's basically connecting them by using a cable jumper. So I have a 2 channel relay shield attached to my arduino, and I've been wondered how do I connect them to RPi. I need help for this problem, any advice would be appriciated. I'll post the GPIO pin below.
Thankyou

What you are asking really makes no sense at all.

You are starting from the mid-point of your project and wondering how to communicate using bare GPIOs without really knowing what it is you want to communicate and what you want to do with that data - or at least you haven't made any of that clear to us.

It is unclear what you want to do with the shield from the Pi. Do you want to control the relays on it by sending instructions from the Pi? Do you want the Pi to send and receive data through the XBee? Either way the Arduino is pretty redundant in the system and in fact gets in the way more than is useful.

If it's just relays you want then it would be far simpler to wire cheap relay modules direct to the GPIOs of the Pi - then you don't have to worry about "how to communicate" - you just turn the relays on and off.

If you want to communicate with the XBee there are far simpler shields available that will plug directly into a Pi. Indeed, there are some good shields around for the Pi ("Hats" I think they call them) which give you an Arduino footprint and an XBee socket together.

The Arduino is completely pointless in this system. And anyway, if you wanted to make the two systems communicate there are far easier ways than with bare GPIO pins. Serial, for a start. The simplest ever method is to just plug the Arduino into the Pi's USB. That way it gets power and data all in one go. Just like using it with a computer.


Switch case inside a switch case with serial input I'm trying to build a test program for some hardware. Basically I want to select the piece of hardware with the outer switch case then select the test with the inner switch case. I'm trying to accomplish this by using serial input in the Arduino IDE monitor.

I can't make it work whatever I do. I either end up stuck in the outer switch case or I never enter the inner switch case where I want to select the test.

I've got a bit of code below:

char select_addon;
char select_test;

void setup() {
  Serial.begin(9600);
  Serial.println("(1) PB1");
  Serial.println("(2) PB2");
  Serial.println("(3) PB3");
}

void loop() {
  if (Serial.available() > 0) {
    select_addon = Serial.read();
    switch (select_addon) {
      case '1':
        Serial.println("Test");
        if (Serial.available() > 0 ) {
          select_test = Serial.read();
          switch (select_test) {
            case '4':
              Serial.println(" Test 1.1");
              break;
            case '5':
              Serial.println(" Test 1.2");
              break;
            case '6':
              Serial.println(" Test 1.3");
              break;
          }
        }
        break;
      case '2':
        Serial.println("TEST 2");
        break;
      case '3':
        Serial.println("TEST 3");
        break;
    }
  }
}

Obviously this isn't the finished code, but it's the switch case structure I've been trying to implement. Any suggestions on how I can enter the inner switch case?

What happens of the if (Serial.available() > 0) call fails?  That's the problem, because when there isn't anything available it's skipping the second switch statement.

On a point of style it actually might be better to implement the inner switch as a separate function. Imagine what your code will look like with 5 cases in the outer switch, each with 5 cases in the inner switches.

Also it might be worth, for debugging purposes, to always have a default statement, at least then you will know what key it was that you pressed.


Feeble click in relay but it doesn't get activated when connected to Arduino circuit I have an Arduino uno board and I have a soil moisture sensor

connected the digital output pin of the sensor to Arduino input pin
connected an output pin of Arduino to the INPUT pin of the relay board
programmed the Arduino such that if input is HIGH then the OUTPUT should be HIGH as well
connected 5 v pin of Arduino to vcc of the relay board
connected gnd pin of Arduino to gnd of the relay board

When my sensor outputs a HIGH DO (digital output), the relay only creates a feeble click sound and does not get activated. The Relay board LED does light up but the relay itself does not work (NC remains closed and NO remains open).

Do I need to supply an external VCC to the relay board? If yes then how should I set up the circuit?

A picture of the relay board is attached. You are right ... it is a 12 v relay. Do I need a 12 v external power source with IN1 coming from Arduino? Any help will be much appreciated.

You need to join the ground of the external supply to the ground being supplied from the Arduino.  The 12V supply must be capable of at least 100ma

There appears to be a transistor and resistor on the board.  This is probably to drive the relay coil from the Arduino.  However, I would need to look at the circuit diagram of the board to be certain.  Can you supply images of the copper side and component side of the board to see what the connections are.

Ideally the circuit diagram from the manufacturer would be even better.


Atmega328 and 4Digit 7 Segment ghost blinking! I hooked up 4 7Seg leds (CC) with NPN transistors on the cathode of each digit. I am using 74HC595 shift register connected in the circuit in a pretty common fashion. The code I am running is the basic scanning code for the 7seg. The problem is that I see the scanned numbers on other LED digits too. Attached is the image. I call them "ghosts". The circuit I am using has an Atmega328 with an internal 8MHz Osc. The resistors on the segments are 220Ohm and 4 BC547's on the cathodes of the digits with 1kOhm resistors on their base.

below is the code:
void loop() {

      cathode_high(); // blank the screen

      break_number(number);

      display_number();
     delay(1);

}

void break_number(int num) { // seperate the input number into 4 single digits

  first_digit = num / 1000;
  digits[0] = first_digit;

  int first_left = num - (first_digit * 1000);
  second_digit = first_left / 100;
  digits[1] = second_digit;
  int second_left = first_left - (second_digit * 100);
  third_digit = second_left / 10;
  digits[2] = third_digit;
  fourth_digit = second_left - (third_digit * 10);
  digits[3] = fourth_digit;

}

void display_number() { //scanning

  cathode_high();
  digitalWrite(latch, LOW);
  shiftOut(data, clk, LSBFIRST, numbers[digits[count]]);
  digitalWrite(CAS[count], HIGH);
  digitalWrite(latch, HIGH);
  count++;
  if (count == 4) {
    count = 0;
  }
}

void cathode_high() { //turn off all 4 digit
  digitalWrite(CA_1, LOW);
  digitalWrite(CA_2, LOW);
  digitalWrite(CA_3, LOW);
  digitalWrite(CA_4, LOW);
}
Any help would be highly appreciated. Thanx in advance!

You change cathodes (digits) before latching in the new data. So for a spit second the data for the previous digits is shown on the current digit.
Swapping digitalWrite(CAS[count], HIGH); and digitalWrite(latch, HIGH); should fix that.


Arduino Micro 5V Vin and 3v3 pins I am very confused with the pins on the arduino micro. What are the 3v3, 5v, and Vin pins used for? Are they for power input, or power output, or both?

Vin is a power INPUT. It is connected to the input of the voltage regulator, which enables you to power the Arduino with voltages between 6V and 12V, while the Arduino itself is running on 5V.

The 5V pin can be both an power INPUT and OUTPUT. It is connected to the general 5V power rail inside the Arduino and thus to the power inputs of the microcontroller. This rail/pin needs to be provided with 5V power to let the Arduino work. Where this power comes from (from the voltage regulator, from USB or from your own external 5V power supply connected to the 5V pin) is irrelevant for the Arduino. The 5V pin can even be used to provide power to other components in your circuit (though with certain limitations, see below).

The 3V3 (meaning 3.3V) pin is a power OUTPUT. It is connected to the output of another voltage regulator, which brings the 5V from the 5V rail down to 3.3V. It can be used to power external parts, that need 3.3V to work.

Up to this point I only wrote about voltage. But depending on your circuit you also need to consider the current. The different electrical parts on the Arduino can only handle a specific power (measured in Watts). Thus with a given voltage you can only draw up to a specific amount of current through them, before you destroy them.

As an example, let's assume you provide the Arduino with 9V through Vin and you want to drive a middle sized motor. Motors in general can draw a lot of current. When you now drive the motor from the 5V pin of the Arduino, the motors current will flow through the Arduinos voltage regulator. Thus the regulator will go into emergency shutdown and cut the power (applies for a genuine Arduino) or it will get destroyed (applies for most cheap Arduino clones). To prevent that, you need to connect the motor directly with the power supply (or through an extra voltage regulator, suitable for the needed current), so that the current for it is no longer flowing through the Arduino.

This explanation is only to prevent you from destroying your board. That is always very annoying, when it happens.


analogRead() output oscillates even though the pin is grounded I'm using Arduino Micro to read from 5 flex sensors and display the corresponding angles to the Serial monitor. I am currently having quite some problems with the oscillating values I am getting from the analogRead(). It doesn't seem to matter whether the pin is connected to a flex sensor or just grounded - the output is oscillating a lot.

Originally everything was being read and outputted just fine but I wanted to have an exact 100Hz sampling frequency and tried to play a bit with Timer Interrupts. And that's when this oscillating behaviour started. I reversed to my original code, which just uses some delay(), and simplified to only read from two pins, but cannot seem to shake off the oscillations.

I think I may have messed up something about ADC when trying to implement Interrupts, but I don't know how to check it or fix it. Please, help me figure out how to fix this!

This is the raw output of analogRead. The drop in values occurs when I bend the flex sensor:

And this is the resulting calculated angle. Also oscillating:

This is the code I've been using to read the pins:

int fin;
const int input[5] = {A0,A1,A2,A3,A4}; // the analog pins

int flex[5]; // analog signal read
float flexV;
float flexR[5]; // resistance on the 47k resistor
int angle[5]; // joint angles

const float VCC = 4.98; // Measured voltage of Arduino 5V line
// Measured resistance of the 47k resistors R1-R5
const float R[5] = {45900.0,45900.0,45900.0,45900.0,45900.0};

// Calibration values of resistance measured during straight phase and 90 deg bend phase
const float R_STRAIGHT[5] = {37651.0,37651.0,37651.0,37651.0,37651.0};
const float R_BEND[5] = {71783.0,71783.0,71783.0,71783.0,71783.0};

void setup() {

}

void loop() {

  for(fin = 0; fin <= 4; fin++) {
   flex[fin] = analogRead(input[fin]);
   flexV = flex[fin]*VCC/1023.0;
   flexR[fin] = R[fin] * (VCC/flexV - 1.0);
   angle[fin] = map(flexR[fin],R_STRAIGHT[fin],R_BEND[fin],0,90.0);
   delay(1);
    }
    Serial.print(angle[0]);
    Serial.print(" ");
    Serial.print(angle[1]);
    Serial.print(" ");
    Serial.print(angle[2]);
    Serial.print(" ");
    Serial.print(angle[3]);
    Serial.print(" ");
    Serial.print(angle[4]);
    Serial.print(" ");
    Serial.println(millis());
    delay(6);
}

You have nothing in your setup loop. You need to set up all the inputs as inputs.

You setup() should look like this:

void setup()
 {
   Serial.begin(9600);
   for (int i = 0; i < 5; i++);
    {
      pinMode(input[i], INPUT);
    }
 }

The code cycles through your array "input", setting all the pins as inputs. Try that.


DHT11 and DHT22 unused pin The DHT11 and DHT22 is a 4 pin temperature and humidity sensor, where one of the pins is labelled as NC (not connected).

I'm curious what the unused pin is used for.
Factory calibration?

On the DHT11 it's connected to pin 6 of the SOIC14 inside. So it's at least connected to something. But who knows what it's for.

It has a (internal) pull-up resistor to VCC of around 100kOhm on this pin.

I connected my logic analyzer to it, there is no signal, even while reading the sensor. Also connecting the arduino's signal wire to this (incorrect) pin does nothing.

Factory calibration or testing would be my guess too, but who knows.


Cannot program Arduino Micro in OSX without hard resetting the board every time I am experiencing a problem when programming Arduino Micro in OSX Mavericks. I have tried to reproduce this problem in XCode and Arduino IDE and it is persistent. I need to make a hard-reset at the same time as a click the "program" button.

I have tried to use the new Leonardo bootloader to see if it solves my issue, but its still persistent.

I am running avrdude 6.1, what is the problem?

Stacktrace:

---- Size ----

Binary sketch size:   24162 bytes (of a 28672 byte maximum)
Estimated SRAM used:  733 bytes (of a 2560 byte maximum)
Elapsed time: 5.2 s

---- Reset ----

screen -X kill

No screen session found.

make: [reset] Error 1 (ignored)

sleep 1

9.2-RESET:  <   micro   ./ ./

stty -f /dev/tty.usbmodem1411 1200

---- Upload ----

10.6-UPLOAD:  <     micro   ./

/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avrdude -patmega32u4 -C/Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/etc/avrdude.conf -D -cavr109 -b57600 -P/dev/tty.usbmodem1411 -Uflash:w:Builds/embeddedcomputing.hex:i

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

This Arduino.cc article describes the differences between Leonard & Micro vs. other Arduinos, including the fact that Micro does not have a separate USB processor on board but creates a virtual USB with the main processor. There is no (or a very different) auto-reset mechanism. There is apparently a way for the IDE to open the Mac's USB at 1200 baud to cause the Micro to reset; then the IDE can wait for the virtual USB to re-appear. But it also says you may need to use the reset button suggesting the 1200 baud dance doesn't work all that reliably.


What do you do when you finish a project? I have just about completed my first Arduino project using an Arduino Uno board, but is that what I use inside the finished device? I figured I’d keep the Uno for future projects and have something else controlling the finished product. Are you supposed to just keep purchasing the Uno board every project?
I just got it a couple of days ago so I’m not very familiar with any of it. If that is the case do you use the batter for power since I can’t have it connected to my laptop once it’s done.

There are many options, so it all ends up depending on your personal
preferences:

You could indeed dedicate this Arduino to this project, and buy a new
one for the next project. This may be the simplest solution, if not
the cheapest. Just make sure you are not using a breadboard for the
other parts. A “proto-shield” may be a good option for soldering the
rest of your circuit in a permanent form.

You may replace the Uno with a smaller Arduino, like the Micro (but
beware it uses a different MCU) or a Pro Mini clone (same MCU). These
smaller boards can then be soldered onto a PCB using standard 0.1” pin
headers.

You could buy a cheap clone, test it to make sure it works as intended
on this particular project, and dedicate the real one for further
prototyping.

You could get a bare ATmega328P plus crystal and caps and put them,
together with the rest of your circuit, onto a perf-board or a
strip-board. C.f. Michel Keijzers’ answer. Note that if your program
can run happily off a somewhat inaccurate 8 MHz clock, you can
use the MCU's internal oscillator instead of a crystal.

If your program is far from using all the resources of the Uno, you
may consider a smaller MCU. The ATtiny85 is a popular “minimalistic”
choice. Make sure an Arduino core is available for it, unless you want
to program all low-level.

For the most professional result, you could design and order a real
PCB for your whole circuit, including the MCU.


Arduino reads bogus from serial Recently I've started playing around with an Arduino Uno (rev 3), and I've set up a communication bridge between the Arduino and my computer using Python. So I send a command in Python ("ping" for instance), which is then read and interpreted. I've had it working before, using the Python commands to control a motor, but today it became non-responsive. However, only if I boot the serial monitor from the Arduino IDE, it suddenly accepts my commands again. Further inspection reveals that the Arduino is probably reading empty or corrupted data, interpreting it as ð, à and ÿ and such.

Here is an excerpt of the Python code I'm using:

import sys, glob, serial, time, re

class interface:

     timeout = 2    # 10 second time-out

    def __init__(self):
        port = "/dev/ttyACM0"
        self.connect(port)
        pass

    def connect(self, port="/dev/ttyACM0"):
        global arduino
        arduino = serial.Serial(port, baudrate=115200, bytesize=8, parity=serial.PARITY_NONE, stopbits=1, timeout=0.1)  # Establishing connection
        time.sleep(3) # Allowing the connection to settle
        arduino.flush()
        print "Connection established..."

    def ping(self):
        arduino.flush()
        arduino.write("ping")
        msg = self.listen_arduino()
        print msg
        if msg == "ping_ok":
            print "pinged"
            return True
        return False

    def listen_arduino(self):
        timeout = self.timeout
        matcher = re.compile("\n")
        buff = ""
        t0 = time.time()
        buff += arduino.read(128)

        while (time.time() - t0) < timeout and (not matcher.search(buff)):
            buff += arduino.read(128)
        return buff.strip()

And here is the Arduino C code:

String readString;

void setup() {
    Serial.begin(115200); // use the same baud-rate as the python side
}

void loop() {
    readString = listen(); // listen for any commands
    if (readString.length() > 0) {

        Serial.println(readString); // print the command

        if(readString == "ping") {
          Serial.write("ping_ok");
        }
    }
}

String listen() {
    String readString;
    while (!Serial.available());
    while (Serial.available()) {
        delay(1); // Allow the buffer to fill
        if (Serial.available() > 0) {
            char c = Serial.read();
            readString += c;
        }
    }
    return readString;
}

I suspect there is something fishy with the connection I'm making on the Python side, as the Arduino IDE serial monitor works just fine. I hope anyone can spot the problem in this code, I'm willing to provide more details on request.

Thanks

I've discovered that there was another program trying to access the Arduino, interfering with the code above and causing corruption of the signal. After terminating the intrusive program, the code worked just fine.


How do I use the prototyping area on a SparkFun MicroSD Card shield? I'm having trouble figuring this out. I'm using this popular shield: https://www.sparkfun.com/products/12761

There is a breadboard area in the middle of the shield. But what confuses me is the lack of lines (order). On normal breadboards you can tell which row would be at the same voltage. If I wanted to put something on this prototyping area, how would I connect it? For example an LED, which would have a resistor attached to the positive side going to 5V and the negative side going to ground?

This type of board, "pad per hole", has no pre-made interconnects. If you use thin enough wire sometimes you can push two pieces of wire into the same hole before you solder, say a resistor lead and another wire to connect to the next component. You can also solder an interconnect wire to the protruding leg of a DIP chip. You can make a buss for ground or 5v by assigning a whole row for that purpose, on the top side wire everything that needs to connect to that buss, and on the bottom side solder a straight piece of bare wire to all those wire ends in that row.


Too few arguments for multiple if statement conditions I am using the Arduino Uno.  I am attempting to only light a red LED when both a blue LED is on and the push button is pressed.  However, I keep receiving an error message stating too few arguments in my if statement.  I don't know whether I am simply overlooking something in my code.

The code is as follows:

int redLEDPin=7;
int blueLEDPin=3;
int redLEDOn=2000;
int redLEDOff=1000;
int blueLEDOn=2000;
int blueLEDOff=1000;
int leverR=2;

void setup() {
    pinMode(redLEDPin, OUTPUT);
    pinMode(blueLEDPin, OUTPUT);
    pinMode(leverR, INPUT);
    }

void loop() {
    digitalWrite(blueLEDPin, HIGH);
    delay(blueLEDOn);
    digitalWrite(blueLEDPin, LOW);
    delay(blueLEDOff);
    }

  if ((digitalWrite(blueLEDPin) == HIGH) && (digitalRead(leverR) == HIGH)) {
    digitalWrite(redLEDPin, HIGH);
    delay(redLEDOn);
    digitalWrite(redLEDPin, LOW);
    delay(redLEDOff);
    }
  else
  {
    digitalWrite(redLEDPin, LOW);
  }
}

The digitalWrite statement in the if statement needs a value to write. It looks like you meant digitalRead, since you're comparing the result to something and the other condition is a digitalRead.

 if ((digitalWrite(blueLEDPin) == HIGH) && (digitalRead(leverR) == HIGH)) {

vs

 if ((digitalRead(blueLEDPin) == HIGH)  && (digitalRead(leverR) == HIGH)) {


Code with if multible conditions My project has 4 float switches, 2 valves and 3 pumps. I created a sketch and uploaded it. But my project keep all "OUTPUT" at "HIGH" all the time. I couldn't find what the problem, can you help?

This is my sketch:

#include <DS3231.h>
#include <Wire.h>
#include <LiquidCrystal.h>
DS3231  rtc(SDA, SCL);

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
int x = 45;
int y = 47;
int z = 41;
int w = 43;

int WaterIn =  40;
int WaterOut = 42;

int Pump1 = 25;
int Pump2 = 24;
int Pump3 = 27;

void setup()
{
  rtc.begin();
  lcd.begin(16,2);
  // Start the I2C interface
  Wire.begin();
  // Start the serial interface
  Serial.begin(9600);
  //rtc.setDOW(TUESDAY);     // Set Day-of-Week to SUNDAY
  //rtc.setTime(1, 15, 0);     // Set the time to 12:00:00 (24hr format)
  //rtc.setDate(6, 6, 2017);   // Month, Day, Year

 //Setup FLoat Switch Pins
  pinMode (x, INPUT);
  pinMode (y, INPUT);
  pinMode (z, INPUT);
  pinMode (w, INPUT);

 //Setup Irrigation Valves
  pinMode(WaterIn, OUTPUT);  //irrigation "in" valve
  pinMode(WaterOut, OUTPUT);  //irrigation "out" valve

//Setup Pumps
  pinMode(Pump1, OUTPUT);
  pinMode(Pump2, OUTPUT);
  pinMode(Pump3, OUTPUT);
}  // end of setup

void Calendar(){

 lcd.setCursor(0,0);
 lcd.print("Real Time Clock  ");
 lcd.setCursor(0,1);
 lcd.print("Time: ");
 lcd.print(rtc.getTimeStr());
 delay(1000);
 lcd.setCursor(0,1);
 lcd.print("Date: ");
 lcd.print(rtc.getDateStr());
 delay(1000);
 lcd.setCursor(0,1);
 lcd.print("Day: ");
 lcd.print(rtc.getDOWStr());
 lcd.print("           ");
 delay(1000);
 lcd.setCursor(0,1);
 lcd.print("Temp: ");

 lcd.print(rtc.getTemp());
 lcd.print(" C");
 lcd.print("          ");
 delay(1000);
}  // end of setup

void Valves(){
    int pinToTurnHigh = 24;
    if ((x == HIGH) && (y == HIGH) && (z == HIGH) && (w == LOW))  //Condition 1
    {
        pinToTurnHigh = WaterIn;
        pinToTurnHigh = Pump1;
        pinToTurnHigh = Pump2;
        pinToTurnHigh = Pump3;
    }
    if ((x == LOW) && (y == LOW) && (z == HIGH) && (w == HIGH))  //Condition 2
    {
       pinToTurnHigh = WaterOut;
    }
    resetAllPumpValve();
    digitalWrite(pinToTurnHigh, HIGH);
}  // end of setup

void resetAllPumpValve(){
     digitalWrite(WaterIn, LOW);
     digitalWrite(Pump1, LOW);
     digitalWrite(Pump2, LOW);
     digitalWrite(Pump3, LOW);
     digitalWrite(WaterOut, LOW);
}  // end of setup
void loop()
{
    Calendar();
    Valves();
    resetAllPumpValve();
}  // end of loop

It is not clear, what the code actually should do (what behaviour you are trying to achieve), so I will only look into the obvious programming problems.

The following declarations at the global scope seem to be pin numbers:

int x = 45;
int y = 47;
int z = 41;
int w = 43;

int WaterIn =  40;
int WaterOut = 42;

int Pump1 = 25;
int Pump2 = 24;
int Pump3 = 27;

But in the Valves() function yout treat them as they were representing the value of that pins. That is not the case. If you want to read the state of a pin, you cannot do

if ((x == HIGH) && (y == HIGH) && (z == HIGH) && (w == LOW))

You are just comparing the pin number with HIGH, which is defined as 1. That cannot work. You have to actually read the pin using it's pin number, which looks like this:

if( digitalRead(x) == HIGH && digitalRead(y) == HIGH && digitalRead(z) == HIGH && digitalRead(w) == HIGH)

And that can be shortened to:

if( digitalRead(x) && digitalRead(y) && digitalRead(z) && digitalRead(w) )

Inside of the mentioned if statements you set a variable multiple times without doing anything with it. Any consecutive write to this variable will overwrite the previous value. After the code block

pinToTurnHigh = WaterIn;
pinToTurnHigh = Pump1;
pinToTurnHigh = Pump2;
pinToTurnHigh = Pump3;

The variable pinToTurnHigh is 27 (Pump3). The values, that you assigned right before that line, are lost. You actually have to do something with the variable, or the first 3 lines of that block makes no sense.
In most cases it is not a good idea, to use variables with changing values to handle pin numbers, since that will make the code difficult to understand. The circuitry is mostly hardwired, it will not change. So there is no need to assign pin numbers to a changing variable. Instead you can directly do, what you need to do with a constant pin number. (Actually the code optimizer, that comes with the compiler, can optimize the not-changing pin-number variables out, so that you wrote them in your code, but the actually code might not have them.) Here it seems, that you want to write a HIGH value to all the mentioned pins. You can do that directly:

digitalWrite(WaterIn, HIGH);
digitalWrite(Pump1, HIGH);
digitalWrite(Pump2, HIGH);
digitalWrite(Pump3, HIGH);

Here it is important to understand, that digitalWrite() is only working on 1 single pin at a time. If you want to set multiple pins with it, you have to call it multiple times with the according pin numbers.
Now the timing of your code: The Calendar() function will block the rest of the code for about 4s, because you used that much of delay(). During that time the Arduino cannot react to anything. The switches will not do anything either (since the Arduino is busy waiting in the delay() instead of checking the switches). The code, that is called after the Calendar() function, contains no delay()s, so it will run very fast. In the Valves() function you first reset all the pumps and valves to LOW. Then you write HIGH to one pin (as mentioned above I assume, that you wanted to write them all on condition). After that the program will go back to the loop() function and execute the resetAllPumpValve() function again, which will set all the outputs to LOW.

All in all that means, that the Arduino is fiddling thumbs inside the Calendar() function, without doing anything else. Then he will reset, set and reset the pins again. Since there is not timing code in there, this will happen very fast. So the pins have to be LOW most of the time and being turned on about every 4s for a tiny amount of time (a low number of milliseconds, since that is about the time to execute digitalWrite() or it's siblings). The motors or values will hardly have time to move with that.

For solving this you might want to look into the BlinkWithoutDelay example, that comes with the Arduino IDE. It shows a non-blocking coding style, that will only do something, if it is the time to do it. Much like when you bake a pizza. You will not sit in front of the oven and wait patiently, until the pizza is fully baked. You will put it into the oven and regularly (maybe every 5 min) look, if the pizza is ready to eat. In the meantime you would do other things. Thats what is done there by using the millis() function, that will return the number of milliseconds passed since the programs startup. You can look into the example and google about it to learn more. It has been covered numerous times throughout the internet.

That's it for now. To really help you with the logic of the program, you will first have to get these parts right.

Have fun while learning :-)


Read Comma Separated String I have a string that looks like this "10.00,20.00,-50.00," in which these are angle values and they have 2 decimals and can be negative. I want to separate them into 3 separate floats. Here is my current code in which I use sscanf. All I get is 0.00 and have no idea why. Any help is truly appreciated.
String recvString = "10.00,20.00,-50.00,";
float r,p,y;

void setup() {
  Serial.begin(9600);
  Serial.println(r);
  int result = sscanf(recvString.c_str(), "%f,%f,%f,", &r, &p ,&y);
  Serial.println(r);
}

void loop() {}

The AVR implementation of sscanf() does not support parsing floating point numbers, thus you only get zeros out of it. You can't use the %f specifier with it. You need to convert these numbers by yourself with functions like atof() or similar.
Splitting a string into parts can be done many ways. You could use sscanf() to split up the string parts and then use something like atof() to actually convert to float. Or you use strtok() for splitting (see my answer to this question). Or you use one of the many other options, that you get, when googling for something like "Arduino split string" or "Arduino split c string".
Note: Using the String class in Arduino is easy for beginners, but not a good practice (dynamic allocation, heap fragmentation). Look at Majenkos blog for more information about that. Since you already used a function for C-strings, I would suggest moving completely to C-strings (which are basically only an array of char).


ESP8266 and Python Communication I'm new to networking and working with ESP8266. I have successfully setup my ESP8266 and can program it from Arduino IDE (tested a blinky code).

I want to send some data from a Python script running on my PC to ESP8266. Similar to a setup where use PySerial in Python, open a COM port and send my serial data to an Arduino. Arduino will parse my data bytes and will perform some action. Now, I am trying to achieve the same with ESP8266 and UART replaced with wireless communication.

First, I would like to connect my PC to ESP which will have its own SSID and password. Once connected, I would like to send my data bytes from Python script to ESP8266 wirelessly. Now, similarly, ESP will parse this received data and perform some function (like control its GPIOs).

How can I achieve this? It seems like a pretty simple task, but I'm really confused with what mode I've to use (AP? Client? Server?). What protocol for communication is the best (TCP? MQTT?). What do functions like Handle client/root do? I understand I've to use socket programming on Python, how to do that specifically in my case? How do I buffer my incoming data on ESP, so that I don't miss the bytes?

Could anyone please explain using an analogy with wireless communication and UART? Any links to tutorials will be helpful too. There are some tutorials online where they do this using a HTTP server and control the GPIOs from the browser, but no, I don't want this. I just simply want to send my data as I would with COM Port/UART/Arduino!

Check my project: "Esp 2 Python"

https://github.com/KebabLord/esp_to_python

The theori is you can create a localhost and get the sensor data or manage the module through arduino requests or urllib modules with a simple local mDNS server. This project allows you to control and read ESP.


Why is that any sensor signal need to be hooked up to the interrupt pins on Andruino boards? I have come across some Andruino Sensors like Motion, Light and all recommend to be connected to pin 2 or 3 on Andruino Uno board which are interrupt pins. This is especially true if you are looking for HIGH or LOW values. Why is that to be connected to interrupt pins?

One example would be is I used CC3000 Wifi Breakout and Motion sensor. Both were in fight to occupy the interrupt pin 2. I have seen the Motion sesnor not working correctly after getting it's signal hooked to Pin 4[It has pull up resistor enabled]

What should I do if i need to hook up more sensor which uses the limited interrupt pins and how should i handle the above scenario?

The interrupt pins are used to notify the MCU that a device needs attention. The INTx pins are chosen first because they are easy to program for; each gets a dedicated interrupt vector and hence ISR.

There is another type of external interrupt though, the Pin Change interrupt. This can be invoked via any of the PCINTxx pins on the device; on the '328 any pin can act as an interrupt.

The main difference between INT and PCINT is that PCINTs are grouped into banks of 8, which means that once the ISR has been invoked the appropriate pins need to be checked for their level, which furthermore means that it is possible to misread an interrupt if a bank is shared by multiple devices and the interrupt pulse itself is very short.

Further details can be read in the "External Interrupts" and "Interrupts" sections of the MCU datasheet.


using more than 8 temperature probe of DS18B20 on Arduino I am trying to use more than 8 temperature DS18b20 on one bus. Is there any problem to make it work?

As far as I can see there is no limit on the number of sensors you can have on a bus.

So if you are having problems does your code work with less sensors? Try one and work up.

Is it a current issue are you pulling to much from the board?

Is the problem with the one wire library?

Have you got 4.7k pull ups on each sensor?


Arduino MCP23S17 I/O Expander (SPI) I found this post and I am having almost the exact same issue. Nick Gammon (the god of arduino) has an excellent answer but I can't for the life of me implement it myself. I am not an advanced user like the initial question asker.

So What I want to do is use 2 MCP23S17's (picture here).
I have been messing with one of them all week and have it reading like a charm. I am using the githib library by n0mjs710 to do this. But writing to one will not work.

Along with the zipped library is a few examples. I am trying to read some BCD switches off of one "input MCP" and then display the digits on the "output MCP"

I have used external pullups so I did make one change to the code by commenting out the call for pullups. Here is what Doesn't work:

#include <SPI.h>              // We use this library, so it must be called here.
#include <MCP23S17.h>         // Here is the new class to make using the MCP23S17 easy.

MCP inputchip(1, 10);             // Instantiate an object called "inputchip" on an MCP23S17 device at address 1
                                  // and slave-select on Arduino pin 10
MCP outputchip(2, 10);            // Instantiate an object called "outputchip" on an MCP23S17 device at address 2
                                  // and slave-select on Arduino pin 10

void setup() {
  inputchip.begin();
  outputchip.begin();
  inputchip.pinMode(0xFFFF);     // Use word-write mode to set all of the pins on inputchip to be inputs
  //inputchip.pullupMode(0xFFFF);  // Use word-write mode to Turn on the internal pull-up resistors.
  inputchip.inputInvert(0xFFFF); // Use word-write mode to invert the inputs so that logic 0 is read as HIGH
  outputchip.pinMode(0x0000);    // Use word-write mode to Set all of the pins on outputchip to be outputs
}

void loop() {
  int value;                        // declare an integer to hold the value temporarily.
  value = inputchip.digitalRead();  // read the input chip in word-mode, storing the result in "value"
  outputchip.digitalWrite(value);   // write the output chip in word-mode, using our variable "value" as the argument
  // outputchip.digitalWrite(inputchip.digitalRead()); // this one line replaces the three above, and is more efficient
}

I have tried:

slowing the SPI bus by changing the library to SPI_Divide the clock by 2
changing the ss line and even splitting the lines so one chip uses pin 10 and the other uses pin 9

So after reading Mr. Gammon's post I have made some changes to the code attempting to rid myself of the old slave select pin low trick he mentioned. Here is my attempt:

MCP inputchip(1, 10);             // Instantiate an object called "inputchip" on an MCP23S17 device at address 1
                                  // and slave-select on Arduino pin 10
MCP outputchip(2, 9);            // Instantiate an object called "outputchip" on an MCP23S17 device at address 2
                                  // and slave-select on Arduino pin 10
int ssPin = 9;

void setup() {
  pinMode(ssPin,OUTPUT);

  inputchip.begin();
  digitalWrite(ssPin, HIGH);
  digitalWrite(ssPin, LOW);
  outputchip.begin();
  inputchip.pinMode(0xFFFF);     // Use word-write mode to set all of the pins on inputchip to be inputs
  //inputchip.pullupMode(0xFFFF);  // Use word-write mode to Turn on the internal pull-up resistors.
  inputchip.inputInvert(0xFFFF); // Use word-write mode to invert the inputs so that logic 0 is read as HIGH
  digitalWrite(ssPin, HIGH);
  digitalWrite(ssPin, LOW);
  outputchip.pinMode(0x0000);    // Use word-write mode to Set all of the pins on outputchip to be outputs
}

void loop() {
  int value;
  // declare an integer to hold the value temporarily.
  value = inputchip.digitalRead();  // read the input chip in word-mode, storing the result in "value"
  digitalWrite(ssPin, HIGH);
  digitalWrite(ssPin, LOW);
  outputchip.digitalWrite(value);   // write the output chip in word-mode, using our variable "value" as the argument
}

So any advice would be great to get this working. Help me Obi wan Gammon your me only hope.

Majenko's library works. All praise to Majenko https://github.com/MajenkoLibraries/MCP23S17


How can I tell what programmer to use? I have a bunch of different dev boards for different projects. What I have been getting very confused about is what board needs what programmer from the Tools > Programmer menu.

I wish the selection had the option to be partially automated for the board selection. But it's evidently not. Part of my problem is that if you choose the wrong programmer, some boards seem to work. Others read but won't write, or will write to some spaces, but not others. Or, you might get other cryptic errors that sound a lot like failed hardware. Have a look at this message for an example:

OK, so let's say I have some random dev board. How can I know what programmer I should use? Assume the manufacturer's documentation mentions nothing about it...

Generally the Tools > Programmer selection is only used for Tools > Burn Bootloader and Sketch > Upload Using Programmer and is not used for standard uploads. So for standard uploads you can set it to anything you like because it will have no effect.

The most notable exception is the Adafruit Trinket, which does require you to select Tools > Programmer > USBTinyISP even though you are uploading through the USB socket on the Trinket board without a separate ISP programmer.

You will also find some 3rd party hardware packages that are not written for boards with an Arduino style serial bootloader and so treat a standard upload as an "Upload Using Programmer" for the sake of convenience. Examples are MicroCore and the "Barebones ATmega Chips (no bootloader)" hardware package. In this case the correct Programmer menu selection is dependent on which model of ISP programmer you are using.

So regarding the question "How can I tell what programmer to use?": If you're doing a standard upload, start by assuming it doesn't matter. If that doesn't work, read the documentation!

If you're doing a Tools > Burn Bootloader or Sketch > Upload Using Programmer (or holding shift while pressing the "Upload" button) then you should select the model of the ISP programmer you're using.


Corrupted output from HC-05 Bluetooth module I have arduino Pro Mini 3.3V version with hc-05 module connected to 3.3V/GND and RXI/TX0 pins. I am then using my android phone to connect to the module. It shows up and pairs fine. Then I use BlueTerm app to view the output. I am seeing output that is occasionally as expected but mostly partially corrupted (characters replaced with random characters).

I am using 9600 baud rate and trasmitting the following:

void serialTransmit(int data){
  // send to raspberry pi or other device(s).
  Serial.print("Serial Transmit: ");
  Serial.println(data); // this is hard coded as "12" for testing
}

I tried switching rx/tx pins around but got same corrupt output. Tried changing baud rate but then it wouldn't transmit anything at all and default rate is 9600 so that was expected.

What could be the cause?

First thing to try:

Connect a 2.2k - 10k resistor from the arduino RX pin (the hc-05 tx pin) to ground.

If that didn't work, I recommend getting everything into a known state and eliminating some complexity. So, first let's remove the Android software from the equation.  And second, let's put the module into a known baud rate.

To do this wire up the arduino and module like this:

Notice that the Key pin is connected to 3.3v.  That will ensure the module is at 38400 baud on power up.

Connect the arduino to your computer with the FTDI cable.  Upload the following sketch:

/* Serial Loop */

#include <SoftwareSerial.h>

#define rxPin 8
#define txPin 9

SoftwareSerial mySerial(rxPin, txPin); // RX, TX
char myChar ;

void setup() {
  Serial.begin(9600);
  Serial.println("AT");

  mySerial.begin(38400);
  mySerial.println("AT");
}

void loop() {
  while (mySerial.available()) {
    myChar = mySerial.read();
    Serial.print(myChar);
  }

  while (Serial.available()) {
    myChar = Serial.read();
    Serial.print(myChar); //echo
    mySerial.print(myChar);
  }
}

With the sketch now uploaded and running, open the Arduino serial console and enter these AT commands. The serial console baud rate should be set to 9600 and line endings should be "Both NL & CR"

AT+ORGL //back to factory settings
AT+ROLE=0 //slave role - transparent serial bridge
AT+UART=9600,0,0 //default baud rate
AT+INIT //init module

You should get "OK" back from the module after each command. If you've gotten this far, we know the module is working fine and we know what baud rate it will default to now.

Hook the module back up the way you had it before.  Make sure 3.3v is disconnected from key pin and make sure you have added the pulldown resistor on the RX line. Cycle the power to the module. The module should start up running 9600 baud, slave mode. Delete the module from the Android pairing list and re-pair it.  The name probably will have changed.  Hopefully it works correctly now.

Cheers


7 segment display with common anode I am brand new to electronics. I am trying to use a seven segment display breakout module with my arduino uno. My problem is that the display has a common positive instead of negative common. How do I make this work? As far as I am aware, all the arduino pins output positive with the exception of the ground, which is the negative common.

This answer assumes Arduino Uno. For other types, refer to the documentation.

Ardino pins are not positive per se: you can change the voltage with digitalWrite() to either 0V (LOW, equal to the GND pin) or 5V (HIGH, equal to VCC).

The difference between a common cathode or common anode will be the flow of the current. With a common cathode (negative), the pins will need to provide current ("source" current), with a common anode, the pins will need to receive current ("sink" current).

There is a description for the limits of sourcing and sinking:

  Pin SOURCE Current Limitations:

  20 mA at VCC = 5 V

  Pin SINK Current Limitations:

  20 mA at VCC = 5 V

Please also read about the maximum total of 150 mA sourcing and 100 mA sinking.

You'll need to compare those current limits with the current requirements of your 7 segment display. My guess is that your a 7 segment display has 1 VCC pin and 7 output pins that you connect to the Arduino. The limiting factor is the total maximum here. The Arduino can handle 100 mA/7 = 14mA in the worst case. If that's enough for your 7 segment, it should work.

For example, this one works with 10 mA, so it would be compatible with Arduino. Make sure you have resistors in place.


Set dynamically hour - DS1307 I want keep my RTC1307 always updated with my server, so I created this code to first search the time on the server then passes to getServerTime() function to divide it and set in the RTC. I use the rtc.adjust() to adjust my watch.

Problem: My watch is getting wrong, this is set 2165/165/165 165:165:85. I think the problem is in defining the time in rtc.adjust(), I'm going as follows:

//tempDate -> May 19 2015
//tempHour -> 09:25:14
rtc.adjust(DateTime(tempDate, tempHour));

Does anyone know the cause of this error?

#include <Ethernet.h>
#include <SPI.h>
#include <Wire.h>
#include <RTClib.h>
RTC_DS1307 rtc;

byte server[] = { 192, 168, 0, 8 };
byte ip[] = { 192, 168, 0, 237 };
byte mac[] = { 0xDE, 0xAD, 0xAD, 0xEF, 0xFE, 0xED };

void setup() {
    Ethernet.begin(mac, ip);
    Serial.begin(9600);
}

void loop() {
    getServerTime(getSiteData());
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
    Serial.println();
    delay(5000);

}

char * getSiteData()
{
    EthernetClient http;
    unsigned char startRead = 0, i = 0;
    char inString[50];

    if (http.connect(server, 80)) {
        http.println("GET /util/date.php HTTP/1.1");
        http.println("Host: ");
        http.println("Connection: close");
        http.println();

        while (http.connected()) {
            while (http.available()) {
                char c = http.read();

                if (c == '<' )
                    startRead = 1;

                else if (startRead) {

                    if (c != '>') {
                        inString[i] = c;
                        i++;
                        inString[i] = '\0';
                    } else {
                        startRead = 0;
                        http.stop();
                        http.flush();
                        return inString;
                    }
                }
            }
        }
        Serial.println(inString);
        http.stop();
        http.flush();
    }
    else
        Serial.println("Tentativa de conexão falhou. Sem internet ou servidor inacessivel");
}

//May 19 2015-09:17:24
void getServerTime(char* siteData)
{
    char *tempDate, //May 19 2015
        *tempHour; //09:17:24

    tempDate = strtok(siteData, "-");
    tempHour =  strtok(NULL, "-");

    rtc.adjust(DateTime(tempDate, tempHour));

}

The numbers you are reporting are very familiar to me.  They are telling me that it is not possible to obtain the time from the RTC chip.

You are getting the time from your server, and as long as the string is actually what you think it is, then the values should be fine.  This snippet works perfecty:

#include <RTClib.h>

char siteData[] = "May 19 2015-09:17:24";

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

    char *tempDate = strtok(siteData, "-");
    char *tempHour =  strtok(NULL, "-");
    DateTime now(tempDate, tempHour);

    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(' ');
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();
    Serial.println();
}

void loop() {
}

So it must be in the passing of the data through the RTC chip that is failing.

Check that the chip is actually wired up properly, is running, and is responding normally before you try adding in the code to set the time from the server.