How to make a Smart Light Bulb? I was wondering what I would need and what I should do, to make a Smart Light Bulb, like the Hue one from Philips.

I know these light bulbs can be controlled by their Apps from the smartphone, is there a way I can achieve this too?
What components would I need to purchase?
Is there a reference or a tutorial on how I should program this light bulb?

You could use an ESP8266 NODEMCU. There is an example for making it emulate a Hue bridge ( https://github.com/probonopd/ESP8266HueEmulator ).
To have the official bridge control your lights would take Zigbee and finding out the protocol that Philips uses. Their API is open source, however the zigbee protocol they use is not afaik.
ESP8266 is a very cheap solution that works with arduino ide and does not need an arduino. There are powerplugs which have an ESP8266 in them (https://www.itead.cc/smart-home/sonoff-sv.html)


Is it possible to write data to a fat file system on SPI flash using an arduino? I have an SPI flash based mp3 module and was wondering whether its possible to write to the flash chip using a microcontroller(arduino). the IC supports FAT16/FAT32 file systems. I have researched arduino and the fat file system but they are all in relation to SD cards which operate differently as far as i understand. Is it possible to write data to a fat file system on SPI flash using an arduino?

The first and most important problem is not the filesystem. Currently on the board the USB port is connected to the internal MCU, which in turn is connected via SPI to the flash chip. The internal MCU is the master on the SPI bus. But the SPI bus does not support multiple masters on one bus. So just connecting the external MCU to the SPI lines as master would not work.
I see 2 possible ways to go here:

You can unsolder the flash chip from the board and add a fitting multiplexer chip, which can switch the SPI lines between the two masters. That effectively gives you only one master on the SPI bus at any time. This way would be rather hacky and difficult for a beginner. It might also be important to keep an eye on the capacitance of the bus, since it might run with rather high speed. A too high capacitance (for example through using a breadboard) might result in erroneous communication.
Then you could use one of the FAT libraries. I don't know them in detail, but I think you could also use them for a simple SPI flash chip. You just would need to implement the lower level access functions, that the FAT library needs.

Or you could try to use a USB host board with your external MCU and try to write data through the USB port. I don't have much experience with USB host boards, so I cannot really tell you, if and how exactly this is possible with the available hardware (the board will most likely implement an USB interface like a simple flash USB stick).

All in all I think, this would be rather hacky. Your board is not really made for changing the data through another microcontroller. Depending on what exactly you want to achieve, you might want to go to a different hardware setup.


Function of rxAlign parameter in the PCD_ReadRegister function in MFRC522 Library I'm trying to port the MFRC522 Arduino library (from GitHub) to the ARM MCUs.
My problem is with the PCD_ReadRegister function:

/**
 * Reads a number of bytes from the specified register in the MFRC522 chip.
 * The interface is described in the datasheet section 8.1.2.
 */
void MFRC522::PCD_ReadRegister( byte reg,       ///< The register to read from. One of the PCD_Register enums.
                                byte count,     ///< The number of bytes to read
                                byte *values,   ///< Byte array to store the values in.
                                byte rxAlign    ///< Only bit positions rxAlign..7 in values[0] are updated.
                                ) {

    if (count == 0) {
        return;
    }
    //Serial.print(F("Reading "));  Serial.print(count); Serial.println(F(" bytes from register."));
    byte address = 0x80 | (reg & 0x7E);     // MSB == 1 is for reading. LSB is not used in address. Datasheet section 8.1.2.3.
    byte index = 0;                         // Index in values array.
    SPI.beginTransaction(SPISettings(SPI_CLOCK_DIV4, MSBFIRST, SPI_MODE0)); // Set the settings to work with SPI bus
    digitalWrite(_chipSelectPin, LOW);      // Select slave
    count--;                                // One read is performed outside of the loop
    SPI.transfer(address);                  // Tell MFRC522 which address we want to read
    while (index < count) {
        if (index == 0 && rxAlign) {        // Only update bit positions rxAlign..7 in values[0]
            // Create bit mask for bit positions rxAlign..7
            byte mask = 0;
            for (byte i = rxAlign; i <= 7; i++) {
                mask |= (1 << i);
            }
            // Read value and tell that we want to read the same address again.
            byte value = SPI.transfer(address);
            // Apply mask to both current value of values[0] and the new data in value.
            values[0] = (values[index] & ~mask) | (value & mask);
        }
        else { // Normal case
            values[index] = SPI.transfer(address);  // Read value and tell that we want to read the same address again.
        }
        index++;
    }
    values[index] = SPI.transfer(0);            // Read the final byte. Send 0 to stop reading.
    digitalWrite(_chipSelectPin, HIGH);         // Release slave again
    SPI.endTransaction(); // Stop using the SPI bus

} // End PCD_ReadRegister()

I read the datasheet several times & can't understand what's the function of this parameter!
Based on datasheet for reading a register from rc522:

Concerning the image in your post about 'SPI Read Data', that simply says the first byte received over MISO is discarded, which is done in PCD_ReadRegister() right before the for loop, and then n bytes are read, with 0 transferred the last time to stop reading.

A quick look at the library and datasheet shows that the rxAlign argument is used in identifying the first valid bit in the first received byte. txLastBits serves a similar purpose, only for transmission of the final byte. Both are written to BitFramingReg of the MFRC522 and are necessary for bit-oriented frames between the MFRC522 and a card/tag.

For example, in the function you have above, if rxAlign = 3, it means only bits 7 to 3 are valid in the first received byte, extracted with bit mask 11111000. So the first valid 'byte' comprises bits 7 to 3 of the first received byte concatenated with bits 2 - 0 of the next received byte. Similarly, in transmission, txLastBits indicates the number of bits of the last byte that are to be transmitted to the card/tag. In both cases, what is transmitted or received over the RF field may not be a multiple of 8, hence the need for these arguments and BitFramingReg.

Anyways, this shouldn't interfere at all with porting the library. Simply replace the Arduino-specific functions/interfaces and allow the library's existing logic to remain as is.

EDIT

I'll try to answer your questions:

In this context, 106kBd refers to the data rate between the RC522 and a card, and not between the RC522 and the MCU. The maximum is about 848kBd, i think. Check the datasheet for more details.
Bit-oriented frames are necessary for the anti-collision process. Superimposed bits in the Manchester encoding, when several cards attempt to communicate with the RC522 at once, require that individual bits be processed as opposed to the usual byte-sized units. Look up anti-collision techniques.
Anticollision is necessary if the same reader will possibly have multiple tags within its range. From an IEEE article:

  Tag collisions can impose a major inefficiency in RFID systems, resulting in low identification rates, short reading range and ineffective resource utilization. They are more problematic in passive tags due to limitations on power and functionality.

So, if you will be presenting only one card at a time, then you should be safe without implementing anticollision in your code. Else, I'm afraid you have no choice unless you want to confuse the reader.

If all you want to do is read UIDs and read from/write to blocks on a card (one at a time), you may want to try porting this straightforward MFRC522 UART library, which doesnt implement anitcollision, by the way.

If you still want to port the SPI-based library, then, a few suggestions:

You want to replace the SPI interface with UART. This is low-level stuff, all contained within a few functions like PCD_ReadRegister(), PCD_WriteRegister() and a few others. These functions serve higher-level functions, which have no clue of their internal implementation, but expect certain behaviour from them. Swap the SPI functions for their UART equivalents, as soon as you understand how to talk to the reader over UART. Once your ARM UART functions behave exactly like the SPI functions, your work is almost done; there is no need to learn the reason for everything in the higher-level functions since they dont relate to anything interface-specific. This includes everything concerning rxAlign and whatnot. Good luck :).


Arduino Due uploading error using Eclipse plugin "avrdude: stk500_recv(): programmer is not responding" I have a Arduino Due that I'm trying to upload a sketch to. I follow the tutorial http://playground.arduino.cc/Code/Eclipse to get the board running with the Eclipse plugin.

However uploading the sketch gives me the error

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

If I use the Arduino IDE everthing works fine. I'm using Eclipse mars with Arduino 1.6.5

What could have gone wrong?

avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

There's your clue.
1) programmer is not responding - This usually means the device isn't connected, or powered, or reachable by the IDE, make sure you have eclipse configured correctly for your device, and it's location.

2) not in sync - This is a redundant, or overlapping error, of course it's not going to sync if it can't connect.


Can 1 arduino control 6 stepper motors? I want to make a single cell 3×2 Braille grid that has 6 up and down shafts each of which can be controlled by arduino using 6 stepper motors .

So will that work with 1 arduino uno and/or stepper driver?
How many drivers should I use or is there a better way for controlling those 6 up down shafts individually?
Can I use 16 channel servo shield for controlling those stepper motors?

A servo is not the same type of motor as a stepper. A servo is controlled by a somewhat PWM signal (somewhat, because the servos position will come from the absolute pulse length, not the duty cycle). A stepper motor needs to get the different phases driven in the correct order. This is done by a driver circuit for stepper motors and you cannot use the servo shield for this purpose without any extra circuitry.

You should use drivers explicitly meant for your type of stepper motor. Most drivers will have 2 inputs: 1 direction input (HIGH level means driving the motor in one direction, LOW level in the other) and 1 pulse pin. Everytime a pulse (pin going to HIGH, stay there for a short time and going back to low; or sometimes vice versa) is reaching this pin, the stepper will do 1 step. So to let the motor spin at a certain speed, you need to provide a specific number of pulses in a specific amount of time.

Since you want to drive all steppers individually, you need 6 drivers (one for each motor) and 12 output pins on your Arduino.


SPI Problem with K-Thermocouple and Potentiometer? I have a setup where the Arduino reads input from the k-thermocouple and uses that info to regultate the an output voltage through a potentiometer. I know the potentiometer is not faulty because able to read the output from the wiper when I run the program but for some reason, k-thermocouple is stuck at 0 Celsius. I know that the k-thermocouple is not faulty either because it works accordingly when I run a program specifically by itself.

Does anybody know why there is a problem with how the k-thermocouple is operating in junction with the potentiometer? Here is a declarations of my program.

#include <SPI.h>

// K-couple dependent DigiPot Regulator

#include "SPI.h"
#include "max6675.h"

byte address = 0x10;
int CLK = 13;
int CS = 10;
int SDI = 11;
const int ktcSO = 12;
int ktcCS = 9;
int ktcCLK = 13;

MAX6675 ktc(ktcCLK, ktcCS, ktcSO);

int digitalPotWrite(int value) //Everything that happens when the DigiPot is
called
{
  digitalWrite(CS, LOW); // Chip Select is ACTIVE LOW (so now it's selected)
  SPI.transfer(address);
  SPI.transfer(value);
  digitalWrite(CS, HIGH);
}

void setup()
{
  SPI.begin();
  pinMode (CLK, OUTPUT);
  pinMode (CS, OUTPUT);
  pinMode (SDI, OUTPUT);
  Serial.begin(9600);
  // give the MAX a little time to settle
  delay(500);
}

void loop()
{
  if (ktc.readFahrenheit() < 60)  // While it's still in Safe Zone
  {
    digitalPotWrite(255);
    // Show the current temp in C and F
    Serial.print("Deg C = ");
    Serial.print(ktc.readCelsius());
    Serial.print("\t Deg F = ");
    Serial.print(ktc.readFahrenheit());
    int sensorValue = analogRead(A0);
    float voltage = sensorValue * (5.0 / 1023.0);
    Serial.print("\t V = ");
    Serial.println(voltage);
    int clockValue = analogRead(A1);
    Serial.print("\t Clock = ");
    Serial.println(clockValue);
  }
        if (ktc.readFahrenheit() < 65) // While in Caution Zone
        digitalPotWrite(51);
        else if (ktc.readFahrenheit() < 70)
        digitalPotWrite(102);
        else if (ktc.readFahrenheit() < 75)
        digitalPotWrite(153);
        else if (ktc.readFahrenheit() < 78)
        digitalPotWrite(184);
        else if (ktc.readFahrenheit() < 80) //Getting into Danger Zone
        digitalPotWrite(204);
        else if (ktc.readFahrenheit() < 81)
        digitalPotWrite(214);
        else if (ktc.readFahrenheit() < 82)
        digitalPotWrite(224);
        else if (ktc.readFahrenheit() < 83)
        digitalPotWrite(235);
        else if (ktc.readFahrenheit() < 84)
        digitalPotWrite(245);
        else (ktc.readFahrenheit() < 85); //Complete Shutoff
        digitalPotWrite(255);
    {
     Serial.print("Deg C = ");
     Serial.print(ktc.readCelsius());
     Serial.print("\t Deg F = ");
     Serial.print(ktc.readFahrenheit());
     int sensorValue = analogRead(A0);
     float voltage = sensorValue * (5.0 / 1023.0);
     Serial.print("\t V = ");
     Serial.println(voltage);
     int clockValue = analogRead(A1);
     Serial.print("\t Clock = ");
     Serial.println(clockValue);
    }
}

Also, the code I used to test the K-Thermocouple is one that can be found on the internet (with just a little bit of adjustments)...

// Sample Arduino MAX6675 Arduino Sketch

#include "max6675.h"

int ktcSO = 12;
int ktcCS = 9;
int ktcCLK = 13;

MAX6675 ktc(ktcCLK, ktcCS, ktcSO);

void setup() {
  Serial.begin(9600);
  // give the MAX a little time to settle
  delay(500);
}

void loop() {
  // basic readout test

   Serial.print("Deg C = ");
   Serial.print(ktc.readCelsius());
   Serial.print("\t Deg F = ");
   Serial.println(ktc.readFahrenheit());
   int clockValue = analogRead(A1);
    Serial.print("\t Clock = ");
    Serial.println(clockValue);

   delay(500);
}

The wiring diagram, if accurate, shows a couple of problems.

First, A0 has nothing attached to it, so sensorValue may read in as zero or some small random number.

Second, attaching the digital pot's analog output pin 6, P1W, to the Uno's digital input pin 12 is pointless.  Instead connect P1W to whatever it is supposed to control.  If you want to handle data from the MCP42X1, connect its pin 13, SDO, to an Uno input.

However, neither of those problems appears to be related to misreading the MAX6675 temperature.  I don't know of a good approach to solving that problem, but if I were working with the circuit, would remove the wire between P1W and the Uno's digital pin 12, and would use 12 as the input from the MAX6675; that is, would wire it to d12 instead of d8, and instead of int ktcSO = 8 would say const int ktcSO = 12.  Also, I'd probably replace the bit of code

  }
  else
  {
    while (ktc.readFahrenheit() < 85)
      {

with just a closing }.  In the Arduino paradigm, loop() runs repeatedly, and the if–else sequence adequately guards each of the digitalPotWrite() calls.

Note, the digitalPotWrite() function should be defined or declared before any calls to it appear.  Instead of placing that function at the end, put it before  loop() or before setup().


Attempts with Sainsmart Motor Shield Not Working I received the sainsmart motor controller a few days ago, and am now having trouble testing it. The Arduino I am using is an Arduino Mega 2560. I thought it was an I2C communication issue but that wasn't working. So here I am now asking for help.
Here is my wiring.

Here is my code:

#include <AFMotor.h>

AF_DCMotor motor(2);

void setup() {
 Serial.begin(9600);           // set up Serial library at 9600 bps
 Serial.println("Motor test!");

 // turn on motor
 motor.setSpeed(200);

 motor.run(RELEASE);
}

void loop() {
 uint8_t i;

 Serial.print("tick");

 motor.run(FORWARD);
 for (i=0; i<255; i++) {
  motor.setSpeed(i);
  delay(10);
 }

 for (i=255; i!=0; i--) {
  motor.setSpeed(i);
  delay(10);
 }

Serial.print("tock");

motor.run(BACKWARD);

 for (i=0; i<255; i++) {
  motor.setSpeed(i);
  delay(10);
 }

for (i=255; i!=0; i--) {
  motor.setSpeed(i);
  delay(10);
 }

Serial.print("tech");
motor.run(RELEASE);
delay(1000);
 }

I also tried this one:

#include<AFMotor.h>
 AF_DCMotor motor2(2);
void setup() {
 // put your setup code here, to run once:
 motor2.setSpeed(255);
}

void loop() {
 // put your main code here, to run repeatedly:
 motor2.run(FORWARD);
  }

None of the two worked. If someone could help me that would be great. Thank You!!!

I figured out the problem. One of the terminals was damaged during transportation. Now it's all good. Thanks for the help.


How do I wire a ground rail to a VEROboard? I’m looking to move my project from a breadboard to a vero board. However, I’m not sure how to go about soldering in my ground and power connections as the veroboard doesn't seem to have dedicated ground and power rails like the breadboard.
I’ve also attached a photo of my schematic in its current state.
Also, I’m using an Arduino Nano Board as opposed to the UNO featured in the schematic. (I’ve just used it as a placeholder as I could find a component for the nano.
Any help would be greatly appreciated.

Here’s a photo of the type of veroboard I have:

There's nothing special about ground. It's just a wire like any other.
You could designate a row of holes as ground then link them all together, but you don't need to. Just wire your grounds together as you would any other connection.


Change values of timer using I2C I'd like to alter the "LED_T_ON" values using an I2C enabled device (i.e. RPi)

Code for Arduino Mega slave:

//slave

#include <Wire.h>

#define SLAVE_ADDRESS 0x08

const int PWR_LED = 43;
int LED_TinH_ON = 18;
int LED_T_ON = 5000;
int LED_T_OFF = 5000;

String inString = "";    // string to hold input
byte LastMasterCommand = 0;
int Mval;

char user_input;

class Relay {
  int relayPin;
  long OnTime;     // milliseconds of on-time
  long OffTime;    // milliseconds of off-time

  // These maintain the current state
  int relayState;                 // pumpState used to set the PUMP
  unsigned long previousMillis;   // will store last time PUMP was updated

  // Constructor - creates a Timer and initializes the member variables and state
  public:
  Relay(int pin, long on, long off)
  {
    relayPin = pin;
    pinMode(relayPin, OUTPUT);

    OnTime = on;
    OffTime = off;

    relayState = LOW;
    previousMillis = 0;  //ORIGINALLY 0
  }

  void Update()
  {
    // check to see if it's time to change the state of the TIMER
    unsigned long currentMillis = millis();

    if((relayState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
      relayState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(relayPin, relayState);  // Update the actual LED
    }
    else if ((relayState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      relayState = HIGH;  // turn it on
      previousMillis = currentMillis;   // Remember the time
      digitalWrite(relayPin, relayState);   // Update the actual RELAY
    }
  }
};

Relay relay3(PWR_LED, LED_T_OFF, LED_T_ON);

void setup() {
 // initialize serial communication with computer:
  Serial.begin(9600);

  Wire.begin(SLAVE_ADDRESS);

  Wire.onReceive(receiveData);
  Wire.onRequest(slavesRespond);

  pinMode(PWR_LED, OUTPUT);
}

void loop() {
  delay(1000);

  Serial.print("LED_T_ON=");
  Serial.println(LED_T_ON);
  Serial.print("LED_T_OFF=");
  Serial.println(LED_T_OFF);
  Serial.println();

  relay3.Update();

  switch (Mval) {
    case 1 ... 25:
      LED_TinH_ON = Mval;
      Serial.print("LED time on: ");
      Serial.print(LED_TinH_ON);
      Serial.println("h");
      LED_T_ON = LED_TinH_ON*1000;//*60*60;
      LED_T_OFF = (24-LED_TinH_ON)*1000;//*60*60;
    break;
  }
}

void receiveData(int byteCount) {
  LastMasterCommand = Wire.read();
  while (Wire.available()) {
    int msg = Wire.read();

    if (isDigit(msg)) {
      inString += (char)msg;
    }
  }
  Mval = inString.toInt();
  //Serial.println(LastMasterCommand);
  inString = "";
  //Serial.println(Mval);
}

void slavesRespond() {
}

When I change the value on the RPi the Arduino receives and displays the correct value but the timed relays don't actually use the updated values.

Am I missing something?

Your updating LED_T_ON and LED_T_OFF but those values were already passed into the constructor and changing them will not change the object. you need to update  relay3.OnTime and relay3.OffTime


Fan control circuit with Arduino I have a fan control circuit with Arduino (PWM). I did all things and it worked. My question is why we did not directly connect the fan to Arduino. Why should we have a driver circuit?

This is an electronics question, and it should be forwarded to the electronics stackexchange.

The fan needs to have a proper amount of current to spin, and because the microcontroller that controls the fan draw very little current on its output pins (check the datasheet for the exact value, but it should be a few milliamps), unless you have a miniature fan, wiring it directly on the microcontroller will not be able to move the fan.

And this is by design that microcontrollers cannot provide much current. Because to provide larger amount of current than what they do, they'd need to have bigger copper tracks between the transistor to avoid having they internal circuits building too much heat, and they would be much much bigger.

So as a work around, we use an transistor, which receives on the "Base" pin a voltage, drawing almost no current, which will "connect" the collector and emitter pins where you can have a much bigger current flowing (though be careful to respect the datasheet's nominal values for current! Or use either a MOSFET, a Triac or a Relay for bigger currents).


Hacking old car dvd monitors with arduino I got this old junk LCD from my car. The DVD function stopped and the LCD holder on the top of the car broke, so I took it.

Is there any documentation or advice I could use to get this working with an Arduino mega or clone of similar power? I couldn't find anything after looking through Google.

I.e. I'm looking for a way to get a pinout or idea of what those wires on the jack are so that I might be able to get text and/or basic graphics on the screen. Maybe to make an Arduino PC or something idk.

Any advice on either figuring out the connections by hand and how to get a simple connection to the Arduino to get bsic stuff working or a place I can find pinout and such or where someone else has done something similar would be helpful.

Update 2
A quick Google search reveals that it's made by sharp I believe. I'm looking into it.

Update
Here's is the back. It's got quite a few numbers on it. Maybe one of those can help?

Top Numbers:
D 09399847
LQ070T5CRQ2 46009355

And the one on the bottom:
K4013TP

Your best bet is to try to take the casing off until you find a company name so that you can get a lead on where to look for documentation. Because until you find out more about how that screen works, it's a black box to you and you don't know what to put in it. No one else will be able to help you until you provide more information to this extent because no one else can hold it in their hands, and the photo of the socket that you showed us doesn't look like a common display format either.

Also, you're very unlikely to make a PC-type thing out of this. That depends on the power of the computer behind the display and an arduino isn't that powerful. You want a Pi. Or maybe I'm misunderstanding what you want. You could easily get a scrolling text type thing going or maybe even a game (if you figure out how to make it work).

Edit: I just looked up a sample LCD screen and it has 6 signal pins and power and ground. Yours looks like it has a lot more. So you definitely have some digging to do.


Own type definition using a struct does not name a type I need to initialize several buttons and LEDs connected to my Arduino. To store data related to an individual button or LED, I decided to define my own data type using two different structs. One for a button and another one for a LED.
As I need to configure some GPIOs and other peripherals after instantiating each button/LED, I implemented a small factory function to get a clean interface and combine the required steps for instantiating and initialization.
Defining my own button_t type works as expected. The compiler does not throw any errors. However, I tried to implement the same approach for led_t type upon the compiler states the following error:

example:25:1: error: 'led_t' does not name a type
led_t ledFactory(uint8_t pinNumber)
^~~~~
exit status 1 'led_t' does not name a type

My example code looks like this:
#include <Arduino.h>
#include <stdint.h>

struct button_t
{
    const uint8_t pin;
    uint8_t currentState;
    uint8_t lastState;
    uint32_t lastDebounceTime;
};

button_t buttonFactory(uint8_t pinNumber)
{
    button_t btn = {pinNumber, 0, 0, 0};
    // setting some MCU registers here
    return btn;
};

struct led_t
{
    const uint8_t pin;
    const uint8_t state;
};

led_t ledFactory(uint8_t pinNumber)
{
    led_t led = {pinNumber, 0};
    // setting some MCU registers here
    return led;
};

void setup()
{
}

void loop()
{
}

This is a bug in the Arduino IDE: when converting your .ino file to a
.cpp file, it added a declaration for the function ledFactory()
before the declaration of the type led_t.
As it appears to be adding those declarations right before the first
function of your sketch, a simple workaround is to put all your type
definitions before your functions.


Need help with the syntax for a function that takes a closure My C++ is very out-of-date. (20+ years, before C++ had closures).

I'm a senior SW engineer, and I spent several hours yesterday trying to figure this out, but I could not work it out.

The background:

I'm trying to create a class, ClosureButton, that is a subclass of another class, ArduinoObject. (An ArduinoObject has setup(), start(), stop(), and loop() methods so that the main program can invoke it.)

(C++ uses the terms closure and lambda to mean different things. In other languages the terms are interchangeable. Forgive me if I'm not using the correct term.)

A ClosureButton's constructor would take a pin number, and a closure with a bool parameter (pressed). I would save that closure to a member variable. When the button's state changed, it would invoke the closure and pass the new button state to the closure.

The question:

I need help with the syntax for the constructor, as well as how to declare the instance variable that would hold the closure.

The constructor would look something like this:

ClosureButton::ClosureButton(uint8_t pin, _unkonwn_syntax_ closure);

(Where I need help with the _unkonwn_syntax_ bit.)

Then I need to declare a member variable on my ClosureButton to hold the closure:

class ClosureButton: ArduinoObject {
  //other stuff
  _other_unkonwn_syntax_ closure;
}

Again, I need help with the syntax to declare a member variable closure of type "closure that takes a bool parameter". (The _other_unkonwn_syntax_ bit.) At this point I don't think my closure will capture variables from its enclosing scope, but at some future date I might need to do that, so help with that would be appreciated as well.)

I suggested in a comment that a functor may be a viable alternative to a
capturing lambda. This answer is mostly meant to answer the OP's request
to elaborate on that suggestion.

Let's define a ButtonCallback as an object that can be called like a
function taking a single boolean parameter:

class ButtonCallback {
public:
    virtual void operator()(bool) = 0;
};

To break down the syntax:

void operator()(bool) declares a method that allows the object to be
called as if it were a function taking a bool argument and returning
nothing. In other words, if you issue a call such as
my_object(true), that method will be called.
virtual _method_declaration_ = 0; says that the method is not going
to be defined for this class (it's a “pure virtual method”), but it
can be defined by derived classes. A class with such a method is
called an “abstract class”: it defines an interface, it cannot be
instantiated, and it's meant to be used as a parent for classes that
do implement the missing methods.

Now the Button class can be defined like this:

class Button {
public:
    Button(uint8_t pin, ButtonCallback &callback)
    : pin(pin), callback(callback) {}
    void push() {  // for testing only
        Serial.print("press: ");   callback(true);
        Serial.print("release: "); callback(false);
    }
private:
    uint8_t pin;
    ButtonCallback &callback;
};

Notice that the callback is stored as a reference to a
ButtonCallback object. The object itself cannot be stored because it
has an abstract type. Alternatively, a pointer could be used, which
would practically be equivalent.

For using this class, you first have to create the callback as a
concrete class that inherits from from ButtonCallback. Any data you
wish to capture should be stored as class data:

class CapturingLambda : public ButtonCallback {
public:
    CapturingLambda(int data) : some_data(data) {}
    virtual void operator()(bool pressed) {
        if (pressed)
            Serial.println(some_data);
        else
            Serial.println(0);
    }
private:
    int some_data;
};

With all this in place, the following test:

void setup() {
    Serial.begin(9600);
    int data_to_capture = 42;
    CapturingLambda callback(data_to_capture);
    Button the_button(2, callback);
    the_button.push();
}

void loop(){}

outputs:

press: 42
release: 0

Did you said you “find the syntax of C++ pretty obtuse”? I can only
concur with you!

Addendum: Another alternative is to define the callback using the
good old C idiom: a “lambda” is the combination of a function pointer
and a generic data pointer. The function pointer looks like this:

typedef void (*ButtonCallback)(bool, void *);

The second argument is used to provide the callback whatever data it is
supposed to have “captured”. It is a generic pointer (a void *)
because the library does not know what kind of data its client may need.
Now the Button class has to store both the function pointer and the
data pointer, and always provide the data pointer to the callback:

class Button {
public:
    Button(uint8_t pin, ButtonCallback callback, void *callback_data)
    : pin(pin), callback(callback), callback_data(callback_data) {}
    void push() {  // for testing only
        Serial.print("press: ");   callback(true, callback_data);
        Serial.print("release: "); callback(false, callback_data);
    }
private:
    uint8_t pin;
    ButtonCallback callback;
    void *callback_data;
};

The user would have to decide what kind of data it needs, and do
explicit pointer casts to/from the proper pointer type and void *. For
example, assuming we need an int, the callback may be:

void callback(bool pressed, void *data) {
    int *actual_data = (int *) data;
    if (pressed)
        Serial.println(*actual_data);
    else
        Serial.println(0);
}

Here is the test, with the exact same output as before:

void setup() {
    Serial.begin(9600);
    int data_to_capture = 42;
    Button the_button(2, callback, (void *) &data_to_capture);
    the_button.push();
}

void loop(){}

Notice that, syntactic differences apart, this solution does essentially
the same as the previous one. The main difference is that the data is
given to the callback as an explicit pointer instead of the implicit
this pointer. If you have to choose between these two solutions, I
would suggest going for whichever syntax you find easier to work with.

Beware also that in both cases it is the programmer's responsibility to
manage the storage of the callback data and make sure the corresponding
reference (or pointer) remains valid throughout the lifetime of the
Button object.


Can I use a GPS from old Garmin with an Arduino? I'm working on an Arduino project, and I'd like to add GPS functionality. I could buy a GPS module, but those are expensive. I had an old Garmin Forerunner 305 lying around, so I took it apart and took a peek inside. There are two PCBs - one connected to a screen and one to the GPS. In addition, there was a battery and a small part for charging.

I'd like to know if it is possible to connect this GPS to my Arduino, and if so, how?

Edited:
To make my question more precise,

-I see the pins in the top right of the picture. How do I connect those to my Arduino? Is there any specific kind of wire? Because the pins are too small for standard wires.

-Once I connect it, how do I figure out the voltage requirements and pin layout? I tried googling the  GPS model, but nothing helpful came up. What kind of scope should I put on it?

The two pictures below show only the GPS part of the inside of the watch.

The short answer is NO, unless you have solid experience with microelectronics.

Finding documentation for a module you take out of a commercial device is hard to impossible. Chances are, that module is specific to Garmin, and even if it isn't, it's certainly EOL by now, with no support whatsoever.

Even if you do find the spec, there is a high chance that you'll have to write a software library to support it on Arduino. Don't expect the supplier to share the code they gave to Garmin.

Finally, to put together and debug this project, you will need quite some equipment:

oscilloscope to debug the electrical interface
soldering station to solder small pins properly

Like people said in comments, this equipment alone will cost much more than a brand-new GPS receiver.


atmega328p on breadboard using ftdi to upload sketches @8mhz 3.3v I'm having trouble getting the atmega328p chip to upload sketches using my ftdi. It always comes up with an error saying not in sync.

I have an 8Mhz crystal with 22pf capacitors. The weird thing is I could flash the bootloader using my avrispmkII @ 3.3v. AFAIK this tells me the chip is running. I have an led connected to pin7. It doesn't flash when turn the power on.  However it does flash when powered from 5v and everything is working fine. I could upload sketches using the ftdi.

I have the ftdi on a breakout to pin headers. I have the reset pin wired up to the DTR via a 100nf capacitor. The reset has a 10k pull up. CTS pin is grounded. The usart is as follows tx (atmega) ---> rx(ftdi)  and rx(atmega) to tx(ftdi). I have also switch between 3.3v and 5v logic using the vccio pin on the ftdi. I.e. vccio = 5v if atmega is 5v.

I know the programmer need to know what voltage am using, how critical is it, since I don't have a 3.3v regulator to hand. I used a lm338 and it's coming out as around 3.2

I selected arduino pro/mini @ 8mhz 3.3v atmega328p when I flashed the bootloader

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

pro328.name=Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328

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

pro328.bootloader.low_fuses=0xFF
pro328.bootloader.high_fuses=0xDA
pro328.bootloader.extended_fuses=0x05
pro328.bootloader.path=atmega
pro328.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex
pro328.bootloader.unlock_bits=0x3F
pro328.bootloader.lock_bits=0x0F

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

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

output from avrdude

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x1e950f
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as DA
avrdude: safemode: efuse reads as 5

avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as DA
avrdude: safemode: efuse reads as 5
avrdude: safemode: Fuses OK

avrdude done.  Thank you.

I would suspect that the 328P's fuses were not programmed as defined in the boards.txt This needs to be explicitly done.

uno.bootloader.low_fuses=0xff
uno.bootloader.high_fuses=0xde
uno.bootloader.extended_fuses=0x05
uno.bootloader.path=optiboot
uno.bootloader.file=optiboot_atmega328.hex
uno.bootloader.unlock_bits=0x3F
uno.bootloader.lock_bits=0x0F

if not done. several things can go wrong.

oscillator won't start on external crystal
oscillator will be at wrong speed code
wont start at bootloader


I can send AT Commands, but cannot upload sketch to ESP8266 via Generic ESP Module I can send AT commands to the ESP8266 - 01 but I am not able to upload the sketch.

I have connected TX-RX of module to TX-RX of Arduino, GND to GND, CH_PD, RST and VCC to 3.3V.

Here is the code I'm trying to upload -

#include <ESP8266WiFi.h>

const char* ssid = "ssid";
const char* password = "password";

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

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println(".");
    Serial.println("Connected to ");
    Serial.println(ssid);
  }
}

void loop() {
  Serial.println("Hello, Internet");
  delay(1000);
  Serial.println("IP Address");
  Serial.println(WiFi.localIP());
  delay(2000);
}

Here is the error I am getting.

Arduino: 1.8.1 (Windows 8.1), Board: "Generic ESP8266 Module, 80 MHz, 40MHz, DIO, 115200, 512K (64K SPIFFS), ck, Disabled, None"

Sketch uses 225921 bytes (52%) of program storage space. Maximum is 434160 bytes.
Global variables use 31864 bytes (38%) of dynamic memory, leaving 50056 bytes for local variables. Maximum is 81920 bytes.
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

Please suggest something.

In order to put the ESP into programming mode, you need to connect GPIO0 to ground as you power it up.

(I have a push button attached to my proto board for this purpose.)


Does porting code to different MCU clock frequency affect serial baud rate? Tried to upload my Arduino Uno sketch that writes to serial UART at 9600 baud rate onto my ATtiny2313 running at 1MHz. Not getting the signal on the ATtiny, does this have to do with my clock frequency of the MCUs being 16 vs 1MHz?

Yes, it does. As can be seen in the "USART" section of the datasheet the baud rate is generated directly from both fosc (aka FCPU) and the value contained in UBRR. The tables at the end of the section gives the appropriate value for UBRR for a given CPU frequency, desired bit rate, and state of the USART clock doubler.


How to call 5 different functions in a loop based on serial input? I have 5 types of such functions with different input parameters.

blink(int a,char* b, int c);
fade(int a,int b,int c);
split(int a,int d);

and so on from serial input what i want is to call this three functions in any combinations that can be later executed in a loop. For example  my serial input is this ..

[blink(a,b,c),fade(a,b,c),blink(a,b,c),fade(a,b,c),split(a,d),blink(a,b,c)]

The  Code should also be saved  in memory so that when a person reset Arduino. The order of functions execute without waiting for serial input.The order of functions would get change only when person enter serial data to arduino.
I have no clue where to begin please help me out.

This answer isn't going to give you the code to solve your problem, it is just ideas that you can look at and see what suits you best.

You should be able to find an example on how to read from a serial connection, I'm sure there is at least one example in the IDE.

You need to work out how to encode your data, having it in nice human friendly format (like you have above) is great if you are processing it on a PC but on a processor that is slow and have very limited memory using A,B,C... as the function names might be more practical.  It will be smaller to store and quicker to compare.

You want to store the input so it can be read back later.  There are a number of ways you can do this but they all need a non-volatile storage medium.  You could use an SD card, obviously you'd need an SD reader and the type of reader you get will affect the code you need, but these can be problematic.  You can also use EEPROM chips that, you can get little I2C interfaced modules, they have less space than an SD card, but are generally faster (they also have a shorter lifespan, but don't worry I don't you'll ware one out).  You can also use the EEPROM that is in the Arduino itself (I've never done this).

It is best to build you program up in small parts, get the reading from serial working, then calling functions, then saving and loading.  That way you only have to debug a small bunch of issues at once.  If you wanted you could abstract the storage device away from the code by writing a base class that has virtual save and load functions.  You could then inherit from this class for the EEPROM or the SD card and changing wouldn't affect the rest of the code.

Like I said at the start I appreciate this answer hasn't given you a step by step guide on how to solve your problem, but hopefully it has given you a few pointers on what you could do and you can research the options from there.  Remember when you get stuck on one particular aspect just post a minimal example of what you have tried and explain what you expect it to be doing and people will be more than willing to help.


Control speed of a dc motor with a 9v battery Problem:
I want to have a 9v battery that powers a dc motor. I want to control it with a bluetooth remote that has 3 buttons. 1st button is turn the motor with 1.5v, 2nd button is motor off and the 3rd button is full power (9v). Here is the problem normally I will change volt with my arduino using code, but it has a max voltage of 3.6v so I can't control the battery with the arduino. Also I would like the 9v battery to power the arduino and bluetooth module if that is possible, so I have only one battery that powers everything.

What I tried:
I found a lot of different things on the internet. Pwm, Tip120 transistor, L298N and it only confuses me more I have no idea where to start. Spend 8 hours looking for stuff and no step further.

Result:
I hope everything will work with a 9v battery and the bluetooth remote can switch between 3 different speeds.![enter image description here]

You have 3 problems here:

Driver circuit the motor: Since you only want to control the motors speed (not changing it's direction, where you would need a H-bridge like the L298N), a very simply driver circuit is sufficient. It can consist of a bipolar transistor or a MOSFET. The Arduino's digital output pin would set the transistor/MOSFET to conductive or non-conductive, which turns the motor on or off. The motor is connected (through the transistor/MOSFET) with the full supply voltage. For the needed circuit, you can google terms like "transistor as switch" or "MOSFET as switch". That should give you plenty of tutorials.
Controlling the motor speed: Normally the speed of a motor is not controlled through the voltage, since the speed behaves not linear with the voltage. Instead we use PWM (Pulse Width Modulation), where a squarewave voltage with a constant frequency is outputted at the Arduino's pin. To change the motor speed, you change the ratio between ON and OFF time of the pin (called "duty cycle"). So the motor basically get's turned on and off very fast. Since the motor is to slow, to follow the fast change, we are basically giving it small pushes very fast. If you only push half of the time (duty cycle 50%), the motor will run with about half the speed. In Arduino code you use analogWrite(pin_number, x) with x between 0 and 255 to output a PWM wave at the specified pin. Refer to the Arduino documentation for details.
Powering the whole device: First: A 9V block battery is actually like the worst choice for most cases (especially for devices with motors). It has a big series resistance, what means, that it cannot provide much current without dropping the voltage radically. They are meant for low-current devices. Better use multiple AA/AAA batteries in series.

You didn't state, what Arduino you actually use, but from the description, it has to be one of the 3.3V boards, like the Arduino Pro Mini 3.3V version. Most Arduino boards also have a small voltage regulator on them. The input for it is mostly marked with Vin. Please refer to the documentation of your Arduino board, to check, which voltages are suitable for that voltage regulator. If you don't have a voltage regulator on your Arduino or your battery voltage doesn't fit, you have to provide the power through your own external voltage regulator. You should use a switching regulator (far more efficient, than linear regulators), which can provide the needed power (depending on the Arduino and the bluetooth device maybe between 50mA and 300mA, difficult to say generally) plus a bit overhead.

You should then provide the motor with the full battery voltage, especially not through the Arduino's voltage regulator. Motors can draw quite much current. If you draw more current through a regulator, than possible, it will overheat, emergency shutdown or even burn out. If the battery voltage is not suitable, you should use a voltage regulator, that can safely provide the needed current.

Note: Depending on the size of the motor and it's load, you might want to add a flyback diode, that would safely let inductive reverse currents flow to ground, so that the inductive voltage is not piling up in the transistor/MOSFET.


How to safely remove arduino nano from breadboard? I did some prototyping with arduino nano in breadboard. And then after i done with the design, I was gonna implement it in a printed pcb so i need to remove the nano from breadboard. And this is when the disaster happened.

The board is kinda hard to pull by hand, so i use a long-thin screwdriver in the gutter to pull the nano up (just like i did many times to dip ICs with no problem). And successfully detached the nano from breadboard and also broke the tantalum under the nano in the process. So the question is:

How do you usually remove the nano board from breadboard safely? And
The tantalum i broke is 4.7uF smd. I can't find any 4.7uF tantalum in nearby shops, but i have electrolyte caps rated 4.7uF 16v. Can i use it for replacement?

How do you usually remove the nano board from breadboard safely? And

If you can't remove it by hand (grip it lengthwise and ease up each end with your finger / thumb levering against the breadboard) then you need a lever. The best is a plastic spudger, such as this:

The plastic will flex rather than damage the Arduino. Using a screwdriver can, as you have noticed, damage the Arduino.

  The tantalum i broke is 4.7uF smd. I can't find any 4.7uF tantalum in nearby shops, but i have electrolyte caps rated 4.7uF 16v. Can i use it for replacement?

Sure. All that is, is a reservoir capacitor on the USB input. The value isn't super-critical, as long as the voltage is above 5V. It's not, strictly speaking, even needed. You can just remove it completely and clean up the pads to ensure there's no shorts. The board should still work fine.


Setup arduino uno with ESP8266 ESP-1 Iam trying to set up the arduino uno with the wifi module ESP8266. I use this schematic setup:

I have followed this tutorial: Tutorial ESP8266

Thereby I removed the Mega328P Chip like it says above, I can communicate trough my terminal in the arduino IDE with the ESP-module but when I want to upload an simple test file like this:

#include <SoftwareSerial.h>

SoftwareSerial ESP8266(0, 1); // RX = 8 en TX = 9

boolean FAIL_8266 = false;

void setup() {
  // put your setup code here, to run once:
   do {
    ESP8266.begin(115200); // start communicatie met esp8266

    //Wait Serial Monitor to start
    while (!Serial);

    ESP8266.print("AT\r\n");

    delay(500);

    if (ESP8266.find("OK")){
        ESP8266.print("ready");
    }

   } while (FAIL_8266);
}

void loop() {
  // put your main code here, to run repeatedly:

}

Than it keeps throwing me this error: avrdude: stk500_getsync() attempt x of x: not in sync: resp=0x20 is it because I removed the Mega328P Chip?

Thereby I've tried the test code from the tutorial here is an link to the code: LINK.

There it keeps saying that Serial2 was not declared in scope

I'll hope someone can help me out on this one and run an simple test script to communicate with the ESP8266 WIFI Module

You must have your microcontroller in place if you are uploading code to it.

You can talk to ESP8266 via serial monitor because you are connected directly to the pins of your USB-UART bridge.

Place your uC back, change this line of code:

SoftwareSerial ESP8266(0, 1);

to this one:

SoftwareSerial ESP8266(8, 9);

and change your wires accordingly(what was on pin 0, now connect to pin 8, pin 1 to pin 9).
Now your Atmega can talk to ESP8266 after you upload the code.

btw. "Serial2" is Serial port for more advance Arduino boards, it won't work on Atmega328 based board.


Use normal TFT Shield with SD as a Nextion Display I have a normal Elegoo TFT 2.8" display shield that also had an SD reader. I am trying to use it as a Nextion display. I want to do this because the Nextion tool allows you to make very nice looking sophisticated graphics and I wanted to do the same. Is there any possibility? Maybe some interpreter library?

No, you can't.
Nextion displays contain their own microcontroller with their own closed-source firmware on them.  You need that firmware to have a clue what is in Nextion files, and only Nextion have that firmware.
While it may be possible to reverse engineer Nextion display data and write your own software to interpret it, it would be a huge job with little to no real-world benefit.


Serial Getting Garbage Data with real data I have made an app in VS2015 C#.Net which sends data to Serial port. The data i am sending is:

stat>temp:39,38,;load:17,4,42,;fans>50,50,;

Where as I am receiving:

ððððstat>temp:39,38,;load:17,4,42,;fans>50,50,;

What I have tried:

Set SerialPort Encoding to ASCII in C#
Set SerialPort Encoding to UTF8 in C#
Set SerialPort Encoding to Default in C#

All have no effect.

Some observations:

When I send the data via Serial Monitor of Arduino there is no garbage data.
When I send data via a USB to TTL converter via my App, no garbage. (This part confuses me more)

BAUD RATE IS: 115200.

This is the only thing I have not changed yet and I dont want to change this as the string length will increase over time. this is 43 bytes of data. It can grow to up-to around 64 or 100 bytes and that would take longer to send and even longer to read adding delays in functions that are already working before the serial interrupt.

Regards

The Arduino should read only whole lines (non-newlines until a newline). Discard the line if it doesn't start with "stat>".

This will make your program more robust and less likely to fail with bad input. Fixing the transmitting app instead still leaves your Arduino vulnerable.

Consider the rule of thumb for serial communication: "Be restrictive in what you'll transmit; be lax in what you'll receive." Specify your communication protocol (e.g. "Packets will begin with 'stat>' and end with <newline>", maximum length of a packet, formats of variables and numbers, etc.). Then write your sender to hold as tightly to the spec as possible and write your receiver to accept whatever minor variations in otherwise good packets, that won't cause you to mistakenly accept bad ones. This principle will make your communications systems more robust and easier to get working in the first place.


Why/when to use IoT publish/subscribe protocols rather then RESTful HTTP? I am sending data (GPS coordinates) from Arduino once a minute with HTTP POST request to REST API (in OpenShift PaaS). Data is then stored to MySQL db.

Would so called "IoT" publish/subscribe protocols (XMPP, MQTT) be better? Why?

When exactly do you use those two protocols rather than Restful HTTP? Would I really save a significant baterry energy using them?

AFAIK in those protocols machine would "publish" a data to broker and my app would subscribe to it. If I would like to gather data every minute in my app I guess that I would got to have some CRON job that would subscribe to data every minute? Or how would data gathering be achieved?

In my experience ReST is good for real-time data transfer and processing but has a lot of overhead for simple message passing. Plus, there's no queuing in it so store-forward configurations are troublesome.

MQTT is a message queue transport system where the message can be placed on the channel by the publisher and will stay there until the subscriber picks it up. So you can have some rudimentary store-forward capabilities with this. Also MQTT is more transparent and multicast so communicating to many nodes is no different than communicating to one.

With that, each have their place and use and ReST is great for sending large items (JSON blobs), sending data for calculation and getting it back, and for requesting a specific dataset. MQTT is more for "here's my sensor data every second, enjoy".


Sim808: Is My GPS Module Broken? Is my GPS module broken?

My GPS returns $GPGGA,000250.262,,,,,210,,2,700,,*4C as NMEA. Why there is no latitude longitude? the first value is the UTC time, but there are so many null values ,,,,, Is my GPS module broken?

Edited

My Sim808 model is SIM808 Module GPRS SMS Development Board IPX SMA with GSM GPS Antenna

What makes me think why is this broken is because the day before, the module keep giving me location for every second. The lock was almost instant. I use the module at the same place like before. It is weird because the module is so unstable, yesterday was fine but the next day it takes forever to lock location.

Many fields will empty until the unit can get a lock. $GPGSV messages will tell you how many satellites it currently sees, and how strong the transmissions are. The first lock can take several minutes, and it can be very difficult to get a lock indoors.


Use Arduino Yun Shield as ISP for bootloaded ATMega328-PU My question is how do I replace the Aarduino Uuno board in this circuit:

...With an Arduino Yun shield? I can setup the hardware - ICSP configuration is easy enough - but how do I go about using the IDE to do this? Cheers

It's highly unlikely you will be able to do it from the IDE. Instead you will have to do it from the Yun's command line (SSH) using avrdude and the linuxgpio driver, or the handy run-avrdude script.

$ sudo run-avrdude bootloader.hex

where bootloader.hex is the bootloader file found somewhere in the IDE that you need to copy over to the Yun with scp.

You may find you need to tweak the fuse settings in the script to get the bootloader to work. I am not familiar with AVR fuses, but IIRC there is one that tells it to run the bootloader instead of the sketch. Just copy the values out of the boards.txt in the IDE and place them into a copy of /usr/bin/run-avrdude in your home directory.


Nano clone not working over USB, no data, no power, but can power via Vin (CH340 chip? schottky diode?) My quite new Nano clone (ATmega328P + CH340G) suddenly stopped working. Plugging it in with USB did not light up the LED(s) nor did it get detected by my machine. I looked it up, and found some how-to's (such as this one: Repair Arduino Nano (no power on USB)), which suggested at least some diagnostics.

So I plugged the Nano in to a 5V breadboard power source using the Vin and GND pins, and the power LED lights up, but connecting via USB cable to my machine does not detect it.

So then I used some of the methods mentioned in the link, and used just a normal jumper cable (without soldering) to check if that could magically make it detectable by my machine. No luck. I tried bypassing the voltage regulator by "jumping" over it, and the power LED gets brighter, and "pin 13" LED flashes for just an instant. The same occurs if I "jump" the voltage regulator all the way to either end of what I am guessing is the "Schottky diode".

In all cases, still nothing in terms of being detected by my computer. The cable is fine because I tested with another nano clone, and it gets detected right away.

So, how do I properly diagnose what is going on here? Specifically how do I fix my poor board? How do I find which component is in need of replacing?

Update:

I found some online guides on how to have another Arduino board talk to this one over SoftwareSerial and found that I could get some data flowing through. However, the text was garbled, such that, for example if I was expecting it to say:

  "Please enter some input"

It might read instead:

  "Ulease XYZter some [][]put"

Often with the same characters being garbled in the same way. I tested the Schottky diode the way it was suggested in the video (with some guessing as to the multimeter setting I had to use was, since I have a different model than the one in the video), and it seems the diode is fine. So at this point I am guessing it is the ch340g chip that is toasty, either that, or the ATmega chip itself, which I don't know, but that sounds less likely.

So, could it be that it is the CH340G chip, since I get no power over USB, and the TX/RX over serial is being interfered with? Is there anything else I can do to figure out if it is the CH340G that's damaged before I go about trying to replace it?

Either you have a cable problem or that board is just not working well.

What you call the CH340 chip - when they go bad you get power but NO communications, in my experience.  You can test voltages at the various points like 5V, 3.3V, etc., to see if it getting power.  If it is and you're still not communicating, then if it were me it would go on the shelf for the kids to see.

It no longer can trusted.

Rather than troubleshooting the board it would be worth getting another to compare with.

And if you have more than one cable on hand, try them and see if there are any differences.

But my prediction is that a new board will work and this one will continue to not work.


Can't send serial data throught serial pins but it works with the usb port I am just starting out a project and I am having a little bit of trouble. I want to send data collected from an IR distance sensor, and send it with an XBee Pro S2B to my computer so I can do other stuff with it. The code I am using right now is pretty simple:

void setup()
{
  Serial.begin(9600);
}
void loop(){
 int distance = analogRead(0);
  Serial.println(distance);
  delay(1000);
}

The problem I am having is that when I turn on the arduino with batteries and disconnect the usb cable, the tx light stops turning on and no serial data is sended, AND if I connect it to the computer via USB again it won't work anyway, only works right when I upload the code. The XBees are configured correctly, I have done the chat example on the Building Wireless Sensor Networks by Robert Faludy.

Is it some code error? I must be really obvious.
By the way, when I upload the code and the serial data is sended throught usb, the data displayed on Arduino IDE's console is correct, so the sensor is wired correctly.

I am using an Arduino UNO and I have the XBee's and arduino's drivers installed correctly, and for the XBee I am using the XBee Explorer from Sparkfun

I suggest you try to flash the pin 13 LED in your loop().  It seems like the Arduino is not booting correctly on the batteries?

The serial port on the uno is kinda messy, it shouldn't really be shared with the usb port like that.  I prefer the Leonardo for these applications - where the USB serial and serial pins are totally independent.


Float division returns "inf" and 0 I'm new to Arduino and I'm doing an ultrasonic project where I test for the speed of sound. My code is below and for some reason, this is what the serial port returns:

This is the measured speed of sound: inf m/s
This is the measured speed of sound: 0m/s
This is the measured speed of sound: 0m/s
etc...

Here's my code. Any help's massively appreciated:)

int trig = 13;
int echo = 11;
float target_distance = 0.3;
float recieved;
float speed_of_sound;

void setup() {
    Serial.begin(9600);
    pinMode(trig, OUTPUT);
    pinMode(echo, INPUT);
}

void loop() {
    digitalWrite(trig, LOW);
    delayMicroseconds(2000);
    digitalWrite(trig, HIGH);
    delayMicroseconds(10);
    digitalWrite(trig, LOW);

    recieved=pulseIn(echo, HIGH);
    recieved = recieved*1000000.0;
    speed_of_sound = (2*target_distance)/recieved;
    Serial.print("This is the measured speed of sound: ");
    Serial.print (speed_of_sound);

    Serial.println("m/s");
    delay(3000);
}

Assuming the speed of sound is of the order of 330 m/s, you expect
the round-trip to the target and back to last about 1.8 ms. Then

recieved = pulseIn(echo, HIGH);

should give a value close to 1,800, and

recieved = recieved * 1000000.0;

should make received something like 1.8 × 109.
Then

speed_of_sound = (2*target_distance)/recieved;

gives a speed of sound of 3.3 × 10−10. It is the
correct value if you want that speed in meters per picosecond, but this
is inconsistent with your program printing “m/s” after the value.

The Arduino's Serial.print() is quite dumb with floating point
numbers. It defaults to printing two digits after the decimal point,
irrespective of the order of magnitude of the number. Thus, anything
smaller than 0.005 gets printed as “0”.

I don't quite understand why you got ∞ on the first loop. Looks like
pulseIn() missed the pulse and returned zero, in which case the speed
is computed as 0.6 ÷ 0 = ∞.

The solution is to compute received as

recieved = pulseIn(echo, HIGH) * 1e-6;

This can be remembered by thinking that a quantity (round-trip time) is
a numeric value (pulseIn(echo, HIGH)) multiplied by a unit (1e-6,
which stands for “microseconds”).


Why can't I print this text to LCD? I've been working on this for 4+ hours, and have gotten nowhere.

I have an array of weather conditions, and a number is sent over serial port to indicate which member of the array to print to the LCD.

I'm guessing the problem is in how I'm defining the array. These are my current 2 guesses for how to define it:

String weatherConditions[49] = { "tornado","hurricane","tropical storm","sev tstorms","tstorms","mix rain-snow","mix rain-sleet","mix snow-sleet","freez drizzle","drizzle","freez rain","showers","showers","snow flur","lt snow show","blowing snow","snow","hail","sleet","dust","foggy","haze","smoky","blustery","windy","cold","cloudy","mostly cloud","mostly cloud","part cloud","part cloud","clear","sunny","fair","fair","mix rain-hail","hot","isol tstorms","scat tstorms","scat tstorms","scat showers","heavy snow","scat snowshow","heavy snow","part cloudy","tshowers","snow showers","isol tshowers","not available" };

or:

char weatherConditions[49][16] = { "tornado","hurricane","tropical storm","sev tstorms","tstorms","mix rain-snow","mix rain-sleet","mix snow-sleet","freez drizzle","drizzle","freez rain","showers","showers","snow flur","lt snow show","blowing snow","snow","hail","sleet","dust","foggy","haze","smoky","blustery","windy","cold","cloudy","mostly cloud","mostly cloud","part cloud","part cloud","clear","sunny","fair","fair","mix rain-hail","hot","isol tstorms","scat tstorms","scat tstorms","scat showers","heavy snow","scat snowshow","heavy snow","part cloudy","tshowers","snow showers","isol tshowers","not available" };

I've tried many other ways of defining the array (including "char* weatherConditions"), but I'm sure most of them were just ignorant guesses.

Later in the code I have this to display a member of the array:

lcd.clear();
lcd.setCursor(0, 0);
lcd.print(weatherTodayHigh);lcd.print("/");lcd.print(weatherTodayLow);lcd.print(" ");lcd.print(weatherConditions[weatherCurrentConditionsCode]);
lcd.setCursor(0, 1);
lcd.print(weatherTomorrowHigh);lcd.print("/");lcd.print(weatherTomorrowLow);lcd.print(" ");lcd.print(weatherConditions[weatherTomorrowConditionsCode);
break;

Everything I try ends up causing nothing to be printed on the 1602 LCD display (I have 15 other scrollable "screens" that are displaying just fine on the LCD). The earlier text on this screen (the highs and lows for today and tomorrow) is displaying fine, but after that, where the weather condition text is supposed to be shown, there is nothing.

I'm able to easily display the same weather condition text on the serial monitor (for that I was using "String weatherConditions[49] = {..." and then "Serial.println(weatherConditions[currentValue]);").

How can I get members of a text array to be printed on the LCD?

Ignacio hit the nail on the head. Once I moved the weatherConditions array to EEPROM, the sketch worked perfectly. Also the IDE stopped giving me errors about low RAM.


Constants within array of structs causes strange compiler errors? In my sketch I have the following:

#define HU_ADDR                 0x190;
#define ALL_AUDIO_ADDR          0x1FF;
#define MY_ADDR                 0x360;
#define UNKNOWN_ADDR            0xFFF;

typedef byte MessageID;
enum {
  ACT_UNKNOWN,
  ACT_POWERON,
  ACT_POWEROFF,
  ACT_PASSIVEOFF_0,
  ACT_PASSIVEOFFRARE_0,
  ACT_PASSIVEON_0,
  ACT_KEYTURN,
  ACT_PRESSDISC
};

struct MessageDef {
  MessageID ID;
  word MasterAddr;
  word SlaveAddr;
  byte PayloadLength;
  byte Payload[20];
  char Description[20];
};

MessageDef MessageTable[] = {
  {ACT_POWERON,           HU_ADDR, UNKNOWN_ADDR, 13,  {0x00, 0x60, 0x31, 0xF1, 0x01, 0x01, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "On call"},
  {ACT_POWEROFF,          HU_ADDR, UNKNOWN_ADDR, 13,  {0x00, 0x60, 0x31, 0xF1, 0x00, 0x00, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "off?"},
  {ACT_PASSIVEOFF_0,      HU_ADDR, UNKNOWN_ADDR, 3,   {0x00, 0x11, 0x01},                                                                               "Passive: Weak"},
  {ACT_PASSIVEOFFRARE_0,  HU_ADDR, UNKNOWN_ADDR, 4,   {0x00, 0x11, 0x01, 0x20},                                                                         "Passive: Strong"},
  {ACT_PASSIVEON_0,       HU_ADDR, UNKNOWN_ADDR, 16,  {0x00, 0x74, 0x31, 0xF1, 0x80, 0x13, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x03, 0x03}, "On response"},
  {ACT_KEYTURN,           HU_ADDR, UNKNOWN_ADDR, 11,  {0x31, 0x62, 0x31, 0xF1, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00},                               "Key turned"},
  {ACT_PRESSDISC,         HU_ADDR, UNKNOWN_ADDR, 4,   {0x00, 0x62, 0x31, 0x9F},                                                                         "DISC pressed"}
};

When I compile this, for some reason the Arduino IDE points at the first line and says "expected '}' before ';' token". If I replace the text like so:

#define HU_ADDR                 0x190;
#define ALL_AUDIO_ADDR          0x1FF;
#define MY_ADDR                 0x360;
#define UNKNOWN_ADDR            0xFFF;

typedef byte MessageID;
enum {
  ACT_UNKNOWN,
  ACT_POWERON,
  ACT_POWEROFF,
  ACT_PASSIVEOFF_0,
  ACT_PASSIVEOFFRARE_0,
  ACT_PASSIVEON_0,
  ACT_KEYTURN,
  ACT_PRESSDISC
};

struct MessageDef {
  MessageID ID;
  word MasterAddr;
  word SlaveAddr;
  byte PayloadLength;
  byte Payload[20];
  char Description[20];
};

MessageDef MessageTable[] = {
  {ACT_POWERON,           0x190, 0xFFF, 13,  {0x00, 0x60, 0x31, 0xF1, 0x01, 0x01, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "On call"},
  {ACT_POWEROFF,          0x190, 0xFFF, 13,  {0x00, 0x60, 0x31, 0xF1, 0x00, 0x00, 0x81, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00},                   "off?"},
  {ACT_PASSIVEOFF_0,      0x190, 0xFFF, 3,   {0x00, 0x11, 0x01},                                                                               "Passive: Weak"},
  {ACT_PASSIVEOFFRARE_0,  0x190, 0xFFF, 4,   {0x00, 0x11, 0x01, 0x20},                                                                         "Passive: Strong"},
  {ACT_PASSIVEON_0,       0x190, 0xFFF, 16,  {0x00, 0x74, 0x31, 0xF1, 0x80, 0x13, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x03, 0x03}, "On response"},
  {ACT_KEYTURN,           0x190, 0xFFF, 11,  {0x31, 0x62, 0x31, 0xF1, 0x00, 0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0x00},                               "Key turned"},
  {ACT_PRESSDISC,         0x190, 0xFFF, 4,   {0x00, 0x62, 0x31, 0x9F},                                                                         "DISC pressed"}
};

Then it compiles with no complaints.
....what? Why? Aren't these functionally identical? Why does the compiler care if I use HU_ADDR instead of 0x190?

Don't put a semi-colon at the end of #define.

Whatever comes after #define NAME will be used to replace NAME across the source code.


String input to character array I am in between of project where i am getting string like "hello world" via Bluetooth to arduino I want to list this string into individual character so that I can call any of the character when required, this is not working i am getting only zeros in serial monitor
please suggest what i am doing wrong

char s;
int k[10];

void setup () {
  Serial.begin(9600);
}
void loop () {
  if (Serial.available() > 0) {
    s = Serial.read();
  }
  k[10] = s;
  for (int x = 0; x < 10; x++) {
    Serial.println(k[x]);
    delay(200);
  }
}

There are a few problems with your code sample:

You check for Serial.available()>0, but then assume/grab only one character:

if (Serial.available() > 0) {
  s = Serial.read();
}

It is possible that the serial receive buffer has more than one byte waiting, but you only capture one.

k[10] = s;

You assign the captured character to the last element of the byte array, regardless of all else. This presents two main problems

A C-style string must be terminated with a null character ('\0'), and you have immediately put real data in the position that should contain the terminating byte.
There is no possible way that bytes 0-9 can ever have any data written to them by this code.

Your code assumes that the entire string exists in k[] every time through loop(). Instead, you should assume that it might take hundreds or thousands of times through loop() just to finish receiving your string. The input string should have some kind of end-of-string marker like a newline ('\n') or carriage-return ('\r') (or both) so that your program can look for that and know when the input is fully received.

Below is a simple program that receives a string. Note that it has a portion labeled for when to process the recieved data. That block of code is only entered once a newline and/or carriage return are received.

#DEFINE MAX_INPUT 90

char inputBuffer[MAX_INPUT+1]; // Handles up to 90 bytes in a c-style string, with a null character termination.

void setup()
{
  Serial.begin(115200); // initialization
  inputBuffer[0] = '\0'; //Initialize string to emtpy.
  Serial.println("Begin:");
}

void loop() {

  if (Serial.available()>0)
  {
    char input = Serial.read();
    static int s_len; // static variables default to 0
    if (s_len>=MAX_INPUT) {
      // Have received already the maximum number of characters
      // Ignore all new input until line termination occurs
    } else if (input != '\n' && input != '\r') {
      inputBuffer[s_len++] = input;
    } else {
      // Have received a LF or CR character

      // INSERT YOUR CODE HERE TO PROCESS THE RECEIVED DATA //
      // YOU COULD COPY TO A NEW VARIABLE WITH strncpy() OR //
      // SET A FLAG TO SAY TO START SOME OTHER TASK         //
      Serial.print("RECEIVED MSG: ");
      Serial.println(inputBuffer);

      memset(inputBuffer, 0, sizeof(inputBuffer));
      s_len = 0;             // Reset input buffer here if you
                             // have already copied the data.
                             // If you don't reset here, then
                             // you can't start receiving more
                             // serial port data. This is your
                             // 'software' serial buffer, contrast
                             // with the hardware serial buffer.
    }
  }
}


Compare const char * to const char Using ArduinoJson I have assigned a value such as;

const char* id = root["id"];

in the original JSON id was "1"

if (strcmp(id, "1") == 0) {
    // this executes
}

I have an array of structs that I wish to compare the id against. The struct looks like;

typedef struct  {
   char id[2];
   ....
} Device;

I assign an id (1-9) into the struct id by

_cmd.id[0] = '0' + (++DevicesPtr);
_cmd.id[1] = '\0';
Devices[DevicesPtr-1] = _cmd;

where _cmd is of type Device. Devices is an array with up to 8 entries
Now I try to find a match in the devices using the JSON id

for (byte i = 0; i < DevicesPtr; i++) {
    if (strcmp(Devices[i].id, id) == 0) {
       // This code does not execute
    }
}

I can't seem to get a match I have also tried (Devices[i].id == id)

Try something like this:

typedef struct  {
  char id[2];
  ....
} Device;

const int DEVICES_MAX = 8;
Device Devices[DEVICES_MAX];

for (int i = 0; i < DEVICES_MAX; i++) {
  Devices[i].id[0] = '1' + i;
  Devices[i].id[1] = 0;
  ...
}

for (int i = 0; i < DEVICES_MAX; i++) {
  if (!strcmp(Devices[i].id, id)) {
  ...
}

Cheers!


Interrupt handler in library This is my first library so feel free to burn me and vote this down :D
This is a library that provides me with Watchdog deep sleep on my ATtiny85 projects.

In the test sketch I use the watchdog timer's interrupt vector but I want to place this within the library. How can I do this?

I have tried to add this to the init method but that did not work out;
powernap.h:26: error: expected unqualified-id before string constant
     ISR(WDT_vect) {

Also; feel free to shoot at the rest of the library, I am here to learn.

Test Sketch

#include "powernap.h"

#define LED 0

Napper napper = Napper();

volatile boolean f_wdt = 1;

ISR(WDT_vect) {
  f_wdt=1;
}

void setup() {
  delay(2000);
  napper.setup(8); // configure watchdog timer
}

void loop() { // blink
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
  delay(200);
  digitalWrite(LED, HIGH);
  delay(200);
  digitalWrite(LED, LOW);
  delay(200);

  napper.sleep(); // deep sleep
}

powernap.cpp

#include "powernap.h"

 #ifndef cbi
   #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
 #endif
 #ifndef sbi
   #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
 #endif

Napper::Napper() {

}

void Napper::init(float initial) {
//  volatile boolean f_wdt = 1;

//  ISR(WDT_vect) {
//  f_wdt=1;
//  }
}

void Napper::setup(int cycle) {
    byte bb;
    int ww;
    if (cycle > 9 ) cycle=9;
    bb=cycle & 7;
    if (cycle > 7) bb|= (1<<5);
    bb|= (1<<WDCE);
    ww=bb;

    MCUSR &= ~(1<<WDRF);
    // start timed sequence
    WDTCR |= (1<<WDCE) | (1<<WDE);
    // set new watchdog timeout value
    WDTCR = bb;
    WDTCR |= _BV(WDIE);
}

void Napper::sleep() {
    cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

    set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
    sleep_enable();

    sleep_mode();                        // System sleeps here

    sleep_disable();                     // System continues execution here when watchdog timed out
    sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

powernap.h

#ifndef Fader_h
#define Fader_h

#if ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
  #include "pins_arduino.h"
  #include "WConstants.h"
#endif

#include <avr/sleep.h>
#include <avr/wdt.h>
#include <util/delay.h>

class Napper {
    public:
        Napper();

        void init(float initial);
        void setup(int cycle);
        void sleep();

    private:
        int flag;

};

#endif

It is hard to help you improve your library or code if you don't tell others what your code pieces are trying to do.

In general, you will have a piece of code that sets up the whole thing, a piece of code that will be executed in the isr, and other helper code pieces, like getting status and clear status, as appropriate.

I often use a function pointer that the user can hook to the user handler so my isr portion of the code is fixed. Just hook to different functions in the user space and you are ready to go.

Obviously other ways exist, each with their pros and cons.


Is the DigitalWriteFast library still needed? Yesterday I played with a SRAM 621024 SRAM 1 Mbit IC and since I use a lot of pins, digitalReads and digitalWrites are needed including shift registers (see Example

Since it took a long time for reading/writing one byte, I checked for faster ways and found some posts, one of them was using digitalWriteFast:
Library

However, it did not make any difference... is it possible that the (fast) digitalWrite is already implemented in the default Arduino IDE/library?

Update: I found out I made a stupid mistake and the library was not used.

Now I get different values:

Writing 397.880 us per byte
Reading 386.524 us per byte

Without the fast library:

Writing 502.152 us per byte
Reading 483.752 us per byte

Note, there is also a digitalReadFast, but this does not affect the speed.

I did some more testing and found out that a digitalReadFast/digitalWriteFast cost just about 8-12 us, a pinModeFast is 0 us (negligable), however a shiftOut for setting the address cost 120-124 us ... since 3 shifts are needed to set an address, this results in 360-372 us. Subtracting this from the measured times above, writing takes around 25-38 us and reading 15-27us. I possibly can maybe optimize the bit operations a little bit.

However, the end result for using this RAM chip with enough speed is to either change the shift register to a faster one or remove the shift registers at all. This would mean about 30 pins needed for the SRAM only. The conclusion is: better use a 3K256, 23LC1024 or similar variant.

(Note: I tried a ShiftOutFast file), which reduces a shiftout to 36 us but 3 times 36 is still over 100 us, too much to compare to a 3K256/23LC1024 solution.

I just tried to time digitalWrite() against direct port access with
the following code:

void setup()
{
    uint16_t overhead, start, end;

    Serial.begin(9600);
    TCCR1A = 0;
    TCCR1B = 1;

    // Time digitalWrite().
    overhead = 7;
    cli();
    start = TCNT1;
    digitalWrite(2, HIGH);
    end = TCNT1;
    sei();
    Serial.print("digitalWrite(): ");
    Serial.print(end - start - overhead);
    Serial.println(" cycles");

    // Time direct port access.
    overhead = 4;
    cli();
    start = TCNT1;
    PORTD &= ~_BV(PD2);
    end = TCNT1;
    sei();
    Serial.print("direct port access: ");
    Serial.print(end - start - overhead);
    Serial.println(" cycles");
}

void loop(){}

The result was:

digitalWrite(): 78 cycles
direct port access: 2 cycles

I used an old Arduino core (1.0.5), but that function has not changed
since. You can try with your current core and see.

PS: In this program, the correct value for overhead can only be
determined by examining the generated assembly. It's a count of the
cycles you are measuring but do not directly belong to the operation you
really want to measure.


Reading serial buffer taking newline character instead of user input I am trying to compare whether the user input matches a user ID or not. When I read the input from serial, the program is taking the last character which is newline char '\n' and moving it into the char data value to compare against the stored user ID and I don't understand why it's taking the '\n' value instead of the actual user input.

int Gled = 7;
int Rled = 8;
int wait = 5000;
char UserID = "12345";
char data;
char incoming;

void setup() {
  Serial.begin(9600);
  pinMode(Gled,OUTPUT);
  pinMode(Rled,OUTPUT);
  Serial.println("Please Enter your username or ID:");
}

void loop() {
  if(Serial.available()>0) {
    while(1) {
      data=Serial.read(); //read user input and move to data char
      if(data !='\n')
        incoming = data; //if data doesn't equal newline data = incoming
      if (data == '\n')
        break; // newline char detected break
      if (data == -1) //continue reading all of user input
        continue;
      Serial.print(data);
      Serial.print(incoming);
    }
    Serial.println(incoming);
    if(incoming == UserID) { //if user input matches run statement
      digitalWrite(Gled, HIGH);
      Serial.println();
      Serial.println("Access Granted");
      Serial.println("Hello User Name");
      delay(wait);
      Serial.println("Login time exceeded, you are now logged out.");
      Serial.println("Reenter your UserID to log back in.");
      digitalWrite(Gled, LOW);
      Serial.end();
      Serial.begin(9600);
    } else if(incoming != UserID){
      //user input doesn't match run statement
      digitalWrite(Rled, HIGH);
      Serial.println();
      Serial.println("Access Denied");
      Serial.end();
      delay(wait);
      Serial.begin(9600);
      digitalWrite(Rled, LOW);
      Serial.println("Please Enter a Valid ID to Continue.");
    }
  }
}

if(data !='n')

This should be

if(data !='\n')

NEXT.

data=Serial.read();

only reads ONE character. You should add to a buffer, not assign a single character.


Student Code: map function not functioning We made this code in class:

 int red = 6;
  int green = 7;
  int blue = 8;
  int pot = A0;
  int potVal = 0;
  int chosenColor = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(pot, INPUT);
  Serial.begin (9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  potVal = analogRead(pot);
  chosenColor = map(potVal, 0, 1023, 1, 3);
  if(chosenColor = 1) {
    redCycle();
  }

  else {
    analogWrite(red,255);
  }

  if(chosenColor = 2) {
    greenCycle();
  }

  else {
    analogWrite(green,255);
  }

  if(chosenColor = 3) {
    blueCycle();
  }

  else {
    analogWrite(blue,255);
  }
  Serial.println(chosenColor);
  Serial.println(potVal);
  delay(500);
}

void redCycle() {
    analogWrite(red,0);
  for(int i=0; i < 256; i+=5) {
    analogWrite(red, i);
  }
}

void greenCycle() {
  analogWrite(green,0);
  for(int i=0; i < 256; i+=5) {
    analogWrite(green, i);
  }
}

void blueCycle() {
  analogWrite(blue,0);
  for(int i=0; i < 256; i+=5) {
    analogWrite(blue, i);
  }
}

When we open the serial monitor we find that chosenColor is always 3 regardless of what the potVal is reading. I am sure is something simple but we can't find where is the error. Please help.

As Edgar Bonet pointed out,  “chosenColor = 3 means 'let chosenColor take the value 3'”.  That is, your  potVal = analogRead(pot);  chosenColor = map(potVal, 0, 1023, 1, 3); sequence may very well be working, but by the time you get to Serial.println(chosenColor); you have changed chosenColor to 3.

First, the statement if(chosenColor = 1) {...} changes chosenColor to 1. Then the statement if(chosenColor = 2) {...} changes chosenColor to 2.  Finally, if(chosenColor = 3) {...} changes chosenColor to 3, just before you print out the current value of chosenColor.

When you wish to compare two numeric values for equality, use == instead of =.


Confusion with ATmega328P and 3.3V/8MHz Firstly, I have tried to set the bootloader to be 8MHz internal oscillator.

I have tried the board setup from here - https://github.com/oshlab/Breadboard-Arduino.

And also the breadboard-1-6-x.zip setup from here - http://www.arduino.cc/en/Tutorial/ArduinoToBreadboard.

Burning the bootloader in both cases seems to work, with fuse settings of -Uefuse:w:0x05:m -Uhfuse:w:0xDA:m -Ulfuse:w:0xE2:m (using Arduino IDE 1.6.7):

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0x05:
avrdude: load data efuse data from input file 0x05:
avrdude: 1 bytes of efuse verified
...
avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xDA:
avrdude: load data hfuse data from input file 0xDA:
avrdude: 1 bytes of hfuse verified
...
avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xE2:
avrdude: load data lfuse data from input file 0xE2:
avrdude: 1 bytes of lfuse verified

When I try and run the test sketch (below) at these voltages:

3.3V it fails (tried multiple 3.3V sources, all fail).
4.23V (3xAA rechargeable batteries) it works.
4.8V (3xAA alkaline batteries) it works.
5V it works.

To try and determine if it was my power sources or the bootloader that was the problem I uploaded this test sketch on my ATmega328P, an Arduino Nano (all Nanos are 16MHz?) and a 16MHz Arduino Pro to see if the red LED (with 100 Ohm resistor for ATmega328P) lights up in about the same time. This test sketch also does not work at 3.3V, and must be run at 5V to work.

(edit) When running this test sketch at 3.3V I see no 3.3V logic level on any output pin with my multimeter.  When running at 4.23, 4.28, 5V I see this logic level on all output pins.

(update) When connecting the +ve of the LED directly to 3.3V, the LED lights up.  So the 3.3V source has enough power to light the LED directly.

So I assumed that because my ATmega328P circuit has no crystal in it (and the Nano and Pro Mini are 16MHz), these loops would execute in different amounts of time?  But no, the loops do execute at the same speed (3 and a bit seconds) - so is my Nano/Pro Mini underclocked, or my ATmega still running at 16MHz but without a crystal??  Rather confused.

Thanks.

(update) I tried a second ATmega328P, same problem.

(code edited to use 14 output pins)

void setup() {
  for (int p=0; p<14; p++) pinMode(p, OUTPUT);
}

void loop() {
  // waste some time.
  int y = 0;
  for (int i = 0; i < 11; i++) {
    for (int j = 0; j < 11; j++) {
      for (int k = 0; k < 101; k++) {
        y+=analogRead(A0);
      }
    }
  }
  for (int p=0; p<14; p++) digitalWrite(p, y % 2);
  for (int p=0; p<14; p++) digitalWrite(p, HIGH);
  delay(1000);
  for (int p=0; p<14; p++) digitalWrite(p, !(y % 2));
  for (int p=0; p<14; p++) digitalWrite(p, LOW);
  delay(1000);
}

If you are using an LED to indicate that your sketch is running, then that may be the problem.

For example, if you have a fairly average red LED, it might have a forward voltage of 2.0v @ 20ma (refer to your spec sheet for your particular LED). Putting these values into the LED calculator, it would tell you that you need a 150 ohm resistor. You might have tested this, and seen the LED light up.

Then, if you drop the voltage to 3.3v, your LED might be either very dim, or (more likely!) not light up at all. Putting 3.3v into the same web page, it shows you need a smaller resistor, 68 ohm, for the same LED.

P.S. - I just noticed your paragraph about the green LED - a "true green" LED might have a voltage drop of 3.3v, which means for 5v you would need a 100 ohm resistor (as described in your paragraph); for a 3.3v supply you would need a 1 ohm resistor instead. This is pretty certainly your problem


Sending file from PC to Arduino How can i send a (file) from PC to Arduino Yun at running time ?

There's a way to send some commands via Serial.
But how would a whole file goes ? Assuming the file can take place at RAM without any problems.

Thanks

You can send a file, byte after byte, using Serial.
On the Arduino side, you parse serial communication and put bytes inside an array. At the end, you reconstruct the file.


Read and store data with the usb Hi i am new to Arduino and I want to know if it is possible to read the data from a sensor that it is connected to the Arduino, I am using the Arduino mega 2560, which is already working, as I have a LED which change color depending on the detection of the object and then store it in a file as txt or another normal extension.

I don't have experience with Processing, but probably that is what you need. It communicates through USB and with the CreateWriter function, you can create a text file.

More about Processing can be found at Processing

Also another thread at Electronics stack exchange might help:

Related question

Alternatives (also mentioned in the above thread):

Use serial port directly with a terminal application on the PC
Use an SD card inside the Arduino to log


Existence of a non blocking and task yield framework for Arduino programming I've been playing around with Arduino and understand that the standard runtime provides a single thread essentially.

I was wondering if it is possible to write a thin layer (library) that allows one to write code that is non blocking and one where each task yields control manually which allows the master loop to implement some form of timesharing.

I'd appreciate any:

Comments on existing frameworks that can allow me to write my programs this way
Any comments on how hard implementing anything of this order of magnitude would be.

I would recommend NilRTOS.
I like the fact that it's really minimal.
However, you might find that some libraries (which you would like to use) work in blocking mode and cannot be used with this RTOS, because they might do bad things (polling) or worse things (polling in interrupt context with other interrupts disabled).
But that will be the case regardless of the thread framework you choose.

You might want to try also femtoos.
I think that the code could be organized far better, which is one of the reasons I preferred NilRTOS.


Convert string into char array in Arduino? I am not that great at Arduino and C++ yet, but I'll give this a shot:

I have a char array that looks like this:

char PROGMEM bitmap[] = {0xD7,0xED,0xEF,0xFF,0xF6,0xEF,0xFE};

However, I receive this char array from a string, which is basically:

String input = "0xD7,0xED,0xEF,0xFF,0xF6,0xEF,0xFE";

How do I turn my input variable with a comma separated char array into the actual array? I need it to be fast and not use a lot of memory. I haven't been able to find a use case like this, because it's very unique.

I feel like this should be super simple to do, but I can't wrap my head around it.

Things I've tried and didn't understand that much:

1:

char delimiter[] = ",";

char* ptr = strtok_r(text, delimiter);

while (ptr != NULL) {
  Serial.println(ptr);
  ptr = strtok_r(NULL, delimiter);
}

  cannot convert 'String' to 'char*' for argument '1' to 'char* strtok(char*, const char*)'

2:

char buf[4800];
text.toCharArray(buf, 4800);
char *p = buf;
char *str;
int i = 0;
char bitmap[115];
while ((str = strtok_r(p, ",", &p)) != NULL) {
  bitmap[i] = str;
  i++;
}
Serial.println(bitmap);

(the total length of my characters are 4799 and the total length of hexadecimals are 114, so I'm just trying something here)

Error: Apparently you can't use  =?

3:

char buf[4800];
text.toCharArray(buf, 4800);
char *p = buf;
char *str;
while ((str = strtok_r(p, ",", &p)) != NULL) {
  Serial.println(str);
}

This actually prints the strings to the console, but trying to add them to a char array is still a mystery I am trying to solve right as I write this.

4:

char buf[4800];
text.toCharArray(buf, 4800);
char *p = buf;
char *str;
char *ptr;
char bitmap[115];
int i = 0;
while ((str = strtok_r(p, ",", &p)) != NULL) {
  bitmap[i] = strtol(str, &ptr, 16);
  i++;
}

Serial.println(bitmap);

I'm getting a lot closer now. strtol(str, &ptr, 16) actually gives me the right integers I need, but it seems like my Arduino crashes when I run this code. It simply reboots it. Error:

  assertion "heap != NULL && "free() target pointer is outside heap areas"" failed: file "/Users/ficeto/Desktop/ESP32/ESP32/esp-idf-public/components/heap/./heap_caps.c", line 171, function: heap_caps_free
  abort() was called at PC 0x4011c173 on core 1

So after a lot of help and some tweaking, I finally got it to work!

String text = server.arg(0);

char buf[text.length()];
text.toCharArray(buf, text.length());
char *p = buf;
char *str;
char bitmap[960]; //960 is fixed for now, need to count amount of commas + 1
int i = 0;
while ((str = strtok_r(p, ",", &p)) != NULL) {
  bitmap[i] = strtol(str, NULL, 16);
  i++;
}

bitmap now contains all the XBM data from the GET request. I ran into some issues, causing the device to restart, because I accidentally forgot that the length of the bitmap array isn't 114 (that's the amount of horizontal pixels of the display). This caused it to overflow by a lot.

Huge thanks to jose can u c for helping me.


Electric meter with Arduino and RS485 module I'm a Arduino newbie. I have an Electric meter with an RS485 output. I want to get the MeterID value over the RS485 module and the Arduino. I just have document from manufacturer.

Sent by computer : 68 99 99 99 99 99 99 68 01 02 67 F3 C3 16.
Return from meter : FE 68 99 99 99 99 99 99 68 81 08 67 F3 A6 9B 34 4B 33 33 6F 16.

My Arduino code:

#include <SoftwareSerial.h>

#define SSerialRX        10
#define SSerialTX        11
#define SSerialTxControl 3
#define RS485Transmit    HIGH
#define RS485Receive     LOW

SoftwareSerial RS485Serial(SSerialRX, SSerialTX);
byte request[] = {0x68, 0x99, 0x99, 0x99, 0x99, 0x99, 0x99, 0x68, 0x01, 0x02, 0x67, 0xF3, 0xC3, 0x16};
int byteRead;

void setup()
{
  Serial.begin(9600);
  RS485Serial.begin(1200);
  pinMode(SSerialTxControl, OUTPUT);
  digitalWrite(SSerialTxControl, RS485Receive);
  delay(20);
  Serial.println("Get Meter Address App");
}
void loop()
{
  digitalWrite(SSerialTxControl, RS485Transmit);
  RS485Serial.write(request, sizeof(request));
  delay(2000);
  digitalWrite(SSerialTxControl, RS485Receive);
  delay(2000);
  if (RS485Serial.available())
  {
    byteRead = RS485Serial.read();
    Serial.println(byteRead, HEX);
  }
}

Serial Monitor show:

I'm using combo like this topic modbus-rtu-controller-monitoring-with-arduino-and-rs485-module. My code is in C# below. I used the code before and it worked fine, but on the computer I use a COM port (Baudrate 1200, data 8bits, Parity EVEN, Stopbit 1) with an RS485-R232 converter:

#Send data
dataOUT = WriteData("68 99 99 99 99 99 99 68 01 02 67 F3 C3 16");
serialPort_Meter.Write(dataOUT, 0, dataOUT.Length);

#WriteData method
private static byte[] WriteData(string hex)
{
return hex.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray();
}

#Read data
private static string ReadData(SerialPort serial)
{
byte[] buffer = new byte[serial.BytesToRead];
serial.Read(buffer, 0, buffer.Length);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buffer.Length; i++)
sb.AppendFormat("{0:X2} ", buffer[i]);
return sb.ToString();
}

Using readBytes would do the same as your C# code. readBytes is blocking. It will wait for every byte until timeout. Default timeout is 1 second. If the count of bytes is smaller then the size of the buffer, it will wait a second after the last byte received. You can set the timeout with RS485Serial.setTimeout(500); (500 milliseconds for example).

void loop()
{
  digitalWrite(SSerialTxControl, RS485Transmit);
  RS485Serial.write(request, sizeof(request));
  RS485Serial.flush();
  digitalWrite(SSerialTxControl, RS485Receive);
  int recvLen = RS485Serial.readBytes(buffer, sizeof(buffer));
  for (int i = 0; i < recvLen; i++) {
    Serial.println(buffer[i], HEX);
  }
}