Arduino Mega 2560 Only Powers on with USB I have an Arduino Mega 2560 board running a ramps 1.4 shield for a 3D printer.  For some reason, I can only power the Mega with USB.  It does not get power from the ramps shield and it also will not power on when plugged in to a 12v wall adapter.  I know all power sources are working because I have a second Mega that works fine on all.  What could I check on the Mega board to help figure this out.  Other than being powered only by USB, everything else works as expected with no problems.

Looking at this Arduino Mega 2560 schematic, if IC1 or IC2 failed (assuming only one or the other is installed for a given board), then you would only be able to power the board using the USB port.

Looking at this ramps 1.4 shield schematic it is assumed that the RAMPS 1.4 shield is providing 12 volts through D1 to the Arduino Mega 2560.  And that testing included using a known good Arduino Mega 2560 board with the RAMPS 1.4 shield board with good results.  Thereby eliminating the possibility that D1 on the RAMPS 1.4 shield is damaged.

If these assumptions are correct, this reinforces the likelihood that either IC1 or IC2 has failed on the Arduino Mega 2560 board.


Simply Button Problem (Teensy 2.0) I am getting back into doing some hardware stuff after a fairly long time away and am having a hard time getting back into it. I have a Teensy 2.0 and am trying to run a basic sketch that when a button is pressed will output 0, but my button is always High. I think that I miswired something but my breadboard looks like all the tutorials so I'm just confused as to what is going on and would appreciate any help.

const int pinBtnUp = 0;
const int pinLEDOutput = 11;

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

  //Setup the pin modes.
  pinMode( pinLEDOutput, OUTPUT );
  //Special for the Teensy is the INPUT_PULLUP
  //It enables a pullup resitor on the pin.
  pinMode( pinBtnUp, INPUT_PULLUP );

}

void loop()
{
  Serial.println(digitalRead(pinBtnUp));
}

You should post a higher quality version next time.

Wiring:

First of all, the button looks like it's not all the way in. Fix that first.

Also, from your picture, it looks like the green wire isn't in the right row:

I can't tell for sure. Also, like mentioned before, you to put the button over the gap between the two sides of the breadboard.

Also, you have a pullup resistor in your circuit and you enable it on the Arduino. And your physical pullup resistor isn't connected to your signal line. And you short your signal line to ground. All of this is incorrect wiring...

If utilizing the internal pullup resistor (like you are in your code), all you should need to do for a circuit is like this:

Just be sure to connect the 5V rail to 5V and the green wire to your digital pin.

Code:

That's all fine. When doing logic with a button, be sure to debounce it.


what ftdi windows driver for arduino nano at http://www.ftdichip.com/FTDrivers.htm they seem to divide chips into two categories,  FT4222H vs. D2XX driver.

What's the correct for a arduino nano?

The Official Arduino Nano has an FTDI FT232RL.

You want to use the Virtual Com Port(VCP) Driver so the FTDI device appears as a COM port under windows.

See the getting started guide for details.


Controlling 2WD car chassis with PS3 controller I'm having trouble with controlling my car with the PS3 joystick, and there hasn't been any example codes out there. I'm using;

PS3USB library from USB_Host_shield_2.0 library
Freetronics H Bridge shield http://www.freetronics.com.au/collections/shields/products/hbridge-dual-channel-h-bridge-motor-driver-shield#.VXMqXUJJmgM

This is my code;

include <PS3USB.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB Usb;
/* You can create the instance of the class in two ways */
PS3USB PS3(&Usb); // This will just create the instance
//PS3USB PS3(&Usb,0x00,0x15,0x83,0x3D,0x0A,0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch

bool printAngle;
uint8_t state = 0;

int motora1 = 4;
int motora2 = 7;
int motoraspeed = 6;
int motorb1 = 3;
int motorb2 = 2;
int motorbspeed = 5;

void setup() {
  Serial.begin(115200);
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  if (Usb.Init() == -1) {
    Serial.print(F("\r\nOSC did not start"));
    while (1); //halt
  }
  Serial.print(F("\r\nPS3 USB Library Started"));
  pinMode(motora1, OUTPUT);
  pinMode(motora2, OUTPUT);
  pinMode(motoraspeed, OUTPUT);
  pinMode(motorb1, OUTPUT);
  pinMode(motorb2, OUTPUT);
  pinMode(motorbspeed, OUTPUT);
  delay(5000);
}

void loop() {
  Usb.Task();

  if (PS3.PS3Connected || PS3.PS3NavigationConnected) {

    //go forward
     if (PS3.getAnalogHat(LeftHatY) == 0) {
       Serial.print(F("\r\nLeftHatY: "));
      Serial.print(PS3.getAnalogHat(LeftHatY));
         digitalWrite(motora1, HIGH);
          digitalWrite(motora2, LOW);
          digitalWrite(motoraspeed, 255);
        digitalWrite(motorb1, HIGH);
        digitalWrite(motorb2, LOW);
        digitalWrite(motorbspeed, 255);
}

//go backward
if (PS3.getAnalogHat(LeftHatY) == 255) {
       Serial.print(F("\r\nLeftHatY: "));
      Serial.print(PS3.getAnalogHat(LeftHatY));
           digitalWrite(motora1, LOW);
  digitalWrite(motora2, HIGH);
  digitalWrite(motoraspeed, 255);
  digitalWrite(motorb1, LOW);
  digitalWrite(motorb2, HIGH);
  digitalWrite(motorbspeed, 255);
}

//turn left
if (PS3.getAnalogHat(RightHatX) == 0) {
       Serial.print(F("\r\RightHatX: "));
      Serial.print(PS3.getAnalogHat(RightHatX));
           digitalWrite(motora1, HIGH);
  digitalWrite(motora2, LOW);
  digitalWrite(motoraspeed, 200);
  digitalWrite(motorb1, LOW);
  digitalWrite(motorb2, HIGH);
  digitalWrite(motorbspeed, 200);
}

   //turn right
   if (PS3.getAnalogHat(RightHatX) == 255) {
       Serial.print(F("\r\RightHatX: "));
      Serial.print(PS3.getAnalogHat(RightHatX));
          digitalWrite(motora1, LOW);
  digitalWrite(motora2, HIGH);
  digitalWrite(motoraspeed, 200);
  digitalWrite(motorb1, HIGH);
  digitalWrite(motorb2, LOW);
  digitalWrite(motorbspeed, 200);
}

As of now, when I look at my code in the serial monitor, I get the following;

LeftHatY: 131
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 130
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127
LeftHatY: 131
RightHatX: 127

The numbers adjust as I'm moving the joystick around but just keeps going even though I'm not moving the joystick around. Any help would be appreciated, thanks

I found three issues:

You don't have a # before the include on line 1.
There is no } at the end of the void loop().
You forgot to include an if statement for when the joystick is idle.

Try this code:

#include <PS3USB.h>

    // Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB Usb;
/* You can create the instance of the class in two ways */
PS3USB PS3(&Usb); // This will just create the instance
                  //PS3USB PS3(&Usb,0x00,0x15,0x83,0x3D,0x0A,0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch

bool printAngle;
uint8_t state = 0;

int motora1 = 4;
int motora2 = 7;
int motoraspeed = 6;
int motorb1 = 3;
int motorb2 = 2;
int motorbspeed = 5;

void setup() {
    Serial.begin(115200);
#if !defined(__MIPSEL__)
    while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
    if (Usb.Init() == -1) {
        Serial.print(F("\r\nOSC did not start"));
        while (1); //halt
    }
    Serial.print(F("\r\nPS3 USB Library Started"));
    pinMode(motora1, OUTPUT);
    pinMode(motora2, OUTPUT);
    pinMode(motoraspeed, OUTPUT);
    pinMode(motorb1, OUTPUT);
    pinMode(motorb2, OUTPUT);
    pinMode(motorbspeed, OUTPUT);
    delay(5000);
}

void loop() {
    Usb.Task();

    if (PS3.PS3Connected || PS3.PS3NavigationConnected) {

        if (PS3.getAnalogHat(LeftHatY) == 0) { //go forward
            Serial.print(F("\r\nLeftHatY: "));
            Serial.print(PS3.getAnalogHat(LeftHatY));
            digitalWrite(motora1, HIGH);
            digitalWrite(motora2, LOW);
            digitalWrite(motoraspeed, 255);
            digitalWrite(motorb1, HIGH);
            digitalWrite(motorb2, LOW);
            digitalWrite(motorbspeed, 255);
        } else if (PS3.getAnalogHat(LeftHatY) == 255) { //go backward
            Serial.print(F("\r\nLeftHatY: "));
            Serial.print(PS3.getAnalogHat(LeftHatY));
            digitalWrite(motora1, LOW);
            digitalWrite(motora2, HIGH);
            digitalWrite(motoraspeed, 255);
            digitalWrite(motorb1, LOW);
            digitalWrite(motorb2, HIGH);
            digitalWrite(motorbspeed, 255);
        } else if PS3.getAnalogHat(RightHatX) == 0) { //turn left
            Serial.print(F("\r\RightHatX: "));
            Serial.print(PS3.getAnalogHat(RightHatX));
            digitalWrite(motora1, HIGH);
            digitalWrite(motora2, LOW);
            digitalWrite(motoraspeed, 200);
            digitalWrite(motorb1, LOW);
            digitalWrite(motorb2, HIGH);
            digitalWrite(motorbspeed, 200);
        } else if (PS3.getAnalogHat(RightHatX) == 255) { //turn right
            Serial.print(F("\r\RightHatX: "));
            Serial.print(PS3.getAnalogHat(RightHatX));
            digitalWrite(motora1, LOW);
            digitalWrite(motora2, HIGH);
            digitalWrite(motoraspeed, 200);
            digitalWrite(motorb1, HIGH);
            digitalWrite(motorb2, LOW);
            digitalWrite(motorbspeed, 200);
        } else { //stop moving
            Serial.print(F("\r\RightHatX: "));
            Serial.print(PS3.getAnalogHat(RightHatX));
            Serial.print(F("\r\nLeftHatY: "));
            Serial.print(PS3.getAnalogHat(LeftHatY));
            digitalWrite(motora1, LOW);
            digitalWrite(motora2, LOW);
            digitalWrite(motoraspeed, 0);
            digitalWrite(motorb1, LOW);
            digitalWrite(motorb2, LOW);
            digitalWrite(motorbspeed, 0);
        }
    }
}


Detect when RFID card is absent I am trying to build a mobile device that turns itself on when removed from its usual location. I am attempting to do this with an Adafruit PN532 RFID reader and a MiFare card. Using the sample code I can detect when the card is present

success= nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
Serial.println("Scanning");
if (success){
  Serial.println("FOUND");
}

However, when I try to detect the absence of the card using the following code it will tell me "Present" over and over (since its in the Loop) while the RFID card is present but when it is removed it stops printing "Present" but never prints "Card Gone"

success= nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);
    Serial.println("Present");
    if (!success){
      Serial.println("Card Gone");
    }

Is this a function of how Im using ! or is there something else at play here? I have found very few suggestions regarding detecting the absence of an RFID card and none of them seem to provide any useful answer. Most suggest some other hardware methodology as the solution. That is not the type of answer Im interested in for the moment. I would simply like to figure out why my code is incorrect.

First, your code isn't structured properly. It should be:

success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

if (success)
  Serial.println("Present");
else
  Serial.println("Card Gone");

From what I could find in the library, the reason you aren't getting either the 'Card Gone' or 'Present' message when there is no card is because nfc.readPassiveTargetID() is a blocking function. It will wait forever until a tag is detected, at which point it returns to the caller. When you bring a card within the reader's range, the function returns quickly and loop() runs smoothly, giving you the 'Present' message over and over again. When you remove the card however, on the next call of nfc.readPassiveTargetID(), the function tries to locate a card but finds none and then it keeps trying and does not return. So loop() never gets past that point, until you bring a card within range again.

To detect the presence or absence of something, an observer must observe for some pre-determined period of time before making a decision. So, I suggest you get the latest version of this library which gives you the option of adding a milliseconds timeout argument to nfc.readPassiveTargetID(). That way, you can specify how long you want the function to try detecting a card before concluding there is no card and returning.

Alternatively, you could use your existing function as is but in setup() you need to set the maximum number of re-tries before the nfc.readPassiveTargetID() returns. This is done with setPassiveActivationRetries(). Any argument from 0x00 to 0xFE indicates a finite number of tries, while 0xFF is to wait forever:

nfc.setPassiveActivationRetries(0x9A); // for example
nfc.SAMConfig();  // this comes next

Good luck.


Atmel STK500 and Atmel Studio Is the Atmel STK500 worth using as a AVR programmer and Dev board? I am starting to get to into AVR programming with Atmel studio. I plan on purchasing the AVRDragon and also looking into purchasing the Atmel STK500. This might be too broad of a question, but are their any benefits in using the Atmel STK500?

Atmel STK500

Benefits of STK500? Sure:
- It has push buttons
- It has LEDs
- It has easy accessible connectors to any controller pin

Actually that's all. If you want/need to make use of this, buy both. Use the STK for "rapid prototyping" and the Dragon for debugging.
But if your budget allows it, have a look at the STK600 instead of 500. It's more expensive, but not so "old-fashioned", and it has much more features.


Arduino: Breadboards and PCBs I just watched this excellent video tutorial that shows a simple Arduino program that toggles an LED via a pushbutton. Very cool!

In the video, the author is using a breadboard for prototyping his circuit. What's the next "step up" from this? In other words, say I get my breadboard circuit working perfectly, is it now time to create a PCB? If my understanding of circuitry is correct, this is not a trivial process. I would need a CAD program to design my circuit, and it would likely be very expensive to get the design actually fabricated. At least too expensive for simple hobby purposes. Is there a middle ground between breadboard and PCB?

You can build your project on stripboard (aka Veroboard, which is a particular brand). The wiki page at http://en.wikipedia.org/wiki/Stripboard covers most of the salient points - it is essentially a generic PCB. You can cut tracks, either with a knife, or a specialized tool, and you can solder your parts on to the tracks.

They come in various configurations - my personal preference is just straight strips - and you can cut them to size with a hacksaw.

If your project is non-trivial, you might still like to spend some time working out a decent layout. There are free, and not quite free, products to help you - I use Kicad, which is free & opensource, there are many others.

I have also used stripboard to group a few components together - for example, 2 7-segment displays and two SIPO chips to run them - this can then be a "component" for future bread-board projects.


Sweep with two shift registers I am working with 8 dual color LED's and 2 shift registers. My connections are in place. But I do not understand how to work with 2 shift registers.

So I am trying to make this: turn the first led on, turn the first led of, go to the next led, turn it on, turn in off, etc...

I do not know how to jump from the first shift register to the second shift register when the last LED of the first shift register is turned off.

Exactly the same as when you're trying to keep them dark when lighting an LED with the first register: shift two bytes.

The first byte shifts into the first register to begin with, and then out of the first register and into the second register when you shift the second byte into the first register. Just make sure only the appropriate bits are set in both bytes and you're good to go.


Compile `.hex` files on Linux I build .hex files for Arduino. How can I do this in Linux? I use the Linux distro  Mint 17.2.

I need a program to make [.hex files] (in Linux).

Can anyone help me?

You can download the Arduino IDE for Linux from the Arduino site.

As mentioned in Where are the hex files compiled by Arduino?, in the Arduino program: go to Arduino -> Preferences and then select Show verbose output during -> compilation.

  Finally, when you are compiling, the program will show you lots of
  data. At the last lines, you will find the path to the .hex file
  (Every time the path changes!).

If you want to upload this .hex file to your ATmega328P (the micro controller inside Arduino Uno), avrdude can do that for you.

Here, are few useful links:

Setup Avrdude on Linux
Programming your chip
Choosing a Programmer
Uploading your .hex file


Using PROGMEM to store array of structs I am hitting the limits of my arduino's SRAM and found that SRAM usage can be reduced by storing static stuff in flash memory instead of SRAM.

My project can (optionally) be built with an included SimulatorClass. I use this to 'playback' data at home which I gathered during real-life testing of my project. My project is based on photoelectric sensors, and it's timing-critical, so all timekeeping is done using micros(), which returns unsigned long datatype.

To simulate these photoelectric sensor triggers, I need an array containing a struct of 3 variables each:
unsigned int _iDataPos;

   struct SimulatorRecord
   {
      uint8_t iSensorNumber;
      unsigned long lTriggerTime;
      uint8_t iState;
   };

So one these structs is 6 bytes long in my counting (2x uint8_t = 2 bytes, unsigned long = 4 bytes).
A typical set of simulator records I need to use is about 25-30 records long, so worst case scenario the simulator array is 180 bytes in size.

I initialize these arrays like so:

SimulatorRecord SimulatorQueue[28] = {
      { 1, 41708, 1 }
      , { 2, 60692, 1 }
      , { 1, 176848, 0 }
      , { 2, 197732, 0 }
      , { 1, 4675580, 1 }
      , { 2, 4692252, 1 }
      , { 2, 4830180, 0 }
      , { 1, 4849032, 0 }
      , { 2, 9058416, 1 }
      , { 1, 9074780, 1 }
      , { 1, 9215868, 0 }
      , { 2, 9234968, 0 }
      , { 2, 13497276, 1 }
      , { 2, 13500924, 0 }
      , { 2, 13502728, 1 }
      , { 1, 13514992, 1 }
      , { 1, 13668000, 0 }
      , { 1, 13669344, 1 }
      , { 1, 13681828, 0 }
      , { 2, 13701464, 0 }
      , { 2, 18028788, 1 }
      , { 2, 18034252, 0 }
      , { 2, 18036540, 1 }
      , { 1, 18046892, 1 }
      , { 2, 18160312, 0 }
      , { 1, 18178224, 0 }
      , { 1, 20454580, 1 }
      , { 1, 20456368, 0 }
   };

In my simulator code I then loop through these arrays like so:

   unsigned int _iDataPos = 0;
   SimulatorRecord PendingRecord = SimulatorQueue[_iDataPos];

   //main simulator loop
   if (PendingRecord.lTriggerTime <= lRaceElapsedTime)
   {
      //simulate signal
      digitalWrite(PendingRecord.iSensorNumber, PendingRecord.iState);

      //And increase pending record
      _iDataPos++;
      PendingRecord = SimulatorQueue[_iDataPos];
   }

Now I've been reading various PROGMEM tutorials, and storing the SimulatorQueue array in flash seems to be piece of cake, just change

SimulatorRecord SimulatorQueue[28]

to

const PROGMEM SimulatorRecord SimulatorQueue[28]

But for the life of me I can't find out how I should change the copying of each array item to the PendingRecord variable, as my iDataPos counter increases.

Edit: I should have mentioned that this simulator class and all it's member functions & variables reside in a seperate *.cpp and *.h file.
I alreadt found out that since i'm initializing the SimulatorQueue array in the class itself, and not in the main *.ino file, I should do it like so:

constexpr static SimulatorRecord SimulatorQueue[28] PROGMEM = {<structs go in here>};

Edit2: Sample code which reproduces the problem when the simulator array is available here:
http://1drv.ms/1TRwiIB

An easy way of accessing any type of data in PROGMEM is to use this small library:

PROGMEM_readAnything.h

#include <Arduino.h>  // for type definitions

template <typename T> void PROGMEM_readAnything (const T * sce, T& dest)
  {
  memcpy_P (&dest, sce, sizeof (T));
  }

template <typename T> T PROGMEM_getAnything (const T * sce)
  {
  static T temp;
  memcpy_P (&temp, sce, sizeof (T));
  return temp;
  }

You can put that file into a new tab in your IDE, or make a library by putting it inside a folder called PROGMEM_readAnything and put that folder inside the libraries folder, which is inside your sketchbook folder.

That lets you copy from the memory in PROGMEM (using memcpy_P) into RAM. The template is used to work out how many bytes to copy.

Example, using your structure:

#include <PROGMEM_readAnything.h>

struct SimulatorRecord
{
  uint8_t iSensorNumber;
  unsigned long lTriggerTime;
  uint8_t iState;
};

const SimulatorRecord SimulatorQueue[28] PROGMEM = {
      { 1, 41708, 1 }
      , { 2, 60692, 1 }
      , { 1, 176848, 0 }
 //    ...   omitted for brevity
      , { 1, 18178224, 0 }
      , { 1, 20454580, 1 }
      , { 1, 20456368, 0 }
   };

// number of items in an array
template< typename T, size_t N > size_t ArraySize (T (&) [N]){ return N; }

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

  for (int i = 0; i < ArraySize (SimulatorQueue); i++)
    {
    SimulatorRecord thisItem;
    PROGMEM_readAnything (&SimulatorQueue [i], thisItem);
    Serial.print (i);
    Serial.print (F(" = "));
    Serial.print (thisItem.iSensorNumber);
    Serial.print (F(" / "));
    Serial.print (thisItem.lTriggerTime);
    Serial.print (F(" / "));
    Serial.print (thisItem.iState);
    Serial.println ();
    }  // end of for loop
}  // end of setup

void loop ()
{
}  // end of loop

I found that it decreased RAM usage by 166 bytes, which is almost 28 * 6 (a couple of bytes must have been used by something).

Reference

Putting constant data into program memory (PROGMEM)

Putting PROGMEM into a class

In response to some comments below, this explains how to put the constants into a class.

Alex originally had:

class SimulatorClass
{

...

   typedef struct SimulatorRecord
   {
      uint8_t iSensorNumber;
      unsigned long lTriggerTime;
      uint8_t iState;
   } SimulatorRecord;

   constexpr static SimulatorRecord SimulatorQueue[28] PROGMEM = {
      { 1, 41708, 1 }
      , { 2, 60692, 1 }
   //    ...   omitted for brevity
      , { 1, 20454580, 1 }
      , { 1, 20456368, 0 }
   };

   SimulatorRecord PendingRecord;
};

Putting aside whatever "constexpr" is, you can't put constants inside a class like that. You need to make it static, and have the actual definition elsewhere. So, change the constants to:

class SimulatorClass
{

...

   typedef struct SimulatorRecord
   {
      uint8_t iSensorNumber;
      unsigned long lTriggerTime;
      uint8_t iState;
   } SimulatorRecord;

  static const SimulatorRecord SimulatorQueue[28] PROGMEM ;

  SimulatorRecord PendingRecord;
};

Now in your main class file (Simulator.cpp in your case):

 const SimulatorClass::SimulatorRecord SimulatorClass::SimulatorQueue[28] PROGMEM = {
    { 1, 41708, 1 }
    , { 2, 60692, 1 }
   //    ...   omitted for brevity
    , { 1, 20454580, 1 }
    , { 1, 20456368, 0 }
   };

That now compiles OK.


Obtain retained MQTT message I’m using ESP8266 with Arduino code. Each device posts a ‘state’ and an ‘avail’ messages for a specific topic.

I wish to be able to read those retained messages and not only right after connecting and subscribe to MQTT broker.

EDIT 1  - Clarifications

I'm using Raspberry Pi Zero W as a MQTT Broker ( Local ).
When device boots, it changes its state from offline to online, but a different process checks periodically if state is offline or online for current device and others on the network.
it is not same as when subscribing to a retained topic, that you get the state at that specific time.
Storing chage of state in a variable, is one way to do it, but is there a different way ?

Once a message has passed through an MQTT broker there is not a way to retrieve it from the broker.

Consider instead deciding upon the action at the time the message is received by the subscriber.  If this decision needs to be made at a later time consider storing the state in the of the payload of the message on the subscriber.

Also consider running Node-RED.  If the platform running the MQTT broker can support Node-RED (such as a Raspberry Pi), it turns out to be convenient to run both on the same computer.  Node-RED contains nodes (graphical programming blocks) which can subscribe to and publish to MQTT topics.  By connecting other nodes to these, the topic and payload can be manipulated.  Of interest is an option within the Output MQTT node.  Here you can select Retain True.  This page explains how this option works:

  Once you have sent a retained message to a topic, all subscribers will
  receive that message when they subscribe.

  To clear a previously retained topic from the broker, send a blank
  message to that topic with the retain flag set.


How to publish on Pubnub with node mcu? I have node mcu and i am trying to use the example code on github and pubnub blog to send a msg as an experiment but can't figure how to do it.

I used 2 example as the reference - https://github.com/pubnub/arduino , https://www.pubnub.com/docs/arduino/data-streams-publish-and-subscribe

Here is the code which i have. I modified it to include some libraries and my API keys. Let me know what changes i have to make:-

#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP

#include <PubNub.h>

String pubkey = "pub-c-4a9cdbca-5688-4939-a852-f63cf6743980";
String subkey = "sub-c-9b4067ae-1293-11e9-b4a6-026d6924b094";
String pubchannel = "sec-c-NmFiYjliODYtMTc3Mi00YTMzLTg0OWMtMDgzYjE2ZGUwNzg5";

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(9600);

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(pubkey, subkey);
}

void loop() {
    /* Maintain DHCP lease. For other HW, you may need to do
       something else here, or maybe nothing at all. */

    /* Publish message. You could use `auto` here... */
    PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);
    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`.
    */
    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
        }
    }
    sclient->stop();

    delay(1000);
}

Error:-
node_mcu_test_code:44:46: error: 'subchannel' was not declared in this scope

     PubSubClient *sclient = PubNub.subscribe(subchannel);

                                              ^

node_mcu_test_code:54:14: error: 'class PubSubClient' has no member named 'stop'

     sclient->stop();

              ^

exit status 1
no matching function for call to 'PubNub::begin(String&, String&)'

The pubchannel and subchannel can be defined as any values in char variable.

Here is the right code:-

const char * pubkey = "publisher key from your account";
const char * subkey = "subscriber key from your account";

const char * pubchannel = "demo_keyset";
const char * subchannel = "demo_keyset";

Then the error disappeared


High power consumption of ATmega32u4 when connected to iOS device Just wondering if I can get some help here.

I have a simple scheme of MIDI controller based on ATmega32u4:
ATmega32U4 with TXLED and RXLED as output pins and USB functionality

And my team wants me to make this device Android/iOS compatible (because our Arduino prototypes worked fine with iPads and even iPhones).

I am experiencing a high power consumption of ATmega32u4 when connected to iOS devices. When we connect our device to iOS we get the following message:

Meanwhile, when I make almost the same scheme and run the identical sketch on ATmega328 chip it works just fine!

I tried running all the stuff on Arduino boards, and the result is stable:

works on Arduino Uno and Arduino Mega (based on ATmega328 chip);
doesn't work on Arduino Micro and some of its Chinese clones like Arduino Micro Pro (based on ATmega32u4).

We've found a small trick/workaround: connect even two our ATmega32u4 devices through an active USB hub with additional power supply to one iPad, and they both work perfectly, then we switch off the additional power on the hub, and devices continue to work fine using the power from this single iPad without any messages about high power consumption.
This case leads me to the thought that high consumption of ATmega32u4 chip appears only on the device initialisation stage.

Is there a way to solve this?

Thanks in advance.

The major difference between ATmega32u4 and ATmega328 is that the former has USB functionality built in, while the latter requires an external USB to UART chip. When such UART chips go through enumeration, they will tell the host that they only consume 100 mA or less, because they have no idea what else you have on the board. ATmega32u4 however can potentially consume up to 200 mA (sinking 100 mA through each of the IO banks). Maybe it's requesting that current from the host when you connect it, and your phone refuses to power up a device requesting more than 100 mA of current.

You can connect your controller to a computer and check USB properties to confirm this.


Any disadvantages on using Particle Photon over an Arduino? It seems to me like Photon is 'winning' on the price front and ease of programming and of course the cheap wifi connection.

I realize the cloud portion (even the local cloud server) could be considered a disadvantage, but what about things like ability to drive dc/stepper motors or some exotic sensor? Perhaps not enough analog and/or digital pins? etc..

One disadvantage I can think of is the lack of resources whereas the Arduino has a ton of references online with working with all kinds of motors and sensors.

Photon advantages:

The photon has cloud compatibility and wifi access. The Arduino doesn't without a separate shield.

A photon  about 1/4 the size of an Arduino UNO

Photon is much cheaper than arduinos

Arduino UNO advantages:

Arduino UNO has 5 volt AND 3.3 volt while Photon has only 3.3 volt

Arduino has many resources while Photons don't since Photons are fairly new

Arduinos don't need any wifi to work while Photons need to be connected to wifi and the cloud to flash code (Although there is a way to flash over USB cable, it is HIGHLY complicated with need of the terminal and DFU-UTIL installed.)

UNO has 5 analog, 13 digital ports while Photon has only 5 analog, 7 digital

UNOs have female pins, so no breadboards are necessary for small, simple projects.
Photons have male pins, and they need to be plugged into a breadboard or soldered.

Personally, I have both an UNO and a photon. Photons are useful for small and more compact projects, while Arduinos are for projects on a bigger scale. Unless you specifically need access to the cloud or access to WIFI, I would suggest buying the Arduino. Good luck!


I am getting an error while trying to set up the U8g2 library I am just trying to set up the U8g2 library to use an OLED. I read through the documentation and tried copying and pasting the code block example for the constructor, but switched out their information for my OLED's information. After trying to verify, the IDE returned this error:
exit status 1
expected ')' before ',' token
#include <SPI.h>
#include <U8g2lib.h>

//Constructor
U8G2_SSD1306_128X64_NONAME_1_SW_I2C(U8G2_R0,A5,A4);```

I saw a similar post about this problem from four years ago, but the only suggestion on there was to capitalize the "A" in the analog pins. I tried this and nothing changed. Any help would be much appreciated!

I figured out what I was doing wrong. I was copying the name from the Constructor Reference and immediately inputting the arguments in parentheses. I needed to put u8g2 after the constructor name and then put the arguments. Thanks!
The corrected code is as follows:
#include <Arduino.h>
#include <SPI.h>
#include <U8g2lib.h>

//Constructor
U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0,A5,A4);


What does this error mean?? Arduino Due loop warning I am getting this error on compilation of the code given further below;

warning: iteration 3u invokes undefined behavior [-Waggressive-loop-optimizations]
leds[XY (x, y)].r = redarray[x][y];
note: containing loop
for(uint8_t x=0; x < MatrixWidth; x++){

Code:
 // the header files for the RGB data

#include <FastLED.h>
#include "redarray.h"
#include "greenarray.h"   //g data header file (hex or dec)
#include "bluearray.h"   //b data header file (hex or dec)*/

 //matrix parameters

#define MatrixWidth 36 //columns (x)
#define MatrixHeight 1 //rows (y)
#define numled (MatrixWidth * MatrixHeight)

//pin details

#define datapin 7

#define clockpin 8

CRGB leds[MatrixWidth * MatrixHeight];

const bool  MatrixSerpentineLayout = true;

void setup() {

   FastLED.addLeds<APA102, datapin, clockpin>(leds,numled);
   FastLED.clear();
         }

void loop() {
   for(uint8_t y=0 ; y<1 ; y++){
     for(uint8_t x=0; x < MatrixWidth; x++){
         leds[XY (x, y)].r = redarray[x][y];
         leds[XY (x, y)].g = 0;
         leds[XY (x, y)].b = 0;

         FastLED.show();
         delay(50);
     }
   }
 }

  uint16_t XY( uint8_t x, uint8_t y)
  {
      uint16_t i;

      if( MatrixSerpentineLayout == true) {
          if( y & 0x01) {
          // Odd rows run backwards
          uint8_t reverseX = (MatrixWidth - 1) - x;
          i = (y * MatrixWidth) + reverseX;
    } else {
         // Even rows run forwards
         i = (y * MatrixWidth) + x;
    }
}
   return i;
}

The following is redarray header -
//RED
const byte redarray[3][36] PROGMEM = {
{0x00,  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
};
How to remove this warning. The redarray is not being read properly by arduino. THe above code should make the 36 LEDs turn off (black) as per the header file. They are randomly lit red... I am totally perplexed!
Plz help if somebody can.
Thanks!

MatrixWidth is 36. redarray[] has 3 elements. The compiler has detected that your code will likely blow up on the 4th go through the loop. Make sure your code is accessing the dimensions correctly.


Counting loops or if..else What I would like to do is,
 step 1:

led1 fades from black(off) to green (max-on 255)
led2 fades from black(off) to red (max-on 255)

this happens at the same time.
If the max value is reached, then both leds fade out (to black, off)
so step 2:

led1 fades from green to black
led2 fades from red to black

Then step 3, almost same as step 1 but opposite colours:

led1 fades from black(off) to red(max-on 255)
led2 fades from black(off) to green(max-on 255)

And step 4, both fade to black

led1 fades from green to black
led2 fades from red to black

This is the code that fades led 1/3/5 from red to black and back to red
and led 2/4/6 from green to black, and back.

#include <FastLED.h>
    #define NUM_LEDS 6
    #define DATA_PIN 3

        CRGB leds[NUM_LEDS];

           void setup() {
               Serial.begin(9600);
       FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
   }

       void loop()
{

  int x = 1;
   for (int i = 1; i > -1; i = i + x){

     leds[0] = CRGB(i,0,0);
     leds[1] = CRGB(0,i,0);
     leds[2] = CRGB(i,0,0);
     leds[3] = CRGB(0,i,0);
      Serial.println(i);
      FastLED.show();
      if (i == 55) x = -1;             // switch direction at peak
      delay(100);

   }
}

****Original question****

  I am trying to fade a led (WS2812B) from black to green or red, and
  back to black. (that is working)  But now I want the same led fading
  to blue.

  How could I do that? I was trying a if..else but can't figure it out
  Or should I count the for loops?

  This is the starting code I am using

  maybe something like

    if (i==0)
{
             leds[0] = CRGB(i,0,0);
             leds[1] = CRGB(0,i,0);
             leds[2] = CRGB(i,0,0);
             leds[3] = CRGB(0,i,0);
}
    else
{
             leds[0] = CRGB(0,0,i);
             leds[1] = CRGB(0,0,i);
             leds[2] = CRGB(0,0,i);
             leds[3] = CRGB(0,0,i);
}
              FastLED.show();
              if (i == 100) x = -1;
              delay(100);

  But that is not working. Any suggestions?

I would do that based on the clock. This lets you run each one independently.

On the off-chance that your project runs that long, the clock rolls over (resets) every 50 days.

I'm going to assume the 55 in your code should read 255.

I would do something like this (this is a code snippet, but should get you started):

const int phase_milliseconds=2500; // each phase lasts 2.5 seconds.
const phase_progress_length=256;   // each phase goes from 0 to 255
const phases=4;                    // numbered from 0 to 3, will repeat forever.

// This is the time since your Arduino turned on
unsigned long time=millis();
// how far we are through the current phase?
int progress= time%phase_milliseconds)*phase_progress_length/phase_milliseconds;

// which phase are we in?
int phase=(time/phase_milliseconds)%phases;

if (phase==0) { // first step
         leds[0] = CRGB(progress,0,0);
         leds[1] = CRGB(0,progress,0);
} else if (phase==1) { // second step
         leds[0] = CRGB(255-progress,0,0);
         leds[1] = CRGB(0,255-progress,0);
} else if (phase==2) { // third step step
         leds[0] = CRGB(0,progress,0);
         leds[1] = CRGB(progress,0,0);
} else if (phase==3) { // fourth step
         leds[0] = CRGB(0,255-progress,0);
         leds[1] = CRGB(255-progress,0,0);
}

Since this is time based, it doesn't matter much how often it runs, you don't need a delay (you can still put one in if you like). You can extend this to more steps.

Also note that I rattled this off, off the top of my head, so there may be errors.


Can I use an ATmega328 alone without anything and what is the max voltage I can power the atmega328 with Okay 2 questions. If I am to replace the Arduino with an ATmega328 programmed with a standard blink on pin 13, is this configuration correct, do I still need oscillators and whatnot?

Second question is, what is the max voltage I can power the ATmega328 with without frying it? I have seen conflicting answers of this on the net. Some have said 5V while some say 6V can someone clarify?

The datasheet describes the electrical and clock requirements of the chip, and AVR042 describes the external hardware configuration required. Decoupling, analog voltages, external crystal or oscillator if required.


Fading LED with different frequencies I have a potentiometer attached to one analog port of arduino (assume A0)
I'm reading the value of that using input_voltage = analogRead (A0); which is a value between 0-1023.
So I want to map this value to frequency from 1Hz to 20Hz. Then I want to fade my LED using this frequency.
Tried to doing this map using int frequency = map (input_voltage, 0, 1023, 1, 20);
But how can i apply this frequency to LED?
I mean PWM has a constant frequency (about 500Hz). How should I apply frequencies from 1 to 20 to this LED in order to fade it?

There is a library in which you can change the frequency

Here is my example code I did long time ago I had the same problem

Get the library from here

https://github.com/atmelino/Arduino/tree/master/libraries/PWM

Go ahead and try example code there and try to understand too.

Include the library first to code

my code

void setup() {
  pinMode(13, OUTPUT);
  pinMode(8, OUTPUT);
  digitalWrite(8,LOW);
  Serial.begin(115200);
  InitTimersSafe();
}
void loop() {
  //mapping
  long x = map(analogRead(A0),0,1023,1,20);
  bool b = SetPinFrequencySafe(9,x);
  digitalWrite(13,b);
  pwmWrite(9,127);
  Serial.print(x);
  Serial.print(" Hz ");
  Serial.println(b);
  delay(100);
}

Built in led will turn on if the frequency is stetted.

By the way led will turn on in 50% on and 50% off in one cycle in pin 9.

Use only the PWM pins in Arduino 3,9,6 etc.

Now you can change the PWM frequency...

I just put a led in the female socket in for easiness + terminal in 9 and - terminal in 8 to go to ground that's why I did put pin 8 to low.


Bredboard board in new release I had installed the old release (1.0.5) but for some reasons arduino stops working and I upgraded to new version 1.8.2, all works fine but I would like to use the bredboard 8Mhz version in the new release, but the boards system is not compatible with new version. The boards.txt is this:

##############################################################

atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=stk500
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=57600

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05
atmega328bb.bootloader.path=arduino:atmega
atmega328bb.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328p
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

How to build it to be compatible with news version? Thank you

I found a solution in this video:

https://www.youtube.com/watch?v=cebMSJrNntI

Adding:

##############################################################

atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=arduino
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=57600

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05

atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328p
atmega328bb.build.board=AVR_ATMEGA328BB
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

atmega328bb.bootloader.tool=arduino:avrdude
atmega328bb.upload.tool=arduino:avrdude

to /hardware/arduino/avr/boards.txt


My Code turns on my LED even when my switch is not pressed I am trying to create a circuit that will turn my motor when I clap. When the first limit switch is low, and there is only one clap, a solenoid pin is supposed to be engaged (currently an LED), but when I clap once without pressing the limit switch, my LED turns on.

Also, I can't seem to get my code to work properly with the limit switches, to control my motor.

I am not sure what is wrong, can someone help?

I have an Arduino Uno with the following code:

#define sound_Sensor 2
#define EN1 9
#define IN1 8
#define IN2 7
#define solenoid_pin 6
#define LimSwitch1 4
#define LimSwitch2 3

int lastSoundValue;
int soundValue;
long lastNoiseTime = 0;
long currentNoiseTime = 0;
int solenoidPinStatus = LOW;
int status_motor = LOW;
int clap_interval = 200;
int claps = 0;
int pos1 = 1;
int pos2 = 1;

void setup() {
  pinMode(sound_Sensor, INPUT);
  pinMode(EN1, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(solenoid_pin, OUTPUT);
  pinMode(LimSwitch1, INPUT);
  pinMode(LimSwitch2, INPUT);
}

void loop() {

  soundValue = digitalRead(sound_Sensor);
  currentNoiseTime = millis();
  if (soundValue == 1 && lastSoundValue == 0 && (currentNoiseTime > lastNoiseTime + 200))
  {
      if (claps == 0) // allow first to register without much condition
      {
          claps = 1;
          lastNoiseTime = currentNoiseTime;
      }
      else
      {
          if (currentNoiseTime > lastNoiseTime + clap_interval)
          {
              claps++;
              lastNoiseTime = currentNoiseTime;
          }
      }
      Serial.print(claps);
  }
  else
  {
      if (currentNoiseTime > (lastNoiseTime + 3 * clap_interval)) // no claps for a longer duration time to print and/or reset clap
      {
          if (claps > 0)
          {
              while(status_motor == LOW){
                  if (digitalRead(LimSwitch1) == LOW && claps == 1)
                  {
                    solenoidPinStatus = HIGH;
                    digitalWrite(solenoid_pin, HIGH);
                  }

                 if (digitalRead(LimSwitch1) == LOW)
                 {
                    pos1 = 2;
                    status_motor = HIGH;
                    digitalWrite(IN1, HIGH); //Turns on Motor
                    digitalWrite(IN2, LOW);
                    analogWrite(EN1, 200); //Set Speed of Motor
                  }
                 else if (digitalRead(LimSwitch2) == LOW)
                 {
                    pos2 = 2;
                    status_motor = HIGH;
                    digitalWrite(IN1, HIGH); //Turns on Motor99++
                    digitalWrite(IN2, LOW);
                    analogWrite(EN1, 200); //Set Speed of Motor
                 }
              }

              while(status_motor == HIGH){
                if (pos1 == 2 && digitalRead(LimSwitch2) == LOW)
                {
                    status_motor = LOW;
                    digitalWrite(IN1, LOW); //Turns on Motor
                    digitalWrite(IN2, LOW);
                    pos1 = 1;
                }

                else if (pos2 == 2 && digitalRead(LimSwitch1) == LOW)
                {
                    status_motor = LOW;
                    digitalWrite(IN1, LOW); //Turns on Motor
                    digitalWrite(IN2, LOW);
                    pos2 = 1;
                }
              }
          }
             claps = 0; ///reset
      }
  }

// if (solenoidPinStatus == HIGH && status_motor == LOW && digitalRead(LimSwitch1) == LOW)
// {
//   solenoidPinStatus = LOW;
//   digitalWrite(solenoid_pin, LOW);
// }
  lastSoundValue = soundValue;
}

Sorry my wire diagram may not be the easiest to look at...

I think your problem might be connected to wiring.

This is one of the ways you can correctly connect a switch to Pin 8.

In this case you need to configure Pin 8 as INPUT_PULLUP to use internal "pullup" resistor. When switch is not pressed Pin8 is connected to 5V through that resistor and value on the pin is HIGH. When you press the switch it connects Pin 8 to ground (the resistor prevents a short) and that way value on Pin 8 is LOW.

This is code that works correctly with the design above

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

void loop()
{
  if (digitalRead(8) == HIGH)
  {
    Serial.println("It's HIGH");
  }
  else
  {
    Serial.println("It's LOW");
  }

  delay(1000);
}

If you do not configure Pin 8 as INPUT_PULLUP but just normal INPUT (as you did in your code) when the button is not pressed Pin 8 is "floating" (it's not connected to anything) and on a "floating" pin values are random.


arduino and gsm module receive Can you help me with the codes? I have gizduino(arduino clone), i used the codes in receiving sms from the internet but what i receive is a symbol "y" with two dots at the top. Whats wrong?

My gsm is set to suart.

// Example 55.4

#include <SoftwareSerial.h>
SoftwareSerial SIM900(2,3);

char incoming_char=0;

void setup()
{
  Serial.begin(19200); // for serial monitor
  SIM900.begin(19200); // for GSM shield
  SIM900power();  // turn on shield
  delay(20000);  // give time to log on to network.

  SIM900.print("AT+CMGF=1\r");  // set SMS mode to text
  delay(100);
  SIM900.print("AT+CNMI=2,2,0,0,0\r");
  // blurt out contents of new SMS upon receipt to the GSM shield's serial out
  delay(100);
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void loop()
{
  // Now we simply display any text that the GSM shield sends out on the serial monitor
  if(SIM900.available() >0)
  {
    incoming_char=SIM900.read(); //Get the character from the cellular serial port.
    Serial.print(incoming_char); //Print the incoming character to the terminal.
  }
}

Most probably you are using sim900 or sim800 module. These modules would be either fixed to a certain baudrate like 9600 or 115200, OR the module might be at auto-baud mode.

In auto baud mode you need to send AT\r to the modem after the modem is switched ON so it can know what baud you are using.

Please check the following...

GSM Modem/Module not responding to AT commands after firmware Upgrade??
Serial port AN


Source code for Arduino “firmware”? I am wondering if anyone here knows where the source code for the Arduino "firmware" is available for reading? I think it must be more than the 'boot loader' but I am not sure. Thanks!

p.s. I assume this kind of question is ok here, even though it's not ok on StackOverflow?

The “firmware” is whatever program a microcontroller runs. On an
Arduino, it is typically the program you write and upload into the
microcontroller's flash memory.

If by “firmware” you mean the core library (the source code of
pinMode(), digitalRead() and so on), it is here:

https://github.com/arduino/ArduinoCore-avr

If by “firmware” you mean the bootloader (the small program that runs at
reset and will accept the upload of your firmware), is is here:

https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/bootloaders/optiboot

Note that this is valid for the AVR-based Arduinos.
The cores and bootloaders used in other architectures are stored is
separate repositories, e.g.

https://github.com/arduino/ArduinoCore-sam


Recognize peak in specific frequency area I am wondering if it is possible to attach a microphone to an arduino board and make the arduino recognize a volume peak in a specific range of frecuency's.
I want it to detect a specific peak (for example 0,1 db's) in the range of 1000hz to 5000hz.
Thanks in advance.

You can filter the signal and look at the power that lies within the
frequency range you are interested about. You could use an FFT for that,
but it is quite computationally expensive. If you go for the FFT, you
would probably end up sampling the mic in small bursts (a few
milliseconds sampled every few tens of milliseconds), as the Arduino
would spend most of its time processing the data.
A better option is probably to work in the time domain, rather than the
frequency domain. If you do not need to know exactly how much power lies
in each frequency bin, and are only interested in the total power within
the window of interest, then the FFT is computing too much stuff you do
not need. A less computationally expensive option would be to run the
samples through a digital band pass filter tailored to the band you
want. You can then compute the power from the output of the filter and
low-pass it:
raw_sample = sample_the_microphone_somehow();
filtered_signal = bandpass_filter(raw_sample);
instantaneous_power = filtered_signal * filtered_signal:
smoothed_power = low_pass_filter(instantaneous_power);

But you would still need a beefy Arduino if you want to be able to
acquire and process the samples at a reasonable rate: at least twice the
highest frequency that comes out of the microphone.
A still better option could be to do the filtering in the analog domain,
before the signal reaches the Arduino. If you can at least remove the
frequency components above 5 kHz, then the Arduino would only need
to sample at 10 kS/s, and run a digital high pass filter to remove
the part of the signal below 1 kHz. This should be easy enough even
for an AVR-based Arduino.
For the implementation of the filters, you may want to try this online
filter builder


How can one use the SPI hardware on the Arduino Nano? I recently prototyped and programmed a system that used some SPI sensors on an Arduino Uno. I wanted to get the size down a bit, so I was thinking I might buy an Arduino Nano and re-wire my system around that. The problem is that I have seen mention of SPI not working on the Nano. From the Nano product page:

  These pins support SPI communication, which, although provided by the underlying hardware, is not currently included in the Arduino language.

Yet I have also seen mention of SPI working on this board, or at least people saying that it should. Someone asked a similar question on Stack Overflow and was told that it should work with the same level of support as I2C, even if it isn't built in to the core framework. But that answer does not definitively answer the question of whether SPI does work, and it doesn't explain any caveats that one may come across. In this question, the OP's premise is that their SPI device works on the Nano but not on other boards; this seems to be a strong indication that SPI does work.

I figured it would be worth it to buy a Nano 3 and see if it worked. SPI devices did not work on that board, including the same radio module mentioned in the question linked to above. So, I am inclined to believe the Arduino product page when they say it isn't supported. But that still isn't satisfactory, and it is the opposite conclusion from that of the other questions: The hardware is all there and the software framework is in place, so what does one need to do to make SPI work on the Arduino Nano? Why is it that some sources say it works while others say it doesn't?

Yes, the Nano supports SPI when used with a modern Arduino version, and no, you do not have to do anything special to utilize it on this board.

The information you found that seems to suggest something to the contrary is simply a result of the fact that that the web page for the Nano is sadly out of date date and does not reflect the current state of the Arduino libraries which support SPI on this processor and hence board.

In terms of components, the Nano it is very nearly just a form-factor shrink of the discontinued Duemilanove, and in the current version updated to an an ATmega328p it has capabilities essentially comparable to an Uno, differing primarily the in the USB interface which has nothing to do with SPI.

In terms of what is wrong with the web page, if we examine archive.org's records for the page of the comparable Duemilanvoe, on September 15th, 2010 it said:

  SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI communication, which, although provided by the underlying hardware, is not currently included in the Arduino language.

But a few days later on September 26th, 2010 it had been changed to say:

  SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK). These pins support SPI communication using the SPI library.

Although the page for that once-flagship product was updated to reflect SPI support nearly six years ago, they've not yet made a corresponding correction to the Nano page.  But as the difference is in the software and the same software is used in either case, the addition of SPI support to the Duemilanove was also automatically an addition of that support to the Nano.


How to send data to sim900 only once in loop() I am trying to communicate with a client(PC) from my arduino (set up as a server with a sim900 module connected via UART). I have successfully got it to register its IP address with a dynamic DNS provider (no-ip.com) and set up a TCP server using the AT+CIPSERVER command for the sim900. All this is done in setup(). After that in loop() it waits for a client to connect. The moment a client connects the problem arises. The code is:-

void loop()
{
  while(Serial.available() <= 0);
  int x=0;
  char server_recv_string[30];
  while(Serial.available()>0)
  {
    server_recv_string[x] =  Serial.read();
    delay(10);
  }
  Serial.println(server_recv_string);
  sendATcommand2("AT+CIPSEND",">","ERROR",1000);
  sendATcommand2("I hear you\x1A","SEND OK","ERROR",5000);
  while(Serial.available()>0)  // I dropped this in to clear out the input buffer.
  {                            // Doesn't help
    Serial.read();
    delay(10);
  }
  Serial.flush();
}

The sendATcommand2 is a function as given below. I don't think that has any fault in it because it seems to work fine for all the other commands in setup. However this is the code:-

int8_t sendATcommand2(char* ATcommand, char* expected_answer1,
    char* expected_answer2, unsigned int timeout){

    uint8_t x=0,  answer=0;
    char response[100];
    unsigned long previous;

    memset(response, '\0', 100);    // Initialize the string

    delay(100);

    while( Serial.available() > 0) Serial.read();    // Clean the input buffer

    Serial.println(ATcommand);    // Send the AT command

    x = 0;
    previous = millis();

    // this loop waits for the answer
    do{
        // if there are data in the UART input buffer, reads it and checks for the answer
        if(Serial.available() != 0 && x < 100){
            response[x] = Serial.read();
            x++;
            // check if the desired answer 1  is in the response of the module
            if (strstr(response, expected_answer1) != NULL)
            {
                answer = 1;
            }
            // check if the desired answer 2 is in the response of the module
            else if (strstr(response, expected_answer2) != NULL)
            {
                answer = 2;
            }
        }
    }
    // Waits for the asnwer with time out
    while((answer == 0) && ((millis() - previous) < timeout));

    return answer;
}

The when I monitor it on the serial terminal I get infinite sends to my client. Its like this:

 AT+CIPSEND
 I hear you

 AT+CIPSEND
 I hear you

 AT+CIPSEND
 I hear you

 AT+CIPSEND
 I hear you

 // And on and on and on.

Any idea why this is happening? If you guys need any more information, please do tell me.

Thanks

Taz

You can use a boolean variable to decide if you are going to execute the send command. You can set the variable to true in the setup and to false after the command is executed.

If you introduce the send call inside an if (your boolean variable == true), it will only be executed in one loop iteration.

You can execute it again anytime you like setting the variable to true at any moment.


How many pins does this circuit (HMC5883L) use? I've been told 2 by a friend but this looks to only use one?

https://www.adafruit.com/product/1746

Below image is the answer to your question.

According to this image, magnetometer required four pins of arduino.

GND of magnetometer ----> Arduino GND

Vcc of magnetometer ----> Arduino 3.3 Volt

SDA of magnetometer ----> Arduino Analog Pin 4

SCL of magnetometer ----> Arduino Analog Pin 5

A4, A5 on Uno are SDA, SCL, required for hardware-based I2C.

I hope it will help you.


No potential across output of H-bridge I’m working on a robot with a club at my school. So far, our team has an H-bridge shield (https://www.freetronics.com.au/products/hbridge-dual-channel-h-bridge-motor-driver-shield#.WwI9omh_WEc) to drive motors in a toy tank. The H-bridge is powered by 6 AA batteries and the arduino is powered through the H-bridge shield with these batteries also.
 When everything is connected up and  code uploaded to make the motors run forward, nothing happens - the motors don’t run. So far to debug, I’ve used a multimeter to check the voltages being output to the H-bridge from the arduino controller. These are all as expected. I’ve touched the motors to the positive and negative terminals of the battery and they run as expected. Lastly, I’ve substituted the H-bridge shield for a known working one. This did not fix the problem. I disconnected the motors and tested the voltage being output, which measured as +6V for both terminals of the motor relative to the negative terminal of the battery as well as relative to the ground pin. I also disconnected the jumper powering the arduino from the H-bridge shield and instead powered the arduino from my laptop. This did not fix the problem either. This seems completely contradictory. Any ideas on what the problem could be? Thanks so much ❤❤

It sounds either (i) like your motor driver is broken or (ii) your code does not operate the H bridge properly.  Check which digital outputs pins of the Arduino control the H bridge and make sure that they do not short out the H bridge.

If you want to try another H bridge, this one is suitable for your application: https://www.pololu.com/product/2990 .  I have worked with this before and it's very easy to use.


Arduino LED lighting up when signal is reading low on multimeter My code is designed to play a tone when ever pin 3 is high on my Arduino. When I am examine the pins voltage with a multimeter it is always reading below 1 volt. When I examined the voltage off of a osiliscope it is reading the voltage pretty steady at 0.2 to 0.3.

My multimeter reads at 0.26

:

My code is:

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
  // put your main code here, to run repeatedly:
int input = digitalRead(3);
Serial.println(input);
if(input == 1){
  tone(A5,4000);
  }
}

My board looks like:

The bottom of the board looks like:

You left pin 3 floating. The multimeter will lower the voltage, resulting the the led lighting. Try enabling the pull-up resistor in pin 3 by adding pinMode(3, INPUT_PULLUP).

PS you might want to add a resistor in series with that led, or it will burn out and/or damage pin 3 on the arduino.


Storing and sequencing output value (arduino) I am new to Arduino programming, after days and nights trying to use array,for loop and googling a lot of article, I still unable to find the way how to store each weighing output value from int Sampling() to be executed by the respective servo in sequence order.
If you have any clue to share and help me, I'll be very happy. Thank You very much.
Below is my base code.
#include <HX711.h>
///////////////////////////////////////////////////////////////////////
#define calibration_factor -251
#define LOADCELL_DOUT_PIN 7   // data
#define LOADCELL_SCK_PIN 8    // sck
////////////////////////////////////////////////////////////////////////
HX711 scale;
////////////////////////////////////////////////////////////////////////
int servo1 = 12;
int servo2 = 13;
int proxiPin1 = 2;
int proxiPin2 = 3;
////////////////////////////////////////////////////////////////////////
int toggleState = 0;
int proxiState1 = 1;
int proxiState2 = 1;
////////////////////////////////////////////////////////////////////////
int weight;
int weightFinal;
////////////////////////////////////////////////////////////////////////
void setup()
{
  Serial.begin(9600);
  scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
  scale.set_scale(calibration_factor);
  scale.tare();

  pinMode(servo1, OUTPUT); // simulating servo1
  pinMode(servo2, OUTPUT); // simulating servo2
  pinMode(proxiPin1, INPUT_PULLUP); // proximity
  pinMode(proxiPin2, INPUT_PULLUP); // proximity

}
/////////////////////////////////////////////////////////////////////////
void loop()
{
  Serial.print(Sampling());
  Serial.print(" gram");
  Serial.println();
  ///////////////////////////////////////////////////////////////////////
  if ( weightFinal == 10 )
  {
    toggleState = true;
    servo10gr();
  }

  if ( weightFinal == 20 )
  {
    toggleState = true;
    servo20gr();
  }
}
////////////////////////////////////////////////////////////////////////
int Sampling()
{
  int weight = scale.get_units();

  if (weight >= 10  && weight< 20)
  {
    weightFinal = 10;
  }

  else if (weight >= 20  && weight < 30)
  {
    weightFinal = 20;
  }

  return weight;
}
/////////////////////////////////////////////////////////////////////////
int servo10gr()
{
  proxiState1 = digitalRead(proxiPin1);
  if ( proxiState1 == 0 && toggleState == true )
  {
    digitalWrite(servo1, HIGH);  //Simulating servo signal Pin//
    delay(500);
    digitalWrite(servo1, LOW);

    toggleState = false;
    weightFinal=0;
  }
}
/////////////////////////////////////////////////////////////////////////
int servo20gr()
{
  proxiState2 = digitalRead(proxiPin2);
  if ( proxiState2 == 0 && toggleState == true )
  {
    digitalWrite(servo2, HIGH);    //Simulating servo signal Pin//
    delay(500);
    digitalWrite(servo2, LOW);

    toggleState = false;
    weightFinal=0;
  }
}

I'm still not entirely sure what you want to achieve, but maybe this will help:
You have a global variable int weight, and in int Sampling() you create another int weight = scale.get_units() which you give a value.
That second variable is only accessible inside of Sampling(). If you want to use it elsewhere for storing or in other functions, change:
int weight = scale.get_units();
to
weight = scale.get_units();
and you can then use weight wherever you like in your code, also in servo10gr() and servo20gr().
You don't need to store a sequence of weights to drive the servos; you can just use the current weight immediately to drive a servo and then get a new weight.
If, however, you want or need to keep a list of weights for some reason, there's a bit more work to be done.
There are better ways of going about this, but let's see first if this solves your problem.


How to read incoming HEX values from Serial.read() method? Brief description about the problem History
Communicating with a old VersaStat II used GPIB port but the GPIB ports PCI card stopped working but there was a another port 25 pin rs232 Serial communication port but even now, too bad computers are abending the Serial port luckily there is still virtual Blutooth COM port which can be used with a modern laptop so ESP32 microcontroller was selected to communicate with this device wirelessly (might later go for HC05 module etc.).
Fixing the voltage difference problem
Now there is a big problem the esp32 Serial uses +3.3 V or logic 1 &  0 V for logic 0 But in the rs232 port logic 0 is +3 V ~ +12 V and logic 1 is -3 V ~ -12 V  also ± 3V  undefined region. To overcome this problem I have used the following circuit with optocouplers.
Here is the circuit diagram

The following code was used to communicate with the device easy as seems
Code
#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;
int speedsend = 9600;

void setup() {
  Serial.begin(speedsend);
  Serial2.begin(speedsend);
  SerialBT.begin("ESP32SERIAL");
  delay(500);
}

void loop() {

  if (Serial2.available()) {
//incoming data from the device
    int i = Serial2.read();
    SerialBT.write(i);
    Serial.println(i); // To check what is coming as output
  }
  if (SerialBT.available()) {
    Serial2.write(SerialBT.read());
  }

}

But I see no meaningful characters in putty (Bluetooth COM port) in Arduino Serial I see some numbers in HEX representation. Is this the way old devices communicate?
This link show how HEX numbers correlate with ASCII characters
https://www.rapidtables.com/convert/number/hex-to-ascii.html
How to fix this issue am I doing something wrong in here the circuit parameters etc.
Communication Example with device
For a start the ID command should give a number as 2532 according to book after the conversion it gives me 32 32 34 32 0 0 , 2242 looking at the Arduino Serial numbers with the help of the converting web site shown in above url. That's how I noticed It gives me HEX numbers.
Here is the PDF rs232c Interface section PDF the original Book came with ID command page too.
https://drive.google.com/file/d/1BHhIsloF4voMxoFeSlz1GsjwfgHwgsPJ/view?usp=sharing
Another book looks same but not from the book came with
https://drive.google.com/file/d/1z0NUOe17SpVYTIBfEE8s0EKStfLKKv_-/view?usp=sharing

Your problem is, that you try to provide a HEX value, but you are actually providing a decimal value.
When you just write a whole number like 32, it will be interpreted by the compiler as a decimal number. The decimal number 32 is equal to HEX 20, which is a space character in ASCII.
Solution: Write your number as decimal value like this:
int i = 0x32;

The 0x preceding the value will mark it as a hexadecimal representation.


Am I multiplexing my LEDs correctly? I am new to electronics. I have a good amount of programming under my belt however.

I want to know if I am multiplexing correctly or not. My intended output is how I want it, but I am not sure if I implemented it how it's supposed to be, i.e. am I potentially damaging my equipment.

I have 6 RGB LEDs hooked up to my arduino, let's called them L1 - L6.

I have each R, G, and B pin on L1 - L3 connected in parallel, and the same for L4 - L6. Then I have ground on L1 and L4 connected in parallel, and the same for L2 to L5, and L3 to L6.

So this gives me 6 pins to supply voltage to, to which I put a 220 ohm resistor in each one. Then it gives me 3 different spots for ground.

My question is about the ground. How should I control the different 'pins' for ground.

This is what I have right now, and it works, but I don't know if this is dangerous to my equipment for some reason.

I have the 3 ground pins connected to the Arduino in 3 different pins, 7, 4, and 2.

In Setup() I configure these 3 pins as outputs, and I later found out in order to keep them all 'off' I need to set them all to high.

So then in order to turn L1 on to red, I need to turn its red pin to high, but turn its ground pin to low, then L1 turns on.

Using this same technique, I am able to get every LED to every desired color. So I mean it works. But why is this? Is this how I should be doing it? I understand LEDs polarity matters, but why would supplying its cathode with voltage make it turn off? That's the part I'm worried about, am I destroying my LEDs by doing this?

Any and all help much appreciated!

Here is how I have it all wired up for clarity.

LEDs are not powered by a particular voltage level, but by the voltage difference between anode and cathode. That's why you need to drive cathode pins (7, 4, and 2) LOW to switch the LEDs ON and HIGH to switch them off. A truth table could help:

╔═══════╦═════════╦══════════════════════════╦═══════════╗
║ anode ║ cathode ║ voltage anode to cathode ║ led state ║
╠═══════╬═════════╬══════════════════════════╬═══════════╣
║ LOW   ║ LOW     ║ 0V                       ║ OFF       ║
╠═══════╬═════════╬══════════════════════════╬═══════════╣
║ LOW   ║ HIGH    ║ - 3.3V                   ║ OFF       ║
╠═══════╬═════════╬══════════════════════════╬═══════════╣
║ HIGH  ║ LOW     ║ + 3.3V                   ║ ON        ║
╠═══════╬═════════╬══════════════════════════╬═══════════╣
║ HIGH  ║ HIGH    ║ 0V                       ║ OFF       ║
╚═══════╩═════════╩══════════════════════════╩═══════════╝

Your schematic looks safe to me, but be aware that if you decide to illuminate L1, L2 and L3 to the same color simultaneously (e.g drive red line HIGH and pins 7, 4, and 2 LOW), your LEDs will not have uniform brightness. Only one of the cathode pins should be LOW at a time, otherwise you will end up in the situation described here.


Beginners code, loop doesn't detect unplugged pin I'm learning on an Arduno UNO board, and im trying to turn a LED on three times when I connect pin 10 to ground and then turn it off. Then when I unplug the pin number 10 it should NOT blink again... yet it does and I can't find the issue.
this is the entire code:
bool ledBlinked = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(7, OUTPUT);
  pinMode(10, INPUT_PULLUP);
}

//Turns on and off a digital pin, a number of times, with a certain delay
void blinkLed(int pin, int times, int del){
  // activates a pin a number of times
  for (int i=0; i<=times; i++){
    digitalWrite(pin, HIGH);
    delay(del);
    digitalWrite(pin, LOW);
    delay(del);
  }
}

//Checks if passed pin number is connected to ground
bool pinIsGround(int pin){
  return (digitalRead(10) == LOW);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(pinIsGround(10) && !ledBlinked){ //if pin is connected to ground and the LED hasn't blinked
    blinkLed(7,3, 100); //blink pin 7, 3 times, with a delay of 100ms
    ledBlinked = true; //LED has blinked already
  }
  if (!pinIsGround(10) && ledBlinked){ //if pin is not connected to ground and the LED hasn blinked
    digitalWrite(7, LOW); //turn LED off (unnecesary?)
    ledBlinked = false; //LED hasn't blinked yet
  }

}

SInce I can coment I have to write this as answer.
there are two ways of understanding your question:
If you dont want it to ever blink again then simply remove
ledBlinked = false;
If you are trying to prevent the blinking until the button is depressed and pressed again then first think I see is the error in blinkLed function as
for (int i=0; i<=times; i++) would run times+one time. because it runs first with value of i being 0 (Eg times=4 would run for i equal 0,1,2,3,4 -> Five times ) So correction to for (int i=0; i<times; i++) would run correct number of times (Eg times=4 would run for i equal 0,1,2,3 -> four times )
Although as you are not checking status during the running of blinkLed function for the status of the button, if you release it while blink is running the script would not notice unless its still unpressed when script gets back to Loop.

Although since hardware operation take more work then logical operation I would recommend if...else statement rather then multiple hardware operations. Although they make code simpler to read
if(digitalRead(10) == LOW){
         if(ledBlinked != true)...
   } else { ...}


Which device to use to measure AC current using Arduino? I'm building a home automation product and want to measure AC current using Arduino (as of now). I've used ACS712 5A Hall Effect Current module but there's a lot of electrical noise and also the accuracy is not good. There's a lot of deflection in value when no current passes through it. I want to pack the whole kit in a box. So how to make sure that there will be no magnetic interference?

Can you suggest some other module to use for the same? Also that can last long enough.

Some sort of Current Transformer usually does the trick.  You run the AC line (not the neutral) through a ferrite core and it converts current into an output voltage.  You can find them packaged like this one with a web search.


How can i receive data from Mega2560 on PC with Visual C# How can i receive the data from my Arduino Mega 2560 with Visual C# on my PC.

I send a short databyte (2 bytes) and a timestamp (4 bytes) over USB to PC

//initialization

const int RX = 0;
const int TX = 1;

void setup(){

pinMode(RX, INPUT);   //readpin for USB
pinMode(TX, OUTPUT);  //writepin for USB
...

Serial.begin(28800);   //open interface
}

 //loop()

 Serial.print(incomingByte, BIN); //sending databyte

 sendBinary(currentMillis);   //send timestamp

//method for timestamp

void sendBinary(long currnetMillis)
 {
  int temp = currentMillis&0xFFFF;  //16 bit of the low-byte
  sendBinary(temp);
  temp = currentMillis >> 16;       //16 bit of the high-byte
  sendBinary(temp);
 }

I have surched in the internet for an example but i didn´t find a good. So i ask here what ist the best way with Visual Studio C# to receive the incoming data?
An example code will be nice because i´m a beginner and didn´t understand the jargon.

With frindly wishes sniffi

I haven't tried the code below, but it should point you in the right direction.

All you have to do is write a C# program that opens the Serial port that your Arduino is connected to and read and write from there like you would from a file.

Open Visual Studio, create a C# command line project.
Paste this code inside main()

    System.IO.Ports.SerialPort port = new SerialPort("COM1", 9600);
    try
    {
        while (true)
        {
            int readData = port.ReadByte();
            System.Console.WriteLine("Read {0} from the port", readData);
        }
    }
    catch(Exception)  // Press CTRL-C to exit.
    {
    }
    port.Close();

Compile the code and run it.


No sketches will upload to Arduino Uno board; says "access denied" I'm using an Arduino Uno board with an HP computer running Windows 10 and IDE version 1.6.8. Arduino was working fine for me until a few days ago, when (and I suspect this is the root of the problem) I accidentally tried to upload software with something connected to the RX and TX pins on the board. Now I continually get the error message below:

  avrdude: ser_open(): can't open device "\.\COM2": Access is denied.

The only other thing that changed is I disconnected a bluetooth dongle (Kinivo BTD-400 Bluetooth 4.0 USB Adapter for Windows) without uninstalling any software, so I suspect that software may be searching for open COM ports and disrupting the Arduino upload.

I've tried everything I could find about troubleshooting online, including that "did I brick my arduino" post elsewhere on this forum, and nothing has worked or even changed the problem - please help! I believe I've narrowed down the problem to my computer scanning open COM ports, but I can't find any reliable way to make sure that doesn't happen.

Thanks

It sounds like Windows thinks that port is in use and isn't letting the ArduinoIDE access it. If it's the same port your dongle had been using, try plugging the dongle back in, then dismounting it before you remove it. Hopefully that will clear the port for other uses.


Arduino Uno WiFi - WiFi mode keeps changing I have an Arduino Uno WiFi device, which is turned on all the time (day and night). The WiFi mode is set to 'STA'. But from time to time it switches to 'AP+STA' mode automatically, so the device is visible in the network as an Access Point, which is not what I want. Is there a way to prevent my Arduino Uno to switch the WiFi mode by itself? Can it be done via code maybe? Thank you for your help.

Here's the code that is working on it (and it's still working without any problems):

#include <Wire.h>
//#include <Ciao.h> // for older IDE
#include <UnoWiFiDevEd.h> // for newer IDE

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
  #include <avr/power.h>
#endif

int sensorsValues[] = {9999,9999,9999};
int timerCount = 25;
static const uint8_t analogPins[] = {A0, A1, A2};

// for LEDs
int NUMPIXELS = 9;
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMPIXELS, 2); // (numOfPixels, pinNo, options)

boolean hasChanged = false;

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
  #if defined (__AVR_ATtiny85__)
  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  #endif
  // End of trinket special code
  //start serial connection
  Serial.begin(9600);
  for(int i=0; i<3; i++){
    pinMode(analogPins[i], INPUT_PULLUP);
  }
  strip.setBrightness(40);
  strip.begin(); // Initialize the NeoPixel library.
  strip.show(); // Initialize all pixels to 'off'
  Ciao.begin();
}

void loop() {
  for (int i = 0; i < 3; i++) {
    int sensorVal = analogRead(analogPins[i]) >= 1000 ? 1 : 0;
    if( sensorsValues[i] != sensorVal ) {
      hasChanged = true;
      if (sensorVal == 1) {
        // green light
        strip.setPixelColor( (i*3), 100, 255, 100);
        strip.setPixelColor( (i*3)+1, 100, 255, 100);
        strip.setPixelColor( (i*3)+2, 100, 255, 100);
        strip.show();
      } else {
        // red light
        strip.setPixelColor( (i*3), 255, 50, 50);
        strip.setPixelColor( (i*3)+1, 255, 50, 50);
        strip.setPixelColor( (i*3)+2, 255, 50, 50);
        strip.show();
      }
    }
    sensorsValues[i] = sensorVal;
  }
  timerCount += 1;
  if( hasChanged == false && (timerCount % 30) == 0 ){
    CiaoData data = Ciao.write("rest", "xxx.xxx.xxx.xxx", "/d/add/A001/active", "GET");
    if (!data.isEmpty()){
      String st = String(data.get(1));
      String re = String(data.get(2));
    }
  }
  if (hasChanged == true && (timerCount % 5) == 0 ) {
    CiaoData data = Ciao.write("rest", "xxx.xxx.xxx.xxx", "/d/add/A001/a/" + String(sensorsValues[0]) + "," + String(sensorsValues[1]) + "," + String(sensorsValues[2]), "GET");
    if (!data.isEmpty()){
      String st = String(data.get(1));
      String re = String(data.get(2));
    }
    hasChanged = false;
  }
  if (timerCount > 30) timerCount = 0;
  delay(1000);
}

OK. I found a little workaround. Arduino UNO Wifi web interface gives some possibilities. When you go to http://<IPADDRESS>/wifi/info you'll get json formatted info about its wifi connection settings, including WiFi mode (STA or AP+STA). To set new WiFi Mode you can go to http://<IPADDRESS>/wifi/setmode?mode=<MODE> to set new mode. mode=1 is for 'STA', mode=2 is for 'AP' only and mode=3 is for 'AP+STA'.
I've created a little cron job on my server that checks the wifi mode and changes it if needed.


Control Air Pump Depending on Pressure Sensor I am working with an Arduino Mega, a 12V micro air pump, and a MP3V5050 air pressure sensor. The sensor outputs an analog voltage depending on the pressure reading in an inflatable member. I'd like to turn on the micro air pump when the pressure is too low and turn off the pump when the pressure exceeds a determined threshold (exact pressure ranges are currently undetermined).

I have been looking for similar tutorials but this is my first experience working with Arduinos and most existing tutorials are either sensing or pump control, not both. I only have minor coding experience with MATLAB, so any help with this is appreciated. Thank you!

So you basically want a hysteresis control for the air pump.

const int lowerLimit;//fill in as needed
const int upperLimit;

void loop(){
    int pressure = readPressureSensor();
    if(pressure < lowerLimit) turnPumpOn();
    if(pressure > upperLimit) turnPumpOff();

}

The helper functions I used should be easy to implement based on the tutorials you found.


Arduino Micro Cannot get Interrupt 6 work on PIN 7 After finding out about the situation with pin7 from this tutorial:

https://forum.sparkfun.com/viewtopic.php?f=32&t=35847

    void setup(){

    EICRB |= (1<<ISC60)|(0<<ISC61); // sets the interrupt type for EICRB (INT6).
                                  // EICRA sets interrupt type for INT0...3

    /*
    ISCn0  ISCn1   Where n is the interrupt. 0 for 0, etc
      0      0   Triggers on low level
      1      0   Triggers on edge
      0      1   Triggers on falling edge
      1      1   Triggers on rising edge
    */
EIMSK |= (1<<INT6); // activates the interrupt. 6 for 6, etc

void loop(){
//do other things here
}

ISR(INT6_vect) {
  // interrupt code goes here
  }

I have set:

EICRB |= (0<<ISC60)|(0<<ISC61);

Because I need it to be triggered on LOW.

I could still not get it work on the micro. IF I use the pin as regular input pin I can clearly see LOW/HIGHs on pin 7 with digitalread.

I have a sensor attached there which goes LOW in case it is triggered.

I wonder if anybody knows what else can I try to get it work. I already hardwired everything in my circuit board, there are no more free interrupts and no way to change them.

I've used following code and loopback from pin 8 to pin 7:

// loopback:  pin 8 -> pin 7

void setup() {
  pinMode(7, INPUT_PULLUP);
  pinMode(8, OUTPUT);
  pinMode(LED_BUILTIN_TX, OUTPUT); // to see pin 8 logic level on TX led
  pinMode(LED_BUILTIN, OUTPUT); // toggled by ISR

  EICRB |= _BV(ISC60);  // Triggers on edge
  EIMSK |= _BV(INT6);   // activates the interrupt
}

ISR(INT6_vect) {
  PINC = _BV(PC7);  // toggle led 13 (@ PC7)
}

void loop() {
  digitalWrite(8, HIGH);
  digitalWrite(LED_BUILTIN_TX, HIGH);

  delay(500);
  digitalWrite(8, LOW);
  digitalWrite(LED_BUILTIN_TX, LOW);
  delay(500);

}

And it works perfectly. Only problem I can imagine is to figure out correctly which pin is really 7 as label is on the right side of pin (not under nor left).


How to store values inside an empty array and get the average integer? [UPDATED QUESTION] Goodafternoon,

I want to read values form a microphone (Adafruit MAX9814) connected to the Analog port A0 from Arduino and store the values that are incoming inside an array.

After the values are stored in the array, I want to read out the values and store the number that is repeated most time in a variable. Is this possible and how to achieve this?

I came up with the following:

const int micPin = A0;
int soundArray[10];

void setup() {

  Serial.begin(9600);
  pinMode(micPin, INPUT);

}

void loop() {

  int micValue = analogRead(micPin);
  Serial.println(micValue, DEC);
  //delay(400);

  for (int i = 0; i > 10; i++) {
    soundArray[i] = micValue;
    Serial.println(soundArray[i]);
  }
  delay(1000);
  Serial.println("End of for loop");

}

The problem now is that a value of the microphone will be repeated 10 times. So I will receive 10 times the number 234 for example. See image.

This is not what I want. I want to get different numbers in the array of that moment.

Hope someone can help me out.
Thanks in advance.

The error message is correct. You did not define the size of the array.
You have 3 choices:

Declare it with a constant length

int foo[10];
Declare it and initalize it

int foo[] = {0,1,2,3,4,5,6,7,8,9};
Declare it dynamic as pointer and alloc or realloc the mem by yourself (this is not recommended (realloc) because of possible heap memory fragmentation)

int foo;
int size = 10;
foo = (int)malloc(size * sizeof(int));
free(foo);

As reference:
http://www.arduino.cc/en/pmwiki.php?n=Reference/Array


Input Capture Pin Atmel ATmega328P I have some code that relies on the input capture timer value.

I assume the timer value (as defined by the pre-scaler etc) is not affected by other code running i.e. it is updated every nth clock regardless of what instruction is next?

If you want code or more detail ask in comments and I will post code.

I assume the timer value (as defined by the pre-scaler etc) is not affected by other code running i.e. it is updated every nth clock regardless of what instruction is next?

yes, unless your code writes to the registers involved.


Mounting Arduino in an enclosure I've decided to use Sparkfun's Pro Mini boards to make my project into a semi-professional product.

My first thought turned to enclosures - of which the entire internet seems to be bereft. If I ever DO see an enclosure, it's for the Uno sized board and costs about twice the price of the board, which seems incredible to me.

No matter, I have found a way to make quite good enclosures for the Pro Mini pretty easily and cheaply.

HOWEVER, the next problem is mounting the board inside the box. I would like to be able to mount it firmly to the base but in a way which allows it to be removed if necessary. Obviously, there's not a lot of scope for putting screws through the board. It occurs to me that anything which holds it would need to do so by gripping the edges or the corners. Is there such a thing?

If there's nothing that fits the bill, would the board be OK if I were to HOT GLUE it to the base of the enclosure?

What type of box?
Howmany times/how easily do you want to remove the Arduino Mini?

Hot glue

Hot glue is the way to go in many occasions.

It does not conduct electricity, so is pretty safe. (Please check your specific hot glue first)
It sticks quite well, for quite a time. You should also check if it's water resistant or fit for your target environment though.

But, it may have some side-effects:

It can get quite messy (which does not look really professional)
It's not that easily removable and has to be "re-glued" when you want to stick it back.
It might be too sticky (in a carboard box, you won't be able to just rip out the Arduino, withouth damaging the box).

You could use double sided tape, which might actually work fine. Or atleast better/neater as the hot glue.

Sticky velcro

A neat solution would be sticky velcro. You can easily attach, detach and re-attach the arduino to the velcro. It looks quite fancy and should hold well.

Again, you should check the specific velcro, it might not last 1000+ times of re-attaching (become loose or smh). But will be a good option overall.

Extra

You can use mint-boxes as an enclosure. But they're usually made of tin or another conductive material. Please take care and cover the back of your arduino (or box) with electrical tape, to avoid shorts.

Extra-extra, you should (for "replacability") add connectors or headers to your Arduino. Since soldering the leads directly will still give the need to un-solder or resolder your Arduino when replacing.

Note on making your Arduino project a consumer item

You might save yourself quite some money by using a barebones arduino. Or actually, an ATmega 328P chip. Which is around 3€.
These will be a little more difficult to program, but might also look more professional.

You can also enable "program protection" fuse bits, so that others can't download the code from your arduino/microcontroller.


Arduino: pins still active after entering sleep mode I'm writing an Arduino sketch to control a display with my Arduino Nano. I have wired it up as explained here, but used pin 3-7 instead of pin 2-6 listed in the example. The reason I did so is that I also added a push-button on interrupt 0 (= digital pin 2). I'm calling the sleep mode with a method, as explained in the section "Example" here. The Arduino seems to sleep, turning off all LEDs but the on/off one. The problem I have now is that the LCD display is sometimes still enabled (but only sometimes, not always). Why is it behaving like this? And how can I switch off everything possible to save as much energy as possible?

Here is my code piece:

int buttonPin = 2;

void setup()
{
  pinMode(buttonPin , INPUT);
  digitalWrite(buttonPin , HIGH);
  ...
}

void loop() {
  ...
  if(counter == 100) {
    enterSleep();            // Enter sleep method!
  }
  delay(1000);
}

void enterSleep()
{
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  attachInterrupt(digitalPinToInterrupt(2), wakeUpNow, LOW);
  sleep_mode();

  /* The program will continue from here. */
  /* First thing to do is disable sleep. */
  sleep_disable();
  detachInterrupt(digitalPinToInterrupt(2));
}

void wakeUpNow() {
  // execute code here after wake-up before returning to the loop() function
  // timers and code using timers (serial.print and more...) will not work here.
  // we don't really need to execute any special functions here, since we
  // just want the thing to wake up
}

The problem is that you are not specifically doing anything to "turn off" the LCD (that is, switch off the back light - note that the LCD module will still be consuming power while you sleep).

When you sleep the MCU it does just that - it goes to sleep. Its clock stops ticking. Not a lot more than that really.  So if you are using PWM to control the backlight of the LCD, when the clock stops ticking the PWM will stop happening, and the I/O pin will remain stuck in whatever state it happened to be in at that moment - leaving you with random on or off at sleep time.

The solution? Manually turn off the backlight just before you sleep.

digitalWrite(9, LOW);

To save more power you might want to consider adding a high-side switch to the power of the LCD module. With that you can physically disconnect the power to the LCD to stop it consuming any power at all during sleep mode. Of course, after re-enabling it you will need to fully reinitialize the module.

The same goes for any other external hardware that takes a power supply.

A high side switch can be built from a P-channel MOSFET being controlled by an N-channel MOSFET. There's plenty of examples on the web.


Flow control between ESP32 and RS323 device I'm trying to communicate an RS232 device with an ESP32 (Heltec Wifi/LoRa 32 v2) my problem is that I don't receive any response from the device, doing some research, I'm thinking that the trouble can be the flow control because I don't use these pins and the modules I've used neither have these pins. Do you know a way to, at least, solder the DB9 pins to have a sort of flow control to communicate the devices?

You could use ESP-IDF calls to setup your UART correctly for hardware serial communication on pin 4 and 5 (and perhaps also other pins).
In the sample below, you just have to:

assign UART_CLIENT_RTS and UART_CLIENT_CTS to the pins of your need
change uart_config_t to whichever parameters are relevant for your RS232 device
set flow_ctrl to UART_HW_FLOWCTRL_RTS, UART_HW_FLOWCTRL_CTS, UART_HW_FLOWCTRL_CTS_RTS or UART_HW_FLOWCTRL_MAX

    #define BUFFER_SIZE 1024

    #define UART_CLIENT_TXD  (GPIO_NUM_4)
    #define UART_CLIENT_RXD  (GPIO_NUM_5)
    #define UART_CLIENT_RTS  (GPIO_NUM_?) // Set this
    #define UART_CLIENT_CTS  (GPIO_NUM_?) // Set this

    uart_port_t uartNum = UART_NUM_1;

    uart_config_t uart_config = { // Set this
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity    = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS
    };

    uart_param_config(uartNum, &uart_config);
    uart_set_pin(uartNum, UART_CLIENT_TXD, UART_CLIENT_RXD, UART_CLIENT_RTS, UART_CLIENT_CTS);
    uart_driver_install(uartNum, BUFFER_SIZE * 2, 0, 0, NULL, 0);

Communication can be done with the various uart_write_* and uart_read_* methods as defined in the documentation.


Fog machine Arduino integration I want to control my fog machine with an Arduino.  Has a simple button that is used to activate the machine.  I want to press this button using an Arduino digital output pin, but the fog machine is operating on its own electrical circuit.  How do I use the Arduino to activate this machine?

I a few other machines with buttons that I want to wire into an Arduino, so is there a generic solution?

You can interface with the fog machine's button by:

Use a Relay (this will isolate the fog machine's circuit from your Arduino's)
Use a Servo to physically press the button on the fog machine

I believe those would be the simplest and most generic.


GPS showing incorrect speed I am using Arduino ATmega 2560.
When i am using "AT+CGNSINF" command to get GPS value, sometimes it showing incorrect speed.
The correct speed should be (50-60)km/h but sometimes it showing (200-300)km/h.
How can I fix the problem or avoid/ignore the unexpected speed.
here is my code

void get_GPS()
{
    sendATCommand("AT+CGNSINF","OK", 1000);

    // condition for valid response
    while (strstr(AT_Buffer, "+CGNSINF: 1,1") != NULL)
    {
        delay(3000);
        strtok(AT_Buffer, ",");
        strtok(NULL, ",");
        strtok(NULL, ",");
        strtok(NULL, ",");
        strtok(NULL, ",");
        strtok(NULL, ",");
        Serial.println("\n");
        Serial.println(strtok(NULL, ","));

        //sendATCommand("AT+CGNSINF", "OK", 1000);
    }
}
uint8_t sendATCommand(char* ATcommand, const char *expectedResponse, unsigned long timeout)
{
    uint8_t x = 0, answer = 0;

    memset(AT_Buffer, '\0', AT_BufferLength);    // Initialice the string
    delay(100);
    while (Serial1.available() > 0) Serial1.read();    // Clean the input buffer
    if (ATcommand[0] != '\0')
    {
        Serial1.println(ATcommand);    // Send the AT command
    }

    unsigned long previous = millis();

    // this loop waits for the answer
    do {

        if (Serial1.available() != 0) {    // if there are data in the UART input buffer, reads it and checks for the asnwer
            AT_Buffer[x] = Serial1.read();
            //Serial.print(AT_Buffer[x]);
            x++;
            if (strstr(AT_Buffer, expectedResponse) != NULL)    // check if the desired answer (OK) is in the response of the module
            {
                answer = 1;
                break;
            }

        }
    } while ((millis() - previous < timeout));    // Waits for the asnwer with time out

    return answer;
}

Speed calculation in most GPS systems is very crude. It consists of simply "Where was I then? Where am I now?". Many will also add "How long has passed between then and now?", but many also don't - they assume a fixed time between points (1 second, for example). It doesn't know it's supposed to move, all it knows is the coordinates it has at the moment.

With the latter, if you don't get a reading for a couple of seconds (buildings in the way, for example) the position can suddenly jump a long way.  You can see the effect in your phone's GPS in built-up areas - your position may jump long distances and then pause for a bit.

To visualise it in 1-dimension, you can think of a simple number sequence 0-9 and the difference between each value:

Value:        0 1 2 3 4 5 6 7 8 9
Difference:     1 1 1 1 1 1 1 1 1

The difference equates to the "speed" of the sequence.

Now if the numbers don't get updated smoothly, but all at once at the end, you get something like:

Value:        0 1 2 2 2 2 2 7 8 9
Difference:     1 1 0 0 0 0 5 1 1

The end results is the same, but you get a "dead" period with no "movement" and then a big jump with an unusually high speed.

It's up to you to filter out such anomalies. It's simple enough to say "5 is too much - ignore it". You could also average the past 10 seconds worth of data (for example) and use that as your average speed over that time period, which would smooth out such peaks and troughs.