Exoskeleton Motor Control Code Background:

I have been working on an exoskeleton project with a group of friends, and I need help.  I made another post on the robotics.stackexchange site for the drive system: https://robotics.stackexchange.com/questions/4323/exoskeleton-drive-system-help.  You can also check out our first prototype on youtube: https://www.youtube.com/watch?v=NL_aCwJSRiE&feature=youtu.be

The device is going to be controlled by an iPad that we created via bluetooth.  We are using the adafruit bluefruitLE

We are attempting to control 4 motors (2 knee motors and 2 hip motors) from an Arduino Mega.  We will be using 2 Roboclaw 2x60A motor controllers.  We are trying to get the motors to mimic the graph (see attached).

The graph is in degrees per percent cycle (a gait cycle).  We are using 50 gait cycles per minute for tests but we hope to make it adjustable.
We can change percent cycle to time in milliseconds using dimensional analysis (ie) 50 cycles/min = 8.333x10^-4 cycles/ms  —->  1/8.333x10^-4 cycles/ms is approx. 1200 ms/cycle.  So if you multiply the cycle times 1200 you get millisecond for a certain percent of the cycle (ie) 0.5cycles(50 percent of cycle) * 1200ms/cycle = 600 ms.

We will have a position feedback system incorporated in the drive system but because it is a prototype and I wanted to make the code as versatile as posible I created a function: getDegrees(int jointNum), so if I change the position feedback system I only have to change the getDegrees method.

In order to mimic the graph we broke the graph up into sections.  Each section represents a different velocity.  We are going to run a correction algorithm so far we have just done the P in PID, we have used a modifier of 1.5.  Then we saved the value that the section ended on so next gait cycle when it runs that section the algorithm will start off closer to the target value.

My question:

I need help developing a strategy in order to sync the movement of the 4 joints while running a correction algorithm on each joint individually.  While the device is running we need to be able to constantly check for a bluetooth message from the iPad.  The bluetooth messages come in via SPI from the adafruit bluefruitLE.

What I have done so far:

I have been able to run a single joint by using a while statement (ie)

int i = 0;
void loop(){
targetAngle = nextAngle[i]; //nextAngle is an array of points so nextAngle[0] through nextAngle[1] represents one section of the graph.
i++
if (getDegrees(1)< targetAngle){
double deg = getDegrees(1);
while (deg<targetAngle){
/*
*
*Execute drive code
*
*/
deg = getDegrees(1);
}else{
double deg = getDegrees(1);
while (deg>targetAngle){
/*
*
*Execute drive code
*
*/
deg = getDegrees(1);
}
}
}

The main problem with that code is its like using the delay() function instead of millis() is that it stops the program while its executing the code, and I cannot run multiple motors and check for bluetooth messages.

Major Challenges:

The drive commands must be based off of angle and not time.  It is ok if we tell it do 50 cycles per minute and it does 52 or 48 but its not okay if it only does 97% of the motion.

Possible solutions I have come up:

Using one arduino for each joint, and making them all slaves of a master arduino and the master arduino would act as the middle man sort of between the joints, making sure that they are synced up.  That way each arduino could use code similar to what I have already tried and confirmed to work.  But I would prefer to run it all from one arduino.

Conclusion:

I need help developing a strategy in order to sync the movement of the 4 joints while running a correction algorithm on each joint individually.

Is this the right forum for this question?  Or is it more of a Stack Overflow or Robotics question?

Any help will be greatly appreciated,

--
Joel

Here's what I came up with:

You have a certain percent of the gain cycle equal one "step" (step may be a bad term in this situation, but I'm using it because of stepper motors).
You have a blocking function that will move the motors and control all the P(ID) logic

Before this function is called, the main code will use a variable to store the desired time to do the next "step."
It will have a loop with "substeps." So it would look kinda like this:

void function nextStep(int var1, int var2) {
    //Read sensors and put into variables
    until(condition == true) { //Condition to see if the motors are at the right degree
        //Adjust motors not in the right place
        delayAndCheckBT(10); //Look at the bottom for this function
    }
}

You could also have it accept a few percent of variance as tolerance so it's not shakey, but that's more of the PID control than anything. You'll have to make sure that many 'steps' doesn't make the PID controller unstable.

When that code is done, the main function will check to see if the desired time for the next step has passed (or if it's now). If it's passed/now, then it will execute. Otherwise, it will not execute the next step and continue executing the main loop.

Great? No. The problem is you need to check for bluetooth! To do this, I've made two functions:

void checkBT() {
    //Checks BT. Make sure this is non blocking: if you need to, set a few global variables
    //Note this code will get called a LOT, so don't implement any delays or loops: inside here: use millis().
}
void delayAndCheckBT(int timeToWait) {
    unsigned long finishTime = millis() + timeToWait;
    while (millis()<finishTime) {
        checkBT();
    }
}


STM8 Development Board with Arduino IDE I got one of these cheap STM8 boards from China and was hoping to find a way to use this with arduino code.

Does anyone know of an arduino boot loader and board package that works with them ?

There is a bootloader on those chips to slow serial programming. A much easier way to to get a stlink debugger.

There are also some packages that allow Arduino styled programming on those chips. I wrote one myself that runs on iar and I think at least one on sdcc.

Those chips are really nice.


Can I make a 455Khz Sine Wave with the Arduino UNO? Can any one help me, I need to make a sine-wave of 455Khz for use in aligning a Super 7 - AM Radio.

I looked into buying a function generator but I have an Arduino UNO. Can this do the tasks?

The Arduino does not has a DAC (digital analog converter), so you cannot make an output varying in voltage (except for 0V / 5V) by default.

The PWM outputs use 0V/5V with duty cycle but this is not a sine wave.

So you need additional hardware anyway.

Also, regarding speed if you have a DAC. Assume 16 MHz for the Arduino, having a 455 Khz sinewave, you have about 35 clock cycli per complete sine wave. The sine values you can store in a table, but you need probably at least 3 or 4 clock cycli per sine wave value (to fetch the value from the table and to send it to the DAC), this results in about 8 values which will give a very rough sine wave.

So I would go for a separate sine wave generator.


Library LiquidCrystal_I2C don't work in other class (Composition) Good afternoon, I'm trying to use a class to streamline the writing on the LCD. In this class I have an private attribute (it's a pointer, do not know how I call him) called  LiquidCrystal_I2C* _lcd, I instantiate it in the constructor, so far so good, but when I call the _lcd-> begin (20, 4) the code below is not executed, but no error is displayed.

Display.h:

class Display{
    public:
        Display();
        ...
    private:
        LiquidCrystal_I2C* _lcd;
        ...
}

Display.cpp:

...
Display::Display() {
    _lcd = new LiquidCrystal_I2C(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
    _lcd->begin (20, 4);
}
...

Program.ino

#include "Display.h"

Display lcd;

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

void loop() {
    Serial.println("test");
    delay(3000);
}

Just I noticed the error when I saw that Serial.println ("test"); was not running. If I comment the _lcd->begin (20, 4); everything works.

I tested writing everything in Program.ino and worked, has nothing to do with connections or something, just do not apply the concept of composition with this class.

Can someone help me? And sorry for the English, i'm from Brazil. Thanks.

Most likely cause

You are hitting an insidious problem that even experienced C++ programmers frequently miss: order of initialization of global variables. In your case, Display lcd is initialized (i.e., its constructor is called) before main() and subsequently setup() are executed. However, you almost certainly are #includeing whatever library is declaring the LiquidCrystal_I2C class, probably Wire.h, and so on. In many of these classes, a global variable of that type is also defined to make it easier to access stuff. For example, Serial (as in Serial.println("foo")) is really a global variable of the appropriate type of whatever serial implementation your particular core is using.

The problem you are hitting is that the C++ standard does not guarantee the execution order of the constructors of global variables. The order is an artifact of the compiler, the order in which object files were linked, and probably the phase of the moon :)

What is (almost certainly) happening is that the constructor for your class Display is being called, which initializes the LCD and the i2c bus, and then something else calls either the LCD constructor or the i2c constructor and messes things up.

OK, "how do I fix this?" I hear you ask. Simple: make the global lcd variable a pointer, and allocate the instance in begin(), like so:

#include "Display.h"

Display *lcd;

void setup() {
  Serial.begin(9600);
  lcd = new Display();
  // stuff
}

void loop() {
  // more stuff
  lcd->some_method(some_argument);
  // even more stuff
}

Now you are guaranteed that your code will be the last to touch any initialization code that might affect the display or the bus. Just keep accessing the class Display methods through the pointer.

A less likely cause

It is still possible that your constructors are getting executed in the right order, but your hardware does not like being initialized twice (but test that anyway!), so you may have to figure out how to reset the hardware so you can initialize it again. If I understand your posting correctly, the loop never runs, which means that a second initialization probably either causes a exception (which you would not see unless you had some kind of additional debugging channel; in the case of the ESP8266, for example, that would be the output-only Serial1 port, and even then, you'd have to explicitly turn on debugging. Each core has its own debugging stuff, I forget what the real Arduino does.)

Hope this helps.

/ji


Waking up async the Arduino while it's sleeping periodically I´m using LowPower.h and PinChangeInt.h libraries to put my Arduino into the sleep mode every 8 seconds and then it wakes up, modifies a counter and it goes to sleep again, but also I need to wake it up when a button is pressed asynchronously.

I´ve reached to wake up the Arduino every 8 seconds using LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF) and, in other code, I´ve also reached to wake it up while it sleeps indefinitely with LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF) but I can´t combine that periodical awakening with the asynchronous awakening.

Here is my code:

void setup(){

    Serial.begin(9600);

    //Pines declaration

    loopsToSend = setTimeToSend();  //

    //The three async buttons
    PCintPort::attachInterrupt(4, readOpinion,RISING);
    PCintPort::attachInterrupt(5, readOpinion,RISING);
    PCintPort::attachInterrupt(6, readOpinion,RISING);
}

void loop(){

    if(loops < loopsToSend ){

        byte opinionValue = readOpinion(); //This method must awake the Arduino ASYNC to give a value to the opinionValue var, write the result in the file and go to sleep

        if(opinionValue != 0){
            Serial.println("Button pressed!");

            //Writing result in a file
            opiniones++;
            delay(500);
        }
        //Go to sleep 8 seconds
        LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
        opinionValue = 0;
    }
    else {
        wdt_disable();

        if(opiniones > 0){
            //Send file using GSM module
        }
        else{
            loops = 0;
        }
    }
    loops++;
}

Can anyone help me? Thanks

This one works for me:

#include <PinChangeInterrupt.h>
#include <LowPower.h>

// I want to know when it was interrupted by PCINT:
volatile byte flag = 0;
void handler() {
    flag = 1;
}

void setup() {
  Serial.begin(115200);
  pinMode(A0, INPUT_PULLUP);
  attachPCINT(digitalPinToPCINT(A0), handler, CHANGE);
}

void loop() {
  Serial.println("entering powerDown sleep mode");
  Serial.flush(); // wait for sending all data

  LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);

  if (flag == 1) {
    flag = 0;
    Serial.println("Pin change interrupt");
  } else {
    Serial.println("Timeout");
  }
}

However if you use RISING (or FALLING), it also wakes up from the sleep when pin changes back to the oposite state (and it'll be reported as Timeout).


How to link a computer processor to an Arduinno on a board? I am completely new to Arduinno, so please forgive if the question is stupid.

Here is the problem: I have a project where I want an Arduino (or similar microchip board) to handle some sensors and actuators. But I need very advanced "artificial intelligence" to handle the data provided by those sensors.
There are two major obstacles for placing this intelligence on the Arduinno, according to my researches.

First, the Arduinno is coded in a language similar to C: I could of course find a way to write the intelligence, but it will be a time-consuming task for the developper
Second, I might encounter a problem with memory: I will store heavy matrix of data, do complicated calculation, and this might be too much for an Arduinno
Third, I read on stackexchange that there are some ways to compile Python code on Arduinno boards, such as the Arduinno Mega. So I can code this intelligence in Python (which is an easy task), and compile the resulting code on Arduinno. However, I will reach a caveat: some libraries I will use will be entirely compiled, and this will take too much memory on an Arduinno (such as the second issue I mentionned)

So I have another solution, but I am not sure if it is state-fo-the-art, or even a feasible solution:
I would like to separate two tasks:

Write an Arduinno code to handle the sensors and create numeric data
Write a Python code on my computer and compile it as an executable file on my computer
Then somehow, I "extract" the processor of my comouter (Intel, by the way) and I plug it on the Arduinno board. The Arduinno sends the data to the processor, and the processor runs permanently the Python file and gives back data

So question:

Is it possible overall?
Was it ever made?
What communication links are good for exchanging data between processor and Arduinno microchip: USB, Serial, Ethernet?
How can I handle the input of the processor, so that it collects data from the Arduinno and then uses it in the Python code?

It sounds like you need a lot of compute power. You can either put the sensors and AI on one device (and @majenko's suggestion of a Raspberry Pi would be a direction to pursue) or you need two devices, one to manage the data collection - Arduino, perhaps -  and one to do the AI. We don't know enough about your post-processing and AI to make a good recommendation, but, as you already have a PC with Python running on it, an Arduino talking to the PC would be a good start.

You didn't say which Arduino you're considering, but as most people mean "Uno" when the speak of a generic Arduino, I'd just suggest that an Uno is far too under-resourced for the post-processing part of your project, but probably ideal for the data collection. Cross-compiling your Python code for an Uno still doesn't address its processing speed and memory size limitations.

There are, of course, a lot of "Arduino" products, some with considerably more resources, that may approach your needs - I'm thinking of the Arm-based boards, here - but I've no way of evaluating your project needs at that level.

My own first approach would be to use what you have, to start with: an Uno collecting data and sending it to your PC. Once you have something running, you'll understand the needs and issues better and if you still want a stand-alone solution at that point, you'll be much better able to make that choice.


Arduino R/C compatible transmitter and reciever I want to make a RC buggy or something down those lines (using Legos of course) and I'm confused while looking what transmitter/receiver to use. Would like a simple classic remote and any compatible receiver for the Arduino.
Found such a remote: http://www.hobbypartz.com/79p-th9x-r9b-9channel-radio.html
But this seems way overkill for what I want to do. Any links or suggestions would be appreciated. Hope the question isn't too broad for stack exchange.

If you want to involve an Arduino on the receiver, you may want to choose a transmitter which is compatible with a 2.4 GHz chipset that is both available, and for which you can find Arduino code.  The NRF24L01+ and Beken compatibles are probably the most available, and a lot of RC toys use something compatible, though getting firmware right to interact with them can be tricky.  Beware that there are some other chips in wide use too, which can be harder to source a module for.

You can use an off-the-shelf multi-channel receiver, but that will tend to output each channel on a distinct PWM pin, which is annoying if you want to capture the data into an Arduino.

You might want to spend some time looking on rcgroups and in various hobby drone sites - the latter folks have a similar problem, as they want to collect all the control channels and mediate them through a custom flight computer (which in the early days was sometimes Arduino-compatible).

You can also make your own transmitter - perhaps by retrofitting an NRF24L01+ module and miniature Arduino equivalent into the casing of an older 5/72/75 MHz set - or the IR transmitter from a toy helicopter.


lcd.clear doesn't work with Serial.begin(9600) on Arduino Mega 2560 So I have a standard 16x2 LCD display with 16 pins. The LCD display works fine with every other aspect, however, the "lcd.clear" function doesn't work with "Serial.begin(ANY BAUD)". I have tried changing bauds and downgrading the board software but it still doesn't work.

Basically, instead of clearing the display like it should do, it displays a weird character with 4 horizontal lines (in one character space) and then continues to write stuff after it.

Here is my code:

#include <LiquidCrystal.h>
LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

void setup() {
 pinMode(8, INPUT);
 lcd.begin(16,2);
 Serial.begin(9600);
}

void loop() {
 lcd.print("incorrect");
 delay(3000);
 lcd.clear();
 delay(100);
}

Whenever I delete the Serial.begin everything works fine, but when I add it the clear function doesn't work anymore.

So in this case, what happens is that the Arduino prints "incorrect", then instead of clearing the display, it prints out four horizontal lines, and then continues to print out "incorrect" infinitely.

Pins 0 and 1 are the hardware serial pins on the Mega.  If you're going to use Serial, then you can't connect your LCD to those pins or it won't work.  Even if you are only connected to Serial through the USB, pins 0 and 1 are still acting as Tx and Rx.


Safely enabling voltage divider on a 12V battery I'm planning to monitor voltage of a 12V battery with an Arduino's ADC pin connected via a voltage divider. Since I don't want the circuit itself to drain the battery when not in use, I want to use a transistor to "enable" it via an Arduino DIO pin like:

Is this a safe circuit to use?

If I set EN low to disable the divider, will that risk putting 12V directly on the ADC pin and burn it out? I've found alternative designs, but they seem overly complicated.

Edit: The battery is a Lipo which is also powering the Arduino through a step-down DC converter.

I use a similar system on a product I recently worked on to monitor the battery voltage - and of course I didn't want it on all the time to drain the battery.

The trick, though, is to do the exact opposite of what you are doing.  Instead of isolating the ground (which leaves the battery then directly connected to the Arduino) you need to completely isolate the battery from the divider.

This can be accomplished by using a P-channel MOSFET which you can then drive with an N-channel MOSFET:

The theory is, when the Arduino DOUT is either LOW or not connected (pulled low by 10K resistor) the N channel MOSFET is turned off.  That means the gate of the P channel MOSFET is being pulled up to the battery voltage by the other 10K resistor, so the P channel MOSFET is off, which isolates the whole divider from the battery.

When DOUT goes HIGH it turns on the N channel MOSFET which then pulls the gate of the P channel MOSFET down to ground which then turns it on, thus connecting the divider to the battery.

When the P channel is OFF the only circuit connected to the ADC is the connection between the ADC input and ground through a 10K resistor, so everything is happy and safe.

You should not use resistors greater than around 10K in size on the input to the ADC because the ADC itself has a resistance (the impedance) which is placed in parallel to the lower resistor of the divider.  If the divider's resistors are too large that impedance will affect the accuracy of your readings because the total resistance of the lower resistor will be skewed slightly.  Yes, it's possible to compensate in software, but as long as you keep to a limit of 10K or so for the resistors you won't need to worry about doing such things.

Note that it is important to use a P-channel MOSFET for this, not a PNP transistor.  A P-channel MOSFET, when on, looks like a very small resistor.  A PNP transistor is seen as a fixed voltage drop skewing your results.  The N-channel MOSFET can be replaced by an NPN transistor if you wish, it makes no real difference. I nearly always use MOSFETS these days instead of BJTs though as a matter of course.

As an aside, the only other way of achieving this whilst maintaining the isolation of the ADC from the battery would be to replace the P channel MOSFET with a small relay (say a reed relay), but then you still have to build a relay driving circuit which is just about as complex as this one.


AttachInterrupt - fail to initiate inside a class I'm trying to create a class that uses attachInterrupt, but get this error msg:

 In member function 'void ledDoor::attach()':
ClosetLedStrip:31:82: error: invalid use of non-static member function
         attachInterrupt(digitalPinToInterrupt(_sensorPin), detection_door, CHANGE);
                                                                                ^
exit status 1
invalid use of non-static member function

I found few answers regarding static member, but it was not clear for my needs.

Appreciate help,

#define USE_SLEEP true

#if USE_SLEEP
#include <avr/sleep.h>
#endif

#define sensorPin_1 2
#define sensorPin_2 3
#define RelayON HIGH
#define doorOpen HIGH

#define pwrdown_timeOut 10*(1000*60) // mins to powerdown

// volatile boolean detectDoor_1_Open = false;
//volatile boolean detectDoor_2_Open = false;
const int relayPin1 = 4;
const int relayPin2 = 5;

class ledDoor {

private:
int _sensorPin;
int _interruptPin;
int _relPin;

void  attach(){
        attachInterrupt(digitalPinToInterrupt(_sensorPin), detection_door, CHANGE);
}

void detection_door(){
    #if USE_SLEEP
        sleep_disable();
    #endif

        detachInterrupt(digitalPinToInterrupt(_sensorPin));
        if (digitalRead(_sensorPin) == doorOpen) {
                _doorOpen = true;
        }
        else {// trun off
                _doorOpen = false;
        }
        attach();
}

public:
bool volatile _doorOpen;
ledDoor(int sensorPin, int relPin){
        _sensorPin=sensorPin;
        _relPin=relPin;

        pinMode(_relPin, OUTPUT);
        pinMode(_sensorPin, INPUT); // sensor io
        attach();
}
void go2sleep() {
  #if USE_SLEEP
        sleep_enable();
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);
        sleep_cpu();
  #endif

}
void switchLeds(){
        if (_doorOpen == true) {
                digitalWrite(_relPin, RelayON);
        }
        else{
                digitalWrite(_relPin, !RelayON);
        }
}

};

ledDoor door1(sensorPin_1, relayPin1);
ledDoor door2(sensorPin_2, relayPin2);

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

void loop() {
        door1.switchLeds();
        door2.switchLeds();

  #if USE_SLEEP
        door1.go2sleep();
        door2.go2sleep();
  #endif
}

Firstly, if detection_door is a non-static member function, then C++ simply has no such expression syntax as just detection_door. Such functions have to either be called (with () operator) or be taken address of (with & operator). You can't just say detection_door. That's meaningless, which is what the compiler is telling you.

Secondly, as you already realized, regardless of the syntax a non-static class member function cannot be used as an interrupt handler. You need a freestanding ("ordinary") function as a handler or a static class member. Non-static class methods are beasts of completely different and incompatible nature.

I see that you have multiple ledDoor objects that you want to attach to interrupts independently.

At the level of attachInterrupt and void (void) handlers you will not be able to use a single interrupt handler function and then properly dispatch the handling to multiple individual objects. The high-level attachInterrupt mechanism is insufficient to work around this limitation in a proper way. (At ISR level you can do that, the same way Servo.h handles multiple servos, but it is more complicated.)

For this reason, in your case, as long as you want to stay at attachInterrupt level, it is better to just implement two separate interrupt handlers as external functions that will call your class methods for your existing global objects

ledDoor door1(sensorPin_1, relayPin1);
ledDoor door2(sensorPin_2, relayPin2);

void handler_door1()
{
  door1.detection_door();
}

void handler_door2()
{
  door2.detection_door();
}

and then just attach these handlers to your desired pins in a regular way.

static in this case can only change things in a purely cosmetic way.

On the second thought one can wrap the above into a quasi-elegant implementation that might look as follows

constexpr unsigned N_PINS = 16; // Range of attachable pin numbers

class ledDoor
{
  // ...

  static ledDoor *self[N_PINS];
  static void (*const HANDLERS[N_PINS])();

  template <unsigned PIN> static void handler()
  { // This is the actual interrupt handler that will dispatch the call to
    // the `detection_door` method of the proper class object
    self[PIN]->detection_door();
  }

  // ...

  void attach()
  {
    self[_sensorPin] = this;
    attachInterrupt(digitalPinToInterrupt(_sensorPin), HANDLERS[_sensorPin], CHANGE);
  }

  void detection_door()
  {
    // Your code
  }
};

And somewhere in one of the .cpp files

// Definitions and initializers for static members

ledDoor *ledDoor::self[N_PINS] = {};

void (*const ledDoor::HANDLERS[N_PINS])() =
{
  ledDoor::handler<0>,
  ledDoor::handler<1>,
  // ...and so on...
  ledDoor::handler<15>
};

This uses a dedicated callback for each pin. Maybe a better idea would be to use interrupt number (i.e. the result of digitalPinToInterrupt) for indexing instead of pin number.

The same thing can be rewritten through lambdas instead of a template. I.e. one can get rid of ledDoor::handler<> template and instead initialize the HANDLERS array as

void (*const ledDoor::HANDLERS[N_PINS])() =
{
  [](){ ledDoor::self[0]->detection_door(); },
  [](){ ledDoor::self[1]->detection_door(); },
  // ...and so on...
  [](){ ledDoor::self[15]->detection_door(); }
};

Note that this approach is a bit more memory wasteful that it could have been, since it uses a number of static tables of pre-determined size. In essense this is a slightly different implementation of the same "gluing" approach as described here.


Arduino micro program not uploading I am having trouble uploading a new program to my arduino micro. I first flashed the blink example program to the board and that worked. However now whenever I try to flash a new program it either cannot fine the port of it just gives me a general error. I have selected the right model and port in the tools menu as well as press the reset button right before the upload stage. This arduino micro has an external power supply. Here is the error code:

Sketch uses 4,244 bytes (14%) of program storage space. Maximum is 28,672 bytes.
Global variables use 154 bytes (6%) of dynamic memory, leaving 2,406 bytes for local variables. Maximum is 2,560 bytes.
PORTS {COM1, COM4, } / {COM1, COM4, } => {}
PORTS {COM1, COM4, } / {COM1, COM4, } => {}
PORTS {COM1, COM4, } / {COM1, COM4, } => {}
PORTS {COM1, COM4, } / {COM1, COM4, COM9, } => {COM9, }
Found upload port: COM9
C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -PCOM9 -b57600 -D -Uflash:w:C:\Users\Joel\AppData\Local\Temp\build4becb324f24d9ea6a5bead572d36ff0a.tmp/d4onOF.ino.hex:i
An error occurred while uploading the sketch.

Com 1 and 4 are default to this computer

Thanks in advance for your help.

This problem was fixed by restarting the arduino IDE by the exe instead of opining it from an .ino file.


Storing data on AT24C02 EEPROM chips with Arduino I have recently come across some  8-pin 128-byte EEPROM chips. I've seen those USB EEPROM chip programmer units, but I was wondering if there is any way I could manually store data on the chip with my Arduino.

I don't have any application for the chips yet, but I would just like to see if I can read / write data on the chips.

Here's the data sheet for the chips.

You wire your chips on a breadboard, with the +/- left rail for Vcc/GND, and the right +/- rail for SCL/SDA, plus a little acrobatics to connect everything.

Your chips can have 8 addresses, 0x50 to 0x57, set up with the A0/1/2 pins: all low = 0x00, all high = 0x07. The you read and write to the EEPROM of your choice with:

char i2c_eeprom_read_char(int deviceaddress, unsigned int eeaddress) {
  char rdata = 0xFF;
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8)); // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Wire.endTransmission();
  Wire.requestFrom(deviceaddress,1);
  if (Wire.available()) rdata = Wire.read();
  return rdata;
}

void i2c_eeprom_write_char(int deviceaddress, unsigned int eeaddress, char data) {
  int rdata = data;
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8)); // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Wire.write(rdata);
  Wire.endTransmission();
}

If you have more than 8 chips (well throw them away and get larger ones, but anyway, for completeness sake): wire all of them with A1/A2 to GND, and each A0 to a different digital pin. When you need to access a chip, set all A0s to LOW, except the one you want to HIGH, and use 0x51 as the address. By doing this you're setting all chips except the one you want to address 0x50 (which doesn't matter) leaving only one at 0x51. That enables you to have as many chips as you have free digital pins...


How can I simulate an accelerometer? I am new to Arduino. I want to simulate a circuit which uses an accelerometer ADXL335 and a DC motor. If any deviation observed in the accelerometer readings, I want the motor to rotate. Is there any way I can simulate its working in software without implementing it?

Your sensor supplies an analog signal, ranging from 0V for -3g to 3.3V for +3g.
This means you have a signal averaging at "338" when read using Arduino's analogRead() function, with spikes in either direction when acceleration changes.

You would want some code which gives you a variable hovering around "338", with random acceleration spikes injected in either direction. This could look something like this:

int16_t num_zerog = (3.3 / 5) * 512;
int16_t num_xaxis = num_zerog;
uint8_t num_random = 0;

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

void loop() {
  // put your main code here, to run repeatedly:
  num_random = random(256);
  if (num_random == 255) {
    num_xaxis += 200;
  }
  else if (num_random == 0) {
    num_xaxis -= 200;
  }
  else if (num_random < 100) {
    num_xaxis += 1;
  }
  else if (num_random > 155) {
    num_xaxis += 1;
  }
  else {
    num_xaxis += (num_zerog - num_xaxis) / 4;
  }
  if(num_xaxis < 0 || num_xaxis > 675) {
    num_xaxis = num_zerog;
  }
  Serial.println(num_xaxis);
  delay(10);
}

Explanation: First, the value for 0g is determined from the voltage difference.
A random value is generated, ranging from 0 to 255.
If the random value is 0, a negative value is added to your "signal". If it's 255, a positive spike is added.
If any other value is obtained, it goes back to it's 0g level with 1/4th of the difference between the current value and the 0g value per loop.

The serial commands only serve to let you watch the result in Arduino IDE's serial plotter.
If you need the spike to occur less frequently, adjust the delay(), or let the counter run to higher numbers.
If the CPU-blocking delay() command is an issue in your project, you could run the randomization code using a timer and an interrupt.

Please note that real acceleration sensors exhibit a lot more noise than this. This could be implemented by adding smaller spikes at a broader range of random values (like -1 if num_random is below 100 and +1 if it is above 155).


Serial Monitor shows a continuous "word salad" without a loop I have written a little program which should (at the end) host a little website. This is just my setup. But for some reason, it writes "srl?" endlessly onto the serial monitor. I just connected the ESP8266-01 to my Arduino UNO, using 115200 baud with the nodeMCU board. Using different boards results in an error telling me I should use nodeMCU.
As I have written in the title, I do not understand how it can produce an endless output without a loop with Serial.print/write in it.
#include <ESP8266WiFi.h>

const char* NAME = "x"; //ssid
const char* PWRT = "x"; //password

WiFiServer server(80);

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

  Serial.printf("connect with %s \n", NAME);
  WiFi.begin(NAME, PWRT);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
  }

  server.begin();
  Serial.printf("webserver open, access with %s\n", WiFi.localIP().toString().c_str());

}

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

}

The ESP8266WiFi.h is for running on an ESP8266 host, but your are trying to use it on an Arduino Uno. This caused the crash of your sketch on Arduino Uno.
Based on the connection diagram you provided, you are using the ESP-01 as an wifi-shield and the ESP-01 by default is having an AT commands firmware. In order to use the ESP-01 as a wifi shield, you need an library like WiFiEspAT.


Chinese CH340 Arduino Uno - Burning stand allone chip I followed regular tutorial and I was able to burn boot-loader on my standalone ATM328 chip, but because I'm using this CH340 UNO and example is with regular UNO, I can't just remove the chip from there (CH340 UNO) and upload the code directly to my new standalone chip trough that board.

So what I tried was to use my FTDI cable, so I hooked up GND, RX, TX and VCC for my breadboard from there, but when I tried to upload a sketch I keep getting that message that programmer is not responding.

So I was wondering, is there a way to use this Chinese board to upload sketch to my new chip without de-soldering the chip from that board as option one.

As option two what I'm doing wrong with FTDI cable and why I'm not able to upload sketch directly like that? I saw some comments related to some auto-reset that needs to be implemented but I'm not following that part, not sure what I need to hookup extra for that...

UPDATE

Here's how my board look like:

Update 2:

OK, everything works great now! I just needed one pull-up resistor for reset pin.

Thanks everyone!

You said:

It just need a pull-up resistor for the reset pin!


How can I use wifi to wirelessly communicate (and wirelessly code if possible) between multiple arduinos? I am using arduino as the base for an accelerometer project - the end goal is to have multiple arduinos with accelerometer chips that can wirelessly start and stop collecting data and wirelessly send this data back to the "base" arduino (which will be connected to a computer).  Currently we have only two arduinos communicating to test a lot of this, and currently are using a bluetooth node to wirelessly code the accelerometer arduino and Rf nodes to wirelessly send the data back to the arduino connected to a computer which then prints the data it is collecting.  How could we replace this with a wifi network?

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

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

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


UART error can not compile on Arduino Yun (ATmega32u4) This code is used for communication between the Glediator interface and a NeoPixel Matrix, but I receive an error saying 'UCSR0A' is not defined within the scope.

UCSR0A |= (1<<U2X0);
UCSR0B |= (1<<RXEN0)  | (1<<TXEN0) | (1<<RXCIE0);
UCSR0C |= (1<<UCSZ01) | (1<<UCSZ00)             ;
UBRR0H = 0;
UBRR0L = 1; //Baud Rate 1 MBit (at F_CPU = 16MHz)

Any feedback is appreciated.

Those register names are for a different chip (maybe the ATMega328P of the Uno).

Instead you need to use the right register names.  Start by reading the datasheet for the ATMega32U4.  You might find that the register names are UCSR1A etc, or UCSRA or something like that instead of UCSR0A.


Since you are being returned JSON, you can use the jsoncpp library found here
To split your return to an array. Then you simply retrieve whatever item you want using array index notation.

Here is another helpful post on creating arrays of strings in C++ from JSON.
C++ and JSON


Activating a defined macro in a class from main.cpp Sorry if this question been asked. I'm trying to activate certain function in a class using a macro defined in the class from main.cpp. I'm using jrowberg MPU6050 library if that matters.

main.cpp

#include "gyro.h"
gyro gyro(Serial);
#define OUTPUT_READABLE_EULER

void setup(){
...
}
void loop(){
...
}

gyro.cpp

  #include "gyro.h"
  #ifdef OUTPUT_READABLE_EULER
      // display Euler angles in degrees
      mpu.dmpGetQuaternion(&q, fifoBuffer);
      mpu.dmpGetEuler(euler, &q);
      serial_.print("euler\t");
      serial_.print(euler[0] * 180/M_PI);
      serial_.print("\t");
      serial_.print(euler[1] * 180/M_PI);
      serial_.print("\t");
      serial_.println(euler[2] * 180/M_PI);
  #endif

If I define OUTPUT_READABLE_EULER in gyro.h, it works. But I want to do it from main.cpp.

You cannot not, but also you should not try to define a macro in a cpp file and use it in another cpp file.

Instead, you have to define it in a h (header) file, which is included in both cpp files.

Why would you define it in main.cpp or main.h anyway if you don't use it in those files?

You have mainly three options:

Define it in gyro.h so you include it in gyro.cpp where you use it. You can later use it in other files as well.
Define it in gyro.cpp so you can use it only in that file. This prevents the macro being used in other files (which can be safer).
Define it in a separate file, e.g. euler.h and include this header file everywhere you need it.

See also Juraj's comments below.


Can anyone suggest me a software timer library that does not use polling but timer ISR instead? There are many software timer libraries available in Arduino.
A library called SimpleTimer http://playground.arduino.cc/Code/SimpleTimer is really good with many functions, but it uses polling.
If anyone is familiar with a really good library that uses Timer ISR of Atmega instead of polling, please suggest me as i am using ultrasonic sensors and i can't afford polling.

Yeah, I have the same problem.
The only solution I found is to rewrite  a lot of the code. Still ongoing, though.

For you, Timer1 is probably the best candidate, unless you have already some use for it, like in my case.

A quick hack is to free Timer0: it is currently (ab)used by the wire library, which provides the typical arduino timing.
But you can remove/rename the file wiring.cpp to something that will not be identified as source (ex: wiring._cpp) and comment out the init() function call from the main() function in the main.c file.

Normal Arduino stile time functions will not work, of course.

Unfortunatelly Arduino SW really lacks the structured design that would allow it to be useful in more complex cases and most of the libraries make exclusive use of resources that could be shared, timer being the most prominent example.

Port ISRs is another.

Btw, if you happen to use a SW serial library, it's already game over, as it busy loops inbetween bits, in interrupt context (!), rather than using a timer.


void loop() stops running after an hour or so So I have a program that measures temperature and humidity over time. Here isthe code I use:

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

#define DHTPIN 2
#define DHTTYPE 22
const int chipSelect = 10;

DHT dht(DHTPIN, DHTTYPE);
RTC_DS3231 rtc;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("DHT22 sensor reading");

  if(! rtc.begin()) {
    Serial.println("Could not find RTC");
    while(1);
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
}

void loop() {

  //temperature measurements
  float hum = dht.readHumidity();
  float temp = dht.readTemperature();

  if( isnan(temp) || isnan(hum )) {
    Serial.println("Failed to read from DHT22 sensor!");
    return;
  }

  Serial.print("Humidity: ");
  Serial.print(hum);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(temp);
  Serial.println(" *C");

  //determining the date
  DateTime now = rtc.now();

  int dayy;
  int monthh;
  int yearr;

  int hours;
  int minutes;
  int seconds;

  String date;
  dayy = now.day();
  monthh = now.month();
  yearr = now.year();
  date = String(dayy) + String(monthh) + String(yearr);

  int seconds_passed; // how many seconds have passed since the start of the day: used for the data plot
  hours = now.hour();
  minutes = now.minute();
  seconds = now.second();
  seconds_passed = ((hours * 60) + minutes)* 60 + seconds;

  //writing to SD card

  if(SD.begin(chipSelect)) {
    Serial.println("Card is initialized! Ready to go!");
  }
  else {
    Serial.println("Error with initializing the card!");
    return;
  }
  Serial.println("Opening file...");
  String FileName;
  FileName = date + ".dat";

  File dataFile = SD.open(FileName, FILE_WRITE);

  if (dataFile) {
    dataFile.print(temp);
    dataFile.print(",");
    dataFile.print(hum);
    dataFile.print(",");
    dataFile.println(seconds_passed);
    dataFile.close();

    Serial.println("Written data to file and closed it");
    Serial.println(" ");
    Serial.print("Seconds passed: ");
    Serial.println(seconds_passed);
    Serial.println(" ");
  }
  else {
    Serial.println("Error with opening the file, trying again");
  }

 delay(1000);
}

It works like a charm, but for the fact that it stops running after an hour, maybe 1,5 hours.

Resetting the board seems to work, but I can't obviously sit there the whole time and reset the board. I use an Arduino Due. Did I program something wrong that something overflows or should I add some more code?

A year ago I had the same problem, it seems there is a bug with the String library. I recomed you this:
1- Easy: use the String library on development, but for the "release" change everything to use C native strings (char name [SIZE])
2- Complex (and worse in my op.): set an interrupt every half an hour (or whenever with margin before it crashes) that activates an output connected to the reset pin of the Arduino. I've seen this on the internet but couldn't make it work.
Link to Arduino Forum's thread


GPS Module Outputting Question Marks in Serial Window I've got a uBlox Neo 7N GPS Module and configured it so if theres is no incoming data print no location but if there is print the latitude and longitude. However it's printing ?,?.

So I'm assuming it's wired correctly as I'm getting an output however maybe my code is preventing it from printing the two long numbers hence converting it to a ? instead.

  char buf[128];
  if (gps.location.isValid()) {
    snprintf(buf, sizeof(buf), "%lf,%lf", gps.location.lat(), gps.location.lng());
    Serial.println(buf);
  }

EDIT I know that Im getting a read as I set two variables of type double lat and long to equal gps.location.lat() and gps.location.lng() respectively and I'm getting a number. How do I fix up this snprintf line so it prints properly?

No floating point for sprintf, it prints a '?'.

The functions sprintf, sscanf and the alike functions (snprintf and others) do not have floating point support for avr microcontrollers.

History

One of the first Arduino boards used the Atmega8 microcontroller with only 8k flash and 1k sram. It was important to be very memory efficient.
The gcc compiler did not automatically include the floating point support libraries for the sprintf functions, however it was easy to include them. Arduino decided not to include those extra libraries because they use extra memory.

Arduino has a preprocessor, compiler and linker that tries to only use code that is actually used. The sprintf does not know at compile time if floating point will be used, so it would have to include those extra floating point support libraries whether they were used or not.

Now it is 2018 and it is sadly still not included.

Workaround

The Serial.println functions can print floating point variables. They can however not print the output in scientific notation. It rounds the value that is printed to the nearest number.
The dtostrf() and dtostre() convert a float variable to text. The dtostre() is for scientific notation.
A variable of the float type can be cast to a integer.
The Arduino String object can handle a float.

Only float for avr microcontrollers, no double.

The avr microcontrollers are 8-bit microcontrollers. There is no floating point library for 64-bit double variables, only a library for 32-bit float variables.
That library is according to the IEEE standard and is extremely fast and optimized.


Faster and lighter approximate timing code without using timer I want to use loop() iterations counter to execute some tasks periodically or tasks like debouncing. My other sketch is running every loop() at least 20 ms, and if i am using 5 ms time to wait to
debounce a button, it will still be at least 20 ms waiting, also cpu will have to compare two not zero values, which is a bit slower.
I think it is more difficult for cpu than just incrementing and decrementing one variable and comparing it to 0. So i came up with pattern like that:

boolean onOff=1; // arduino led state. My task here is LED blinking.
byte loopCounter=2; // number of iterations made by loop(). Set as little variable as possible to save ram and cpu time.
//Code will be executed every "loopCounter" iteration of loop().
void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
      if (--loopCounter == 0) { //comparing with 0 should be a bit faster and easier for Arduino to process. Correct me if i am wrong.
        loopCounter=2; // That digit sets how often your code will be executed. Every 2(3,4... set your own value) iterations of loop().
        digitalWrite(13, onOff= !onOff); // the task itself.
        }
}

It may be more convenient in some ways than millis() and micros() patterns. Also i do want want to use hardware timers for timing.
It may be convenient in cases, when you don't care when exactly task will be done, you just want it to be done ASAP (as soon as possible), but
not during that particular iteration of loop(). Basicly you can use it as a timer if you know how it takes one iteration to be done.
So, if your sketch runs 1 iteration of loop() for 1 ms, and you need some action to be done every 1 sec, 1ms*1000 == 1 sec. So you
need it to be done every 1000 iterations.

So, is that really can save some ram and cpu time?
Is comparing with zero is faster for arduino than comparing with not
zero?
Are millis() and micros() timing patterns using more operations
(setting value to variable, computing the difference between 2
values and than comparing it to a period you have set) instead of
decrementing and comparing to zero with my pattern?
Any side-effects of using my pattern? I can only think of very
unaccurate timing and delays more than you think if your sketch done
smth more than usual, because of button push for example or some
sensor changed value.

Thank you!

Personally I wouldn't be putting too much effort into optimizing away your timers. millis() is pretty fast - the work needed to calculate the result is done in the background anyway (by interrupts). I tried some test code:

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

  unsigned long start, finish;

  start = micros ();
  for (byte i = 0; i < 100; i++)
    digitalWrite (13, HIGH);
  finish = micros ();

  Serial.print ("Time taken to do digitalWrites: ");
  Serial.println (finish - start);
  Serial.flush ();

  start = micros ();
  volatile unsigned long now;
  for (byte i = 0; i < 100; i++)
    now = millis ();
  finish = micros ();

  Serial.print ("Time taken to do millis: ");
  Serial.println (finish - start);
  Serial.flush ();

  }  // end of setup

void loop ()
  {

  }  // end of loop

Results:

Time taken to do digitalWrites: 520
Time taken to do millis: 188

You can see that the digitalWrite() (which you weren't worried about) takes 5.2 µs, whereas calling millis() (which you were worried about) takes 1.88 µs.

  Are millis() and micros() timing patterns using more operations (setting value to variable, computing the difference between 2 values and than comparing it to a period you have set) instead of decrementing and comparing to zero with my pattern?

Yes, just adding one to a variable and then comparing will be faster. Whether it is worth the effort is debatable.


What is a cheap way to interface a USB keyboard to an Arduino Uno? What is the cheapest way to interface a USB 2.0 keyboard to an Arduino Uno?

The keyboard does not support PS/2 emulation (interfacing a PS/2 keyboard to Arduino is easy). So this means the Arduino will read the USB keyboard's keystrokes - whatever their speed of input is.

If it can be solved using an IC then DIP is preferred as it quicker to work  with for soldering and pluggin into breadboard.

The cheapest way is to get a plain PS/2 (or PS/2-USB convertible) keyboard instead of USB1.1 (I hope you mean the standard LS keyboard, since USB2.0 HS keyboards hardly exist), and interface it to GPIOs in accord with known solutions.

The Arduino Uno is designed around Atmega8u2 and ATmega328P chips, which can act as USB device only, FS and LS. To interface it with a dedicated USB keyboard (which is a USB device), the you need to have the Arduino as a USB host. Probably it is possible to emulate some limited hardware host functionality for LS mode (1.5Mbps) over GPIOs, but it will be a remarkable effort.


Program jumps alone from void loop() to another void //simple alarm system
int RipSensor1 = 12;
int RmkeyA = 3;
int RmkeyB = 5;
int RmkeyC = 6;
//--------------------------------------------------------------------------

void setup()
 {
  Serial.begin(9600);
  pinMode(RipSensor1,INPUT);
  pinMode(RmkeyA,INPUT);
  pinMode(RmkeyB,INPUT);
  pinMode(RmkeyC,INPUT);
  pinMode(13,OUTPUT);
  Serial.println(F("System Is Up & Running")); }
  //----------------------------------------------------------------------

void loop()
 {
  Serial.println(F("Main Loop Start"));
  digitalWrite(13,LOW);   //for debugging
  if (digitalRead(RmkeyA) == HIGH)
   {
    Rip1Status();
   }
 }
//----------------------------------------------------------------------

void AlarmSMS1()
 {
  //send sms to admin1
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Serial.println(F("SMS Sending to 1st ADMIN --->"));
  Rip1Status();   // return to this void (monitoring)
 }
//----------------------------------------------------------------------

void Rip1Status()
 {
  Serial.println(F("VOID Rip1 Start..."));
  while (digitalRead(RmkeyB) == LOW) //Arm mode
   {
    digitalWrite(13,HIGH);
    if (digitalRead(RipSensor1) == HIGH) //when Rip sensor sense motion
     {
      Serial.println(F("Movement ALARM --> PowerUP Relay 1 & 2"));
      long RipTimer1 = 0;
      long Rip01 = 0;
      int z = 0;
      int x = 0;
      while (digitalRead(RmkeyC) == LOW)
       {
        RipTimer1++;
        Serial.println(RipTimer1);   //for debugging
        if((z==0) && (RipTimer1 - Rip01 > 500))   //1st CheckPoint do something
         {
          z = 1;
          Serial.println(F("1st CheckPoint OK"));
         }
        else if((x==0) && (RipTimer1 - Rip01 > 3000))   //2nd CheckPoint go on other void
         {
          x = 1;
          AlarmSMS1();
         }
       }
      Serial.println(F("C Key Pressed --> False Alarm"));    //if button C pressed
      RipTimer1 = 0;
      z = 0;
      x = 0;
      Serial.println(F("Monitoring Loop ends --> GoTo Main Loop"));
      break;
     }
    else Serial.println(F("Monitoring"));  //for debugging
   }
  Serial.println(F("B Key Pressed --> Disarming"));  //for debugging
  Serial.println(F("Monitoring Loop ends --> GoTo Main Loop"));
  loop();
 }

I make this code & i have this problem:
Program start & wait for A key pressed to Arm mode. works ok
Press A key go to Arm mode (monitoring). works ok
When its on "monitoring", if i press B key, system disarming then go to void loop() and wait. works ok
When its on "monitoring" & Rip sensor sense movement, then alarm start and if i press C key then disarming as false alarm and go to void loop() and wait. works ok
When its on "monitoring" & Rip sensor sense movement, if i left alarm to complete, go to sms void send sms to admin and return to Rip void (monitoring).
But on this point if i press B button to disarm system this happen...

Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
Monitoring
B Key Pressed --> Disarming
Monitoring Loop ends --> GoTo Main Loop
Main Loop Start
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012.............

Why this happen?
What i am doing wrong?

loop() calls Rip1Status(), which calls loop(), which calls Rip1Status(), which calls loop(), which calls ....

That process will continue until the stack overflows (runs out of memory) or over-writes some necessary variable. If you just meant for Rip1Status() to return to the main loop, delete the loop() call at the end of the function. When Rip1Status()exits, control will automatically return toloop()at the statement following theRip1Status()` call.


How is a 41KB char array filling up 256KB of program memory? I have an array of 41,400 elements of type char, which I am trying to put in program memory on a Mega2560. It should have 256KB of flash memory, but when I try to compile my sketch, it says the size of the array is too large. Each char is one byte, so this array should be 41,400 bytes. I'm at a loss as to how this can be too big.

I have also tried using an array of byte variables (should be the same thing) with no success. This is the only variable going into program memory.

Here is the relevant line:

const char Array[] PROGMEM = {0,19,21,25,27,27,27,29,24, ... };

I have included avr/pgmspace.h

Thanks in advance for any help.

The limitation here is the data type of the index of the array. That is int, and on an 8-bit system an int can hold a value in the range -32768 to 32767.

That means the biggest index number an array can have is 32767.

That limit cannot be changed. You're stuck with it.

However, there are some tricks you can use to expand it.  One is to use a larger data type than char and pack your data into it.  For instance, using unsigned int as your data type will give you a maximum of 32767 16-bit values. Each one can hold two bytes. That gives you a total capacity of 65534 bytes.

Using unsigned long (32 bits) would double that again.

It is then up to you to work out how to get to the individual bytes. Using the pgm_read_byte_*() function you may not see any difference. After all the start address is just an address regardless of type. Of course, you have to watch out for any differences in endianness when you have packed your initial data into the array...


Ping IP address using ESP8266 connected to Arduino I want to make a system using NeoPixels, an Arduino and an ESP8266 module to ping IP addresses on my network to determine if certain people are on our Wi-Fi (I'll be pinging mobile phones).

I'm finding it hard to find any help as to how to ping IP addresses from an Arduino using the ESP8266 module. I did find the ICMP Ping library, but it uses the Ethernet shield, and I'm quite new to Arduino so I don't even know if I could modify the library in any way.

If anyone could help me on my way, that'd be great!

From what I could find, it seems theres a command for pinging a server. It returns the number of milliseconds taken for the server to respond. The command is: AT+PING="web site" or AT+PING=<ip addr>, from 2 separate sources. You'll have to test them to see which (if not both) is correct.


DS3231 + button to trigger light please can someone help me with code, i want to have automatic trigger on specific hour, also i want to have button switch if needed, in my code i can press the button to trigger light relay, but my specific time trigger just flash at start time and does nothing, here is code:

#include <LiquidCrystal_I2C.h>
#include <DS3231.h>
LiquidCrystal_I2C lcd(0x27, 2, 1,0,4,5,6,7,3, POSITIVE);
DS3231  rtc(SDA, SCL);
Time t;

const int OnSec = 30;
const int OffSec = 5;
int relay_3 = 5 ;

void setup() {
 lcd.begin(20,4);
 rtc.begin();

 pinMode(relay_3,OUTPUT);
 pinMode(8, INPUT_PULLUP);
}

void loop() {
  int button_4 = digitalRead(8);
  t = rtc.getTime();
  lcd.setCursor(0,1);
  lcd.print(rtc.getTimeStr());

  if(t.sec == OnSec)                                  //if is hh.mm.30 - just for 1 sec trigger relay
  {
  digitalWrite(5,HIGH);
  }
    else if(t.sec == OffSec)                         //if is hh.mm.05 - release relay
  {
  digitalWrite(5,LOW);
  }
      else if (button_4 == HIGH)                     //if button is pressed - trigger relay
  {
  digitalWrite(5,HIGH);
  }
        else
  {
  digitalWrite(5,LOW);
  }

  lcd.clear();
}

i would be gratefull for any advice :)

The else case is executed every time the other if and else if conditions are not true. That means if it is not 5 sec and not 30 sec and no button is pressed, the relay is switched off.

To achieve what you want is not that easy, because you have to synchronize button press and button release with the timer actions. First you must specify what you exactly want to do. e.g What happens if you have already pressed the button and release it in the time interval between 30 and 5. Releasing the button would switch off the light but should it stay on because you are within the on-time? This is just an example of what to think about.

I wrote a little code for fun doing the things as I would do it:

#include <LiquidCrystal_I2C.h>
#include <DS3231.h>
LiquidCrystal_I2C lcd(0x27, 2, 1,0,4,5,6,7,3, POSITIVE);
DS3231  rtc( SDA, SCL );
Time t;

const int OnSec = 30;
const int OffSec = 5;
int relay_3 = 5;

int timerPhase = -1;
int relayState = LOW;

void setup()
{
 lcd.begin( 20, 4 );
 rtc.begin();

 pinMode( relay_3, OUTPUT );
 pinMode( 8, INPUT_PULLUP );
}

void loop()
{
  t = rtc.getTime( );

  int button_4 = digitalRead( 8 );

  lcd.setCursor( 0, 1 );
  lcd.print( rtc.getTimeStr( ) );

  // this only works if the off time is
  // less than the on time. (OffSec < OnSec)
  timerPhase = ( (t.sec > OffSec) && ( t.sec < OnSec ) ) ? 0 : 1;

  if ( button_4 == HIGH )
  {
    // a button overrides the timer phase
    relayState = HIGH;
  }
  else
  {
    if ( timerPhase == 0 )
    {
      relayState = LOW;
    }
    else
    {
      relayState = HIGH;
    }
  }

  digitalWrite( relay_3, relayState );

  lcd.clear();
}

I could not try the code because I don't know which libraries you used and therefor got compiler errors. So there might be syntax errors in my code but I hope I wrote correct code. It would be nice if you report errors here, if you find one/some ;-).

The line

timerPhase = ( (t.sec > OffSec) && ( t.sec < OnSec ) ) ? 0 : 1;

uses a ternary operator. It means if the condition ( (t.sec > OffSec) && ( t.sec < OnSec ) ) is true, take the first alternative 0 and assign it to the variable timerPhase, if it is false choose the second alternative '1'.


I'm using too much RAM. How can this be measured? I would like to know how much RAM I am using in my project, as far as I can tell, there's no way to actually work that out (other than going through and calculating it myself). I have got to a stage in a rather large project where I have determined that I am running out of RAM.

I have determined this because I can add a section and then all hell breaks loose somewhere else in my code for no apparent reason. If I #ifndef something else out, it works again. There is nothing programatically wrong with the new code.

I suspected for a while that I was getting to the end of available RAM. I don't think I'm using too much stack (although it's possible), what is the best way to determine how much RAM I am actually using?

Going through and trying to work it out, I have problems when I get to enums and structs; how much memory do they cost?

first edit: ALSO, I have edited my sketch so much since starting, these are not the actual results I initially got, but they are what I am getting now.

  text     data     bss     dec     hex filename
 17554      844     449   18847    499f HA15_20140317w.cpp.elf
 16316      694     409   17419    440b HA15_20140317w.cpp.elf
 17346      790     426   18562    4882 HA15_20140317w.cpp.elf

The first line (with text 17554) was not working, after much editing, the second line (with text 16316) is working as it should.

edit: the third line has everything working, serial reading, my new functions, etc. I essentially removed some global variables and duplicate code. I mention this because (as suspected) it's not about this code per sae, it has to be about the RAM usage. Which brings me back to the original question, "how to best measure it" I'm still checking out some answers, thanks.

How do I actually interpret the above information?

So far my understanding is:

`TEXT` is program instruction memory
`DATA` is variables (unitialised?) in program memory
`BSS`  is variables occupying RAM

since BSS is considerably less than 1024 bytes, why does the second work, but the first doesn't? If it's DATA+BSS then both occupy more than 1024.

re-edit: I edited the question to include the code, but now I've removed it because it really had nothing to do with the problem (other than maybe poor coding practices, variable declarations and the like). You can review the code by looking back through the edits if you really want to see it. I wanted to get back to the question at hand, which was more based around: How to measure RAM usage.

You can use the functions provided AVRGCC: Monitoring Stack Usage

The function was intended to check the stack usage but what it reports is the actual RAM that has never been used (during execution). It does so by "painting" (filling) the RAM with a known value (0xC5), and then checking the RAM area counting how many bytes have still the same initial value.
The report will show the RAM that has not been used (minimum free RAM) and therefor you can calculate the max RAM that has been used (Total RAM - reported RAM).

There are two functions:

StackPaint is executed automatically during initialization and "paints" the RAM with the value 0xC5 (can be changed if needed).
StackCount can be called at any point to count the RAM that hasn't been used.

Here is an example of usage. Doesn't do much but is intended to show how to use the functions.

// -----------------------------------------------------------------------------
extern uint8_t _end;
extern uint8_t __stack;

void StackPaint(void) __attribute__ ((naked)) __attribute__ ((section (".init1")));

void StackPaint(void)
{
#if 0
    uint8_t *p = &_end;

    while(p <= &__stack)
    {
        *p = 0xc5;
        p++;
    }
#else
    __asm volatile ("    ldi r30,lo8(_end)\n"
                    "    ldi r31,hi8(_end)\n"
                    "    ldi r24,lo8(0xc5)\n" /* STACK_CANARY = 0xc5 */
                    "    ldi r25,hi8(__stack)\n"
                    "    rjmp .cmp\n"
                    ".loop:\n"
                    "    st Z+,r24\n"
                    ".cmp:\n"
                    "    cpi r30,lo8(__stack)\n"
                    "    cpc r31,r25\n"
                    "    brlo .loop\n"
                    "    breq .loop"::);
#endif
}

uint16_t StackCount(void)
{
    const uint8_t *p = &_end;
    uint16_t       c = 0;

    while(*p == 0xc5 && p <= &__stack)
    {
        p++;
        c++;
    }

    return c;
}

// -----------------------------------------------------------------------------

void setup() {

Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
Serial.println(StackCount(), DEC);  // calls StackCount() to report the unused RAM
delay(1000);
}


Significance of the numbers used in the manual i just bought the starter kit and am currently working my way through the examples in the book when i came across some numbers used in the manual that seems a little too specific.

For example, in project #3,the love-o-meter, i had to divide the sensor value by 1024.0, and the explanation for it was never given in the manual.

Furthermore, in project #4(which i'm currently at), the book states that i have to convert sensor readings from 0 - 1023, to a value between 0 to 255.Is the number 1024/1023 simply an arbitrary number/limit set by the sensor's manufacturers? Also, is they any significance or reason that analogueWrite only accepts positive values up to 255?

Thanks!

The range 0 - 1023 comes from the analog-to-digital converters (ADC) built-in to your Arduino. What they do is take a voltage reading (e.g. from your sensor) and compare it to the analog reference voltage (which is typically 5 volts, although it can be changed).

It converts that reading to a binary number. The ADCs on board a typical Arduino have 10 bits of precision. The maximum number you can represent with 10 binary bits is 1023. Therefore, a reading of 0V is converted to the number 0; a reading of 5V is converted to the number 1023; and so on (it handles all the in-between values too).

However, analogWrite() works quite differently. It's not actually producing a varying voltage on the output (i.e. it's not true digital-to-analog conversion). Instead, it's using Pulse Width Modulation (PWM) to do something similar.

That means it sends lots of 5V pulses on the output in quick succession. The 0 - 255 values you give it affect the duty cycle -- that is, how long each pulse is compared to the gaps between pulses. The longer the pulses are, the 'stronger' the signal is. This is very useful for applications such as controlling the brightness of an LED or the speed of a basic DC motor.

The PWM signal is controlled by timers built-in to the microcontroller. I suspect it's the capabilities of those timers which determine the input range for analogWrite().

You can get more information from the online documentation for Arduino:

http://arduino.cc/en/Reference/AnalogRead
http://arduino.cc/en/Reference/AnalogWrite


How to use? ATmega328P Development Board for Arduino UNO R3 Bootloader Project DIY How to use? ATmega328P Development Board for Arduino UNO R3 Bootloader Project DIY.

The purpose of this board is to flash (Arduino) bootloader to Atmega 328 chips. It has not a build in programmer, only a ICSP header to connect the programmer.

So wire it with a programmer and then chip in, ZIF close, burn bootloader, ZIF release, chip out, next chip in, ZIF close, ....

video


How to set float to variable with 7 digits after the decimal point in arduino? Example:

float x = 3154681.124 / 100000; //x = 31.54;

I want x to be:

x = 31.5468112;

float x = 3154681.124 / 100000; //x = 31.54;

x is now 31.5468112 (or close to).
Serial.println(x);

Output: 31.54
Why? Because Serial.println defaults to 2 decimal places for floats.

Syntax
Serial.println(val)
Serial.println(val, format)
Parameters
val: the value to print - any data type
format: specifies the number base (for integral data types) or number of decimal places (for floating point types)

So the solution: specift 7 decimal places when you print:
Serial.println(x, 7);


What's the difference between #define and const int when declaring a pin? Over the course of my Arduino usage and learning, I've noticed that in some sketches people use the #define command to declare pins, while some others simply use const int for the same.

My question is, what's the difference between the two, and which one should be preferred for use?

"#define" is a preprocessor directive. It defines a lable and a value, that will be positioned in the preprocessed-source-code at the same place of each occurence of the label. No type is defined, so it is a basic and dumb substitution of strings before compilation. It can then lead to errors or misunderstandings during compilation.

"const int xxx" defines a type, and locks the value of that instance. It's safer to use this method. The compiler can check for type errors and throw messages (or break compilation) if you made a mistake.

Example:

#define A 5
int dummy_integer = A

... will be preprocessed as...

int dummy_integer = 5

... and the compiler will read this statement.

However, if I remember good, you can always overwrite a preprocessor directive as follows:

#define A 5
int dummy_integer = A
//some code here
#undef A
#define A "my_string"
std::cout << A

That's not good. By using the "const" modifier, instead, you can't change the value (nor the type) of a variable (and so it's defined "constant").


EBay "Development Programmer Board for ATtiny" Has anyone tried these? Does the ATtiny have a bootloader? What software is used to program the chip? Arduino compatible?

Looks a lot more convenient than programming the ATtiny via an Uno.

http://m.ebay.com/itm/201536595756

/Ola

If you don't have experience working with AVRs at a low level then stay away from that. It doesn't provide any connection for a programmer and relies on the Micronucleus bootloader already being in place.

If you really want to experiment with ATtiny development then go with either an Adafruit Trinket or a Digistump Digispark (both of which already have Micronucleus loaded), or get an AVR programmer and (optionally) a ATtiny13/25/45/85 development board that includes a 6- or 10-pin programming header


Arduino Nano 33 IOT issue Nano 33 IOT is not detecting by windows . When i plug the usb cable only green light on the board.
Board is installed from the board manager. the cable is usb DATA cable and not charging cable. I tried the double press on the reset button but nothing happen. The L light is Off and the green light isnt flashing.
I plugged the board into another usb port, the same issue. I tried the board on my friend computer also but no luck. I dont have ATmel ICE or any other debugger like j-link.
https://www.youtube.com/watch?v=C0tXa0uxv5c

I hope someone can explain what is the issue, is it hardware or software.

If you upload to a SAMD board like the MKR boards or the Nano 33 IoT with Nano 33 BLE selected in Tools menu of Arduino IDE, the upload is executed and deletes the bootloader of the SAMD MCU.

The problem is that bossac uploader doesn't check the chip, because it was developed only for the SAMD chips, but Arduino created a bootloader for the Nano 33 BLE nRF52 MCU to use the SAMD bossac uploader.

The SAMD boards use the native USB support of the MCU, so without a bootloader or good sketch running the USB doesn't work.

You have to restore the bootloader on Nano 33 IoT. It is done over the SWD pads on the bottom side of the board. You can use a SWD programmer or other Arduino board with the Adafruit DAP library.

You can use your Nano 33 BLE or some other board and a SD card with Adafruit DAP library as programmer.

I had this problem with MKR Zero and I used a LPC-Link2 programmer to burn the bootloader. Once before I lost the bootloader for other reason and back then I didn't have the programmer so I used the Adafruit DAP library with an Arduino M0.


Unable to load sketch: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x41 I've stumbled upon what I've later found it's quite common error, but there seems not to be simple troubleshooting way and solution (people often try various things, sometimes they succeed, sometimes not).

I am using DAGU mini driver, I was able to load sketch as described here - chose Arduino NG ATMega8 as board, connect to my PC via USB (with the driver listed on the product page).

Later on I've plugged RedBot wheel encoders sensor and write some simplistic program to check whether it works at all. I've summarized the steps in a github issue, so that it's easy to reference it.

When I tried to upload the sketch I've receiced stk500_initialize(): (a) protocol error, expect=0x14, resp=0x42, stk500_getparm(): (a) protocol error, expect=0x14, resp=0x41. The full log is included in comment on that github issue.

The D13 diode is making series of 3-blink bursts - 8 bursts after start. More diagnostic I did in the github issue as well.

My question (apart from obvious 'how to fix it!?!' ;) ) is whether there is some kind of documentation for this protocol? On the various topics I've found people seem to have somewhat different problems (the numbers and messages were different). I just want to know why the first few messages are exchanged OK (avrdude receives some basic info from the chip), but later ones (namely Send: A [41] . [81]   [20]) are producing protocol errors.

AVR programmer helped.

Meaning the bootloader somewhat got corrupted and I had to burn new one.


Extracting a specific sequence of characters from an array I have a character array called storebuffer that contains data from a POST submission and its in the format ssid=abcdef&pswd=ghijk. I wanted to extract everything after ssid= into one array called acqSSID and the portion after &pswd= into another array called acqPaswd. I tried using this but it does not seem to be working. MAX_STORE_BUFFER_LEN is 255. Can anyone help?

int ctr = 0;
for (ctr = 5; ctr < MAX_STORE_BUFFER_LEN; ctr++)
{
  if ( (storebuffer[ctr] == '&') && (storebuffer[ctr+1] == 'p') && (storebuffer[ctr+2] == 's') && (storebuffer[ctr+3] == 'w') && (storebuffer[ctr+4] == 'd') && (storebuffer[ctr+5] == '=') )
  {
    break;
  }
  acqSSID[ctr] = storebuffer[ctr];
}

Serial.print("acqSSID: ");
Serial.println(acqSSID);
Serial.print("ctr: ");
Serial.println(ctr);

You can simply chop it up in place without requiring more than a few extra bytes of RAM using strtok():

char storebuffer[] = "ssid=abcdef&pswd=ghijk";

// Slice it into two parts around the &:
char *lefthalf = strtok(storebuffer, "&");
if (lefthalf != NULL) { // We found a & and split the string OK
    char *righthalf = strtok(NULL, "&");

    // Now you can slice each half around the =
    char *ssidtag = strtok(lefthalf, "=");
    char *ssid = strtok(NULL, "=");
    char *pswdtag = strtok(righthalf, "=");
    char *pswdtag = strtok(NULL, "=");

    Serial.print("SSID: ");
    Serial.println(ssid);
    Serial.print("Password: ");
    Serial.println(pswd);
}

The existing string gets chopped up and the pointers point to different places:

ssid\0abcdef\0pswd\0ghijk
^     ^       ^     ^
1     2       3     4

1: ssidtag
2: ssid
3: pswdtag
4: pswd


Can you make Arduino Uno send information through a WiFi module to a server? A lot of tutorials are about how to control Arduino through WiFi, but I need my Arduino to send information about motion sensor activity to a server. Is that possible?

Can you make Arduino Uno send information through a WiFi module to a server?

Yes, I can.

The simplest way is through an HTTP "GET" request. Every time you request a web page (and there are plenty of examples of that) you are sending data to the server to tell it both what web page to get (/foo/bar.php) and what data to submit to that web page (?baz=4).

It's then up to you to craft that GET request, such as:

GET /foo/bar.php?baz=4 HTTP/1.1
Host: example.com
Content-length: 0

and write the PHP web page (or whatever language you prefer to write web pages in) to do something meaningful with the "baz = 4" parameter.


Arduino Micro draws too much power from iPhone. How can I change that? I'm building a USB keyboard that has two buttons - space and enter. The plan is to use this USB keyboard (with an Apple Lightning connector to USB) with the built in iOS switch control. I bought the lightning to USB dongle, and hooked it up to a normal keyboard, and it works fine.

Next, I took an Arduino Micro (ATMEGA32u4) and programed it to act as a keyboard with the two keys I need (space and enter). On a PC, it works just fine, but when I hook it up to my iPhone, I get the message:

Arduino Micro: The connected device requires too much power.

I've done quite a bit of research on this, and I found this post. In a nutshell, that post said that when you connect a device to an iOS device, one of the first things it does is tell the iDevice how much current it could potentially draw. This number (about 200mA for the Arduino Micro) is what decides whether the iDevice will support the device or not, when in truth, the device will not come close to its max current draw, at least not in my case.

I hooked up a meter to the normal keyboard, and it draws just over 4mA. When I hook up the Arduino, it is drawing almost 40mA. While the Arduino is drawing much more than the keyboard, it should be okay, because when I plugged in a flash drive, it was drawing 50mA, but the iPhone didn't complain.

There is my story, here is my question:

Is there any way to change it so that the Arduino Micro doesn't request so much power? In other words, is there a way to reset the value that is causing the iPhone to not use the device?

The power consumption is part of the exchange with the PC when it is plugged in. You can change that. Find the file USBCore.h in your Arduino install directory. In my case (under Linux) it was:

./hardware/arduino/avr/cores/arduino/USBCore.h

Inside that file, at around line 269 (depending on the distribution) you should see these lines:

#define D_CONFIG(_totalLength,_interfaces) \
    { 9, 2, _totalLength,_interfaces, 1, 0, USB_CONFIG_BUS_POWERED | USB_CONFIG_REMOTE_WAKEUP, USB_CONFIG_POWER_MA(500) }

On the right of the second line is the requested power consumption in milliamps (currently 500). Change that to (say) 100:

That is, change USB_CONFIG_POWER_MA(500) to USB_CONFIG_POWER_MA(100).

Save and recompile.

You may find that the bootloader initially requests 500 mA even with this change (as it initially runs the bootloader). However when the sketch starts it should re-establish a USB connection and only request 100 mA. To fix that you would need to recompile the bootloader with the same fix, and reinstall it, a somewhat more complex task.

Another possible approach would be to tweak the fuses so that it doesn't run the bootloader, if you have finished debugging your code. Only do that if you are confident with playing with the fuses.


Can I set an Arduino pin as input and output? When I used to program PICs, there was a way to set the pins to input and output, at the same time. Can this be done on the Arduino?
I see the pinmode documentation, but nothing about being an IO port.

No there is no function that lets you set all the pins to either input or output at the same time, but it wouldn't take much to write one.

No, you can't set an Arduino's pin as bidirectional.  If you are running out of pins look at IO expanders or multiple Arduinos.

Hope that helps, if not please feel free to clarify what it is you would like to know and we'll try and help.


read data from controller via RS485 Modbus rtu Arduino I have a device with an rs485 port from which I would like to read the ph value. Below is the connection with the RS485 adapter.

I tried to read the data with this code but doesn't work:

#include SoftwareSerial.h

#define SSerialRX        10  //Serial Receive pin
#define SSerialTX        11  //Serial Transmit pin
#define SSerialTxControl 3   //RS485 Direction control
#define RS485Transmit    HIGH
#define RS485Receive     LOW
#define Pin13LED         13

SoftwareSerial RS485Serial(SSerialRX, SSerialTX); // RX, TX
byte byteSend;
byte request[] = {0, 0x03, 0, 0, 0, 0x01, 0x85, 0xDB};

void setup()
{
  // Start the built-in serial port, probably to Serial Monitor
  Serial.begin(9600);
  Serial.println("SerialRemote");  // Can be ignored

  pinMode(Pin13LED, OUTPUT);
  pinMode(SSerialTxControl, OUTPUT);

  digitalWrite(SSerialTxControl, RS485Receive);  // Init Transceiver

  RS485Serial.begin(9600);
  delay(2000);
   RS485Serial.write(request, sizeof(request));

   digitalWrite(Pin13LED, LOW);
   delay(10);
   digitalWrite(SSerialTxControl, RS485Receive);

}
void loop()
{

  if (RS485Serial.available())
  {
    byteSend = RS485Serial.read();   // Read the byte
    Serial.print(byteSend, HEX);
    Serial.print(" ");
  }
}

Could you help me?
Thanks

I can't say if this is your problem or not but I don't like this bit of code:

   RS485Serial.write(request, sizeof(request));

   digitalWrite(Pin13LED, LOW);
   delay(10);
   digitalWrite(SSerialTxControl, RS485Receive);

You're sending the request then waiting 10ms and switching to receive mode.  That might be enough of a delay, but it's hard to say (best case, 960Bps at 9600 baud gives about 1ms per byte, which is 8ms for the request, but with software serial it may not be that simple).

Instead you should be using the flush method of the Stream class to wait for the data to be transmitted:

   RS485Serial.write(request, sizeof(request));

   digitalWrite(Pin13LED, LOW);
   RS485Serial.flush();
   digitalWrite(SSerialTxControl, RS485Receive);


Light multiple RGB Led Strips from same 3 RGB PWM outputs I need to control about 6 RGB Led Strips from an Arduino Board. The problem is that i need 3 PWM outputs for each led strip, but each will have probably the same colors. I was wondering if i could put two strips receiving a signal from the same PWM output, then i would have to use half the PWM outputs but send the same signal for each pair of strips.
The scheme i found is this one:

And what i want is something like this:

Is this possible? What should i modify to make it work?
Thanks in advance.

You have few options:

do as you represented in the drawing: it should work, as I expect the transistors to not load too much the input.
add a logic buffer inbetween the arduino and the driver stage
use other pins from the arduino for driving the additional strips and bitbang the PWM, instead of using the HW blocks

Whether the solution you propose (1) will work or not depends entirely on the max current that each PWM pin can output vs the total load from the 3 transistors it will have to drive.


How can I get a unique address for all my Arduino boards while in RS485? My attempt is to know how to identify the board I'll be sending parameters to in a serial connection like rs485.  I'm asking because I will have about 11 or so mcu's as "Rx slaves" while my pc is the Master "Tx". I want to know how my code block is being sent to a specific board will be received by just that board and not all the other boards connected to that Rx port COM?

If I send 'LT2|LP3|LM5|LR4|LI6' and I want that to be for one specific Arduino, I don't want all the other 10 arduinos to take those parameters in this serial Rx line.

@Federico Fissore you mentioned in another post "Some boards, when connected to a computer, publish their serial number. My Arduino Uno R3 says"

[16818.451423] usb 3-2: SerialNumber: 85235353137351E02242

how and where can i find this info?

Just assign every node a variable like "const int ID = 5" and so on and then before sending the instructions send a line terminator, the ID, line terminator and the data you need to send to the nodes. Every device listens but they all wait their ID to accept the commands. For example:

Serial.write('\n');
Serial.print(ID);
Serial.write('\n');
Serial.print(|LT2|LP3|LM5|LR4|LI6);
Serial.write('\n');

NOTE: This is the easiest way. Most likely not the most reliable or optimized.


Is Gsm antenna effect on microcontroller working? in my embedded system I used patch antenna and Atmega 328 microcontroller,but somehow it causes the abrupt function of a microcontroller or reset. how can it be solved?

There are 3 possible causes that I can think of (it's difficult to say more without further details):

SW bug: this is hard to confirm without actually finding the bug, but it might cause a lock-up and trigger a watchdog reset (do you have a watchdog running?) or a pointer error cause a jump to some memory location along the boot path (not so likely, I suspect)
Too tight power envelope: when your system tries to transmit, it draws more power than the power supply/battery can provide. This cause a temporary voltage drop, to the point that the system kinda power cycles. You can try to use a power supply with higher maximum current.
Electromagnetic interference: somehow the transmission interferes with the AVR. You can try to direct the antenna further away from the AVR and to increase the distance in between.

But you should really add more information to your question.


Direct 5V current based on analog signal I would like to manage many LEDs from my Arduino - 12 or so - but I do not have the available digital pins to do this. Only one LED needs to be on at one time. Instead, I was hoping to control these with an analog pin. I was wondering if there is some sort of switch out there which can take an analog signal and, based on the value, direct a 5V current to a certain LED.

I realize that I could use a second Arduino for this, but I am trying to avoid that.

Thanks in advance for any help!

If you have 4 pins available, you could use charlieplexing to selectively light up 12 led.

Alternatively you could use some IC. You could use the one Greg suggested.

Or you could use a shift-register. This requires only 2 or 3 pins, an will enable you to light up any one or more leds at the same time. Most have 8 outputs, but you can connect one to the other (daisychain), so with 2 shift-registers you can individually turn on/off 16 leds. You can easily control these using arduino's shiftOut command.

You could also use a port-expander using I2C to talk to it. More complicated, and a bit more expansive. But also more powerful. It will require only 2 pins (A4, and A5).


CurieBLE receive data without pairing I read exist articles about it, but still not understand how to do that.
I have a Genuino 101 and an EEG Headband (neuro interface). Need to get data from neuro device. With external HC-05 bluetooth module the code look like this:

 SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
 bluetooth.begin(57600);
 while (!bluetooth.available()) {}
 byteRead = bluetooth.read();

Has anyone encountered a similar problem?
Thanks!

HC-05 module is not BLE (Bluetooth 4.0)! HC-05 implements SPP (Serial port profile) over Bluetooth Classic (Bluetooth 2.0). You will need a module with BLE capability and that is not over yet. BLE implements several (hundred) profiles for each task such as heartrate monitor, neuro monitor, time etc etc. Your BLE module must be condigured to receive a specific profile data.


Can't connect my ESP-12F to WiFi with my Arduino Uno Recently I bought this wifi adapter for my IOT projects that I connected to my arduino uno that seems to not working.
I have tried with the arduino ESP8266WiFi library with RX connected to pin 0 and TX connected to pin 1 I have also tried the softwareSerial and still the same result that is, in the serial monitor i always get "error" or I get nothing
Thank you in advance and sorry if I made a mistake in the post, I am new to StackExchange :)

edit (added code to question):

#include <SoftwareSerial.h>

SoftwareSerial ESPSerial(10, 11); // RX, TX

void setup() {
  // Open serial communications
  Serial.begin(115200);
  // set the data rate for the SoftwareSerial port
  // if this doesnt work you for you then try different baud rate
  ESPSerial.begin(115200);
  ESPSerial.println("Ready to take AT commands");
}

void loop() { // run over and over
  if (ESPSerial.available()) {
    // reads input from serial console and writes to esp8266
    Serial.write(ESPSerial.read());
  }
  if (Serial.available()) {
    // reads input from esp8266 and writes to serial console
    ESPSerial.write(Serial.read());
  }
}

gpo0 goes to ground to program the module


Failed to boot VL53L0X: VL53L0X Error: -6 I am using a VL53L0X sensor in my project.
It was working fine when suddenly it started to show failed to boot error.
I tried debugging but of no use. I ran I2C scanner sketch and it detected the sensor at 0x29.
I get the following error -
23:38:27.797 -> Adafruit VL53L0X test
23:38:27.830 -> VL53L0X Info:
23:38:27.830 -> Device Name: VL53L0X ES1 or later, Type: VL53L0X, ID: VL53L0CBV0DH/1$1
23:38:27.830 -> Rev Major: 1, Minor: 1
23:38:27.864 -> VL53L0X: StaticInit
23:38:27.932 -> VL53L0X: PerformRefSpadManagement
23:38:27.932 -> refSpadCount = 2226323456, isApertureSpads = 92
23:38:27.932 -> VL53L0X Error: -6
23:38:27.932 -> Failed to boot VL53L0X

This is the code I used (its the example code with just 0x29 and true passed in begin function for verbose output):
#include "Adafruit_VL53L0X.h"

Adafruit_VL53L0X lox = Adafruit_VL53L0X();

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

  // wait until serial port opens for native USB devices
  while (! Serial) {
    delay(1);
  }

  Serial.println("Adafruit VL53L0X test");
  if (!lox.begin(0x29,true)) {
    Serial.println(F("Failed to boot VL53L0X"));
    while(1);
  }
  // power
  Serial.println(F("VL53L0X API Simple Ranging example\n\n"));
}

void loop() {
  VL53L0X_RangingMeasurementData_t measure;

  Serial.print("Reading a measurement... ");
  lox.rangingTest(&measure, false); // pass in 'true' to get debug data printout!

  if (measure.RangeStatus != 4) {  // phase failures have incorrect data
    Serial.print("Distance (mm): "); Serial.println(measure.RangeMilliMeter);
  } else {
    Serial.println(" out of range ");
  }

  delay(100);
}

I am using an Arduino nano -
following are the connections
ARDUINO->VL53L0X
3v3->Vin
GND->GND
A4->SDA
A5->SCL
I have rechecked the connection and voltages the sensor does receive 3v3 and gnd.
I need help with this asap.
Thanks in advance :)

I was facing same issue, now my problem is solved here.
This problem mostly occurs when we apply a power supply to the MCU that has capacitors at its output. This type of power supply's rising voltage is like you can see the image:

If you look at the data sheets of MCUs, you see that most MCUs can work at 1.8V to 5.5V. Here the rising voltage is slow; the MCU starts working at 1.8V and send signals to VL53L0x, but the sensor doesn't work at 1.8V.
So, what you need to do is add some delay (first power supply gets stable then start communication with sensor) in your code to avoid this issue. Do not add delay in the loop; it will affect the working of the MCU, where exactly you need to add delay. Code modifications are in the video below:
https://youtu.be/QEiNbTB8nNE
or you just can search on Youtube: How to fix VL53L0X error


Append Text to Variable Names: Please Help Me Shorten This Code I'm trying to shorten the code under "setup" below, where I have over 120 variables that are being read from an external EEPROM. There is a pattern where the variable that stores the position of the EEPROM address is the name of the variable being populated, plus the word "Pos".

byte fanSpeed, nl1Toggle, ledsToggle;
byte fanSpeedPos = 12, nl1TogglePos = 95, ledsTogglePos = 7;

void setup() {
  fanSpeed = readEE(fanSpeedPos);
  nl1Toggle = readEE(nl1TogglePos);
  ledsToggle = readEE(ledsTogglePos);
  //there are over 120 of the above readEE statements in the actual code.
}

uint8_t readEE(uint8_t entry) {
  readEEPROM(AT24C32_ADDRESS, 1, entry);
}

Ideally I would like it to work like this (I'm using pseudo code because I don't know how to do this):

char* variableNames [] = { "fanSpeed", "nl1Toggle", "ledsToggle" };
byte fanSpeedPos = 12, nl1TogglePos = 95, ledsTogglePos = 7;

void setup() {
  for (int i = 1; i < 120; i++;) {
    variableNames[i] = readEE(variableNames[i] + 'Pos');
  }

Is this possible using C++ / Arduino?

variableNames[i] = readEE(variableNames[i] + 'Pos');

  Is this possible using C++ / Arduino?

No! Very few programming languages allow that as it requires a lot of run-time information.

Let us instead revisit you issue; Load a large set of variables from EEPROM. What mechanisms do we have in C/C++ and AVR library that could help with this?

Here is a really simple solution that results in a "one-liner"; eeprom_read_block().

struct var_t {
  byte fanSpeed, nl1Toggle, ledsToggle;
};
var_t var;
const void* pos = ...;
eeprom_read_block(&var, pos, sizeof(var));

Obviously var_t and var are not very good names (and you will have to come up with something better) and this is for the internal EEPROM but the same technique can be used for the I2C EEPROM.

Cheers!

BW: What AT24CXXX library are you using? Because this looks strange.

 uint8_t readEE(uint8_t entry) {
   readEEPROM(AT24C32_ADDRESS, 1, entry);
 }

No return statement, etc.


Unable to access SD Card when using GPS and MS5611 sensors I'm trying to connect multiple sensors to an arduino and write the retrieved data in to a SD. When I test each module separately it works properly, but when I put everything together the SD card module doesn't work, can anybody help me?

This is the code that I'm using:

#include <Arduino.h>
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <MS5611.h>

// SD
#define GPS_STORED_DATA_FILE_NAME "gps.txt"
#define SDCARD_PIN 10
bool _sdError = false;

// GPS
#define GPS_RX_PIN 9
#define GPS_TX_PIN 8
#define GPS_BAUD 9600
TinyGPSPlus _gps;
SoftwareSerial _ss (GPS_RX_PIN, GPS_TX_PIN);
unsigned long _timeLastMeasurementGps;

// MS5611
MS5611 _ms5611;

void sdTest(double latitude, double longitude, float elevation, double time) {
  if (_sdError) {
    //Serial.print("SD ERROR. Stopping writing");
    return;
  }
  String fileName = GPS_STORED_DATA_FILE_NAME;
  File myFile = SD.open(fileName, FILE_WRITE);

  if (myFile) {
    Serial.print("Writing to ");
    Serial.print(fileName);
    Serial.print("...");
    //myFile.println("testing 1, 2, 3.");
    myFile.print(latitude);
    myFile.print(" | ");
    myFile.print(longitude);
    myFile.print(" | ");
    myFile.print(elevation);
    myFile.print(" | ");
    myFile.println(time);
    myFile.flush();
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening");
    Serial.print(fileName);
    _sdError = true;
  }

  // re-open the file for reading:
  myFile = SD.open(fileName);
  if (myFile) {
    Serial.print(fileName);
    Serial.println(":");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
        // Serial.write(myFile.read());
      myFile.read();
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.print("error opening ");
    Serial.println(fileName);
  }
}

void smartDelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (_ss.available())
      _gps.encode(_ss.read());
  } while (millis() - start < ms);
}

void setupSd() {
  Serial.print("Initializing SD...");
  pinMode(SS, OUTPUT);

  if (!SD.begin(SDCARD_PIN))
    Serial.println(" ERROR");
  else
    Serial.println(" DONE");
}

void setupGps() {
  Serial.print("Initializing GPS...");
  _ss.begin(GPS_BAUD);
  smartDelay(1000);
  _timeLastMeasurementGps = millis();
  Serial.println(" DONE");
}

void setupMs5611()
{
   Serial.print("Initializing vario...");
   while(!_ms5611.begin(MS5611_ULTRA_HIGH_RES))
  {
    Serial.println("Could not find a valid MS5611 sensor, check wiring!");
    delay(500);
  }
  // Serial.print("ms5611 Oversampling: ");
  // Serial.println(_ms5611.getOversampling());
  Serial.println(" DONE");
}

void setup()
{
  Serial.begin(115200);
  setupMs5611();
  setupSd();
  setupGps();
}

void loop()
{
  delay (100);
   sdTest(1, 2, 3, 4);
}

Thanks in advance!

I suspect that your problem lies with how your SD card is connecting via the SPI bus.

The problem is that a lot of Serial Peripheral Interface (SPI) devices, particularly the cheaper ones, don't properly put the MISO pin into high-impedance when SS is pulled high.

I had almost exactly this situation with one of my projects. I eventually resolved it by placing a tri-state buffer in the MISO line for each of the SPI devices.

I used a 74HC125 (4-channel tri-state buffer).

This is the page on Better SPI Bus Design in 3 steps that finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).