text:
adding a dead band to my motor and gearbox
I have a motor and gearbox that has limits and a pot built in.
I have some code what drives the motor one way to when it hits its limits takes a value and drives the other way and takes a value, then map the range from 0 to 100, that all works fine.
I also have a analog input map to 0 to 100 what I would like to do is to drive the motor to where ever the analog input is at, which is what I have done with the code below but when the motor gets close it starts hunting backwards and forwards.
I tried to add some sort of dead band (where + 0.5 / where - 0.5) it just seems to just move the problem.
I did try -+ but this still did not help, so what I need to do is aim for the target value and stop then if I'm within 0.5 ether way then that is good enough.
How can I do that?
sensor       = pot on motor,
where        = 0 to 5 input,
vent1UPlim   = limits,
vent1DOWNlim = limits

PS. I know the map of 0 to 100 could do with being bigger but it's just easier to get my head around at the moment.
        //            pot           0-10v     ONE WAY
          if (sensorValue > (where + 0.5)) {
          if (digitalRead(vent1UPlim)==    HIGH) {
            DoneInitializationA=false;
            digitalWrite(vent1enable,      HIGH);
            delay(50);
            digitalWrite(vent1PWMA ,       HIGH);
            mydisp.drawStr(0, 2, "-close-|");
          }
          else {
            digitalWrite(vent1PWMA ,       LOW);
            delay(50);
            digitalWrite(vent1enable,      LOW);
            mydisp.drawStr(0, 2, "       |");
          }
        }
        else {
          if (!DoneInitializationA)
          {
            digitalWrite(vent1PWMA ,       LOW);
            delay(50);
            digitalWrite(vent1enable,      LOW);
            mydisp.drawStr(0, 2, "       |");
            DoneInitializationA=true;
          }
        }

           //                                   OTHER WAY
          if (sensorValue < (where - 0.5)) {
          if (digitalRead(vent1DOWNlim)==  HIGH) {
            DoneInitializationB=false;
            digitalWrite(vent1enable,      HIGH);
            delay(50);
            digitalWrite(vent1PWMB ,       HIGH);
            mydisp.drawStr(0, 2, "-open -|");
          }
          else {
            digitalWrite(vent1PWMB ,       LOW);
            delay(50);
            digitalWrite(vent1enable,      LOW);
            mydisp.drawStr(0, 2, "       |");
          }
        }
        else {
          if (!DoneInitializationB)
          {
            digitalWrite(vent1PWMB ,       LOW);
            delay(50);
            digitalWrite(vent1enable,      LOW);
            mydisp.drawStr(0, 2, "       |");
            DoneInitializationB=true;
          }
        }

I don't quite understand how your motors work: Do they keep doing the last thing they were told, or do you have to keep sending some signal to them - even to stay at the same speed?

enable the drive pull hight (vent1enble), and to drive the motor pull one pin high and to go the other way pull the other pin high (vent1PWMA or vent1PWMA)

OK, so if you do nothing, the motor keeps turning at the same rate in the same direction as before? So, doing nothing if it is near the desired sensor value is OK?

if i do nothing the motor does nothing. doing nothing near the desired value yes

The simple way is to just subtract one from the other, take the absolute value and see if it exceeds your hysteresis range.
eg.
if (abs (sensorValue - where) >= 0.5) {
  {
  // do something

  if (sensorValue > where)
    {
    // one way
    }
  else
    {
    // other way
    }
  } // end of large enough to worry about

In response to this (since deleted):

would this not have the same problem as mine as instead of hunting round its target it will just do it 0.5 away from the target?

By subtracting and taking the absolute value, we create a band of +0.5 and -0.5 where, if the sensor is in that range, we do nothing. It hasn't moved the problem because it can't move in two directions at once (both up and down).

would this not have the same problem as mine instead of hunting round its target it will just do it 0.5 away from the target? as what will drive it into the middle (the target value)?   i hope you understand what I'm trying to get to
thanks Joe


text:
Better method for PROGMEM data access with multiple indirection?
-edit-
This is a simplified recreation of personal learning project I have ongoing.  My issue is in accessing data in flash, the path to which includes multiple layers of indirection.  When the data was in RAM I found accessing it easy and all worked as expected.
In flash I have created a struct mylist, aa in the example, containing a pointer to an char* array (item_list[ ])(in flash) pointing to char[ ] (in flash).
Problem: (refer to example) Given a pointer to struct aa (pml) and an index into item_list[] (ndx), how to correctly retrieve the string from flash.  My example illustrates the only method I can find that works. It seems kludgy at best, in particular needing to twice read pointers from flash as well as calculating the array item offset.  Have I missed a proper cast or perhaps become confused about 32 vs 16 bit pointers? Or, as strange as it seems, is this the correct and/or best approach?
All help and constructive criticism will be appreciated.
Code:
#include "Arduino.h"
#include <avr/pgmspace.h>

const char x[] PROGMEM = {"Item x"};
const char y[] PROGMEM = {"Item y"};
const char* const item_list[] PROGMEM = {x, y};

struct mylist {
  uint8_t nitems;
  const char** const list;
};
const mylist aa PROGMEM = {2,(const char** const)item_list};

const mylist* pml = &aa;

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

  char cbuf[11] = {"__________"};

  // two line with declared intermediate pointer
  uint8_t ndx = 0;
  const char* pitem = (const char*)pgm_read_ptr_near(&pml->list) + (ndx * sizeof(const char*));
  strcpy_P(cbuf, (const char*)pgm_read_ptr_near(pitem));
  Serial.print("item[0]: /");
  Serial.print(cbuf);
  Serial.println("/");

  // one line without declared intermediate pointer
  ndx++;
  strcpy_P(cbuf, (const char*)pgm_read_ptr_near(pgm_read_ptr_near(&pml->list)
                                                + (ndx * sizeof(const char*))));
  Serial.print("item[1]: /");
  Serial.print(cbuf);
  Serial.println("/");
}

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

}

Output:
item[0]: /Item x/
item[1]: /Item y/

-edit-
After many more hours trying many more variations, I feel the approach shown in the following example is workable for me. I have chosen to keep the extra level of indirection to maintain all the flash data for a particular Field in one struct ‘package’. @NickGammon and his excellent examples greatly helped my understanding and comfort level with pointers in and to flash.
The listing is meant to give context to my point in question and is summarized in the method _copyitem( ) (hope the underscore is ok):
void Field::_copyitem(uint8_t ndx){
  PGM_VOID_P plist = pgm_read_ptr(&_fp->list);
  PGM_P pitem = (PGM_P)pgm_read_ptr(plist + ndx * sizeof(char*));
  strlcpy_P(_value, pitem, getLength());
}

This listing recreates a very small subset of the overall codebase, but the one part that has stopped my progress.
#include "Arduino.h"
#include <avr/pgmspace.h>

struct FieldDefinition {
  uint8_t nitems;
  const char** list;
  uint8_t row;
  uint8_t column;
  uint8_t length;
  // etc, etc
};

class Field {
public:
  Field(const FieldDefinition*  /* other parameters */);
  ~Field();  // -edit-
  char * selectItem(uint8_t);
  uint8_t getLength();
  char * selectItem(uint8_t);
  uint8_t getLength();
private:
  const FieldDefinition * _fp;
  char * _value;
  uint8_t _ndx;
  void _copyitem(uint8_t);
};

Field::Field(const FieldDefinition* fp ) : _fp(fp) {
  _ndx = 0;
  char * _value = new char[getLength()];
 _copyitem(_ndx);
};
Field::~Field(){  // -edit-
  delete _value;
};
char * Field::selectItem(uint8_t ndx){
  _ndx = ndx;
  _copyitem(_ndx);
  // display item
  // do more here . . .
 return _value;
}
uint8_t Field::getLength(){
  return pgm_read_byte(&_fp->length);
}
void Field::_copyitem(uint8_t ndx){
  PGM_VOID_P plist = pgm_read_ptr(&_fp->list);
  PGM_P pitem = (PGM_P)pgm_read_ptr(plist + ndx * sizeof(char*));
  strlcpy_P(_value, pitem, getLength());
}

// Setup flash data
// selection list
const char f1_0[] PROGMEM = {"Item 0"};
const char f1_1[] PROGMEM = {"Item 1"};
const char f1_2[] PROGMEM = {"Item 2"};
const char* const f1_list[] PROGMEM = {f1_0, f1_1, f1_2};
// create in-flash struct
const FieldDefinition f1 PROGMEM = {4,(const char**)f1_list,1,1,10};
// global instance and pointer to Field
Field * s1f1 = new Field(&f1);

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

  Serial.println();
  Serial.print("Field Length: ");
  Serial.println(s1f1->getLength());
  Serial.println();
  for (uint8_t i = 0 ; i < 3; i++) {
    Serial.print("Selection at index ");
    Serial.print(i); Serial.print(" : ");
    Serial.println(s1f1->selectItem(i));
  }
}

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

}

Output
Field Length: 10

Selection at index 0 : Item 0
Selection at index 1 : Item 1
Selection at index 2 : Item 2

I could very wrong (as previously demonstrated) so comments please.
-edit-
Point taken and completely understood.  Destructor added for completeness.  In my actual application, multiple fields are constructed by a screen class when a screen is displayed, user interaction accepted, configuration data stored in EEPROM (my next endeavor), then destroyed on screen exit. Selecting from a list is one method available to populate the field value. The whole interface consists of multiple fields, for multiple screens, driven by an underlying state engine, stepped during each ‘loop’ to minimize impact. It functions as expected in an Xcode simulation, and has been a wonderful learning experience moving it to Arduino.  I thought all this was non sequitur to my question and regret any confusion I may have caused.
To restate my issue: how to get from
// ram based
strcpy(value, _fp->list[ndx]);

to
// flash based
PGM_VOID_P plist = pgm_read_ptr(&_fp->list);
PGM_P pitem = (PGM_P)pgm_read_ptr(plist + ndx * sizeof(char*));
strcpy_P(value, pitem);

using best/correct form with multiple layers of indirection as posted. Is it possible I have missed a proper cast or other mechanism that would allow the compiler to handle the ‘pointer magic’? It appears I have not. @NickGammon I greatly appreciate your input.

Is there some reason you're named your macros so that they specifically conflict with reserved identifiers (underscore followed by a capital letter)? Is there a reason for those macros in the first place?

@Matti  Certainly not intended to conflict, just stand out, and being the case I will stop. Suggestions for form of personal macros, or is there a standard?  The reason is purely personal, I am not good at with keyboards and after typing “Serial.print” the first hundred times I wanted to abbreviate.  Thanks for the observation.

I don't mean this unkindly, but I'm having a lot of trouble reading your code. Can you explain what it is doing? Whatever it is, I think there must be an easier way. Take a look at my page about PROGMEM - see if that helps. And @MattiVirkkunen is quite correct, variables starting with an underscore and followed by a capital letter are reserved for the compiler.

@Nick Gammon  Just the opposite, I take your comment as quite kind. I freely display my ignorance in hope of learning and improving.  Trust I shall never use _Cap again, or perhaps macros at all.  I have read your posted work with respect to PROGMEM several times and in fact have it bookmarked.  It has greatly help my transition to flash. Thank you!  I have edited my submission and reduced to my main point of question as the rest seems to be a distraction and not the insight into my thought process as I had hoped.

What is wrong here precisely? Is the output not what you expect?

See my amended answer to your amended question. :P

const char x[] PROGMEM = {"Item x"};
const char y[] PROGMEM = {"Item y"};
const char* const item_list[] PROGMEM = {x, y};

struct mylist {
  uint8_t nitems;
  const char** const list;
};
const mylist aa PROGMEM = {2,(const char** const)item_list};

It seems to me this is way too wordy for what appears to be trying to store a list of a couple of strings.

First:
const char* const item_list[] PROGMEM = {x, y};

You have a array of pointers to strings. OK.

Now:
struct mylist {
  uint8_t nitems;
  const char** const list;
};
const mylist aa PROGMEM = {2,(const char** const)item_list};

Now you have a list of an array? This is where I am confused.

Compare to an adaptation of the code on Putting constant data into program memory (PROGMEM):
const int NUMBER_OF_ELEMENTS = 2;

const char Message0000 [] PROGMEM = "Item X";
const char Message0001 [] PROGMEM = "Item Y";

const char * const messages[NUMBER_OF_ELEMENTS] PROGMEM =
   {
   Message0000,
   Message0001,
   };

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

  for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
    {
    char * ptr = (char *) pgm_read_word (&messages [i]);
    char buffer [80]; // must be large enough!
    strcpy_P (buffer, ptr);
    Serial.println (buffer);
    }   // end of for loop

  }  // end of setup

void loop () { }

Edited to comment on new code
You have a major problem here:
Field::Field(const FieldDefinition* fp ) : _fp(fp) {
  _ndx = 0;
  char * _value = new char[getLength()];
 _copyitem(_ndx);
};
char * Field::selectItem(uint8_t ndx){
  _ndx = ndx;
  _copyitem(_ndx);
  // display item
  // do more here . . .
 return _value;
}
uint8_t Field::getLength(){
  return pgm_read_byte(&_fp->length);
}
void Field::_copyitem(uint8_t ndx){
  PGM_VOID_P plist = pgm_read_ptr(&_fp->list);
  PGM_P pitem = (PGM_P)pgm_read_ptr(plist + ndx * sizeof(char*));
  strlcpy_P(_value, pitem, getLength());
}

What I gather you are doing here is, to get the string for an item (for printing) doing a new (which allocates memory), copying from PROGMEM into that memory, displaying that item, and then ignoring the allocated memory. Well, you can't do that. You will run out of RAM very quickly.
The code doesn't even have the word delete in it. Every new should have a corresponding delete. It's a fundamental principle.
It looks too complex still. Make a function that just displays the item (menu or whatever it is) without actually making a copy of it. Certainly don't allocate memory and not free it.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Controlling a sliding tray - beginners project
I have a small light metal platform about 30 cm square mounted on horizontal rails. It is well lubricated and slides easily from side to side. I would like to build a device to connect to the underside of the platform that will allow me to programatically move the platform left or right by a defined distance at the touch of a button.
While I've never used an Arduino, I've been aware of its existence for a while and felt this might be a good project to begin experimenting with it. For context, I'm a computer programmer by trade, but have limited exposure to electronics in general.
Where would be a good place to start?  Are there books that are considered the "bible" of Arduino development? Are there existing projects that  basically do what I'm hoping to achieve? Am I barking up the wrong tree and shouldn't be attempting to find a solution for this with an Arduino? Any input would be greatly appreciated.

A stepper motor, with either a timing belt or lead screw would work for this. Arduino would be the most appropriate way to control those in this case.

You may find  robotics.stackexchange useful too.

A stepper motor moves a precise number of steps per revolution. This is a gross over simplification but with a stepper motor controller and an Arduino Stepper Motor Library (there are several) you can rotate the motor forward and backwards by precise amounts. My YouTube video covers controlling stepper motors with an Arduino. https://youtu.be/yV30DO6NO2Y

Thanks guys, this has all given me some excellent starting points. I now have a starter kit and a couple of books to get me going. Many thanks!

Am I barking up the wrong tree and shouldn't be attempting to find a solution for this with an Arduino?

Not at all. For example see Reprap - a 3D printer using an Atmega1280 as the controller. As it says here:

Arduino is an open source project that has created an easy and powerful microcontroller board based on the Atmel ATmega168. It is the brain of the RepRap electronics.

If you can make a 3D printer with an Arduino, then you can make your sliding platform gadget, which sounds simpler if anything.

Are there existing projects that basically do what I'm hoping to achieve?

Reprap, for one.

Are there books that are considered the "bible" of Arduino development?

This is a broad question, and your original question already has a couple of "flags" that it is too broad. I suggest you narrow it down a bit.
There are a number of books about learning Arduino. My advice is to start doing some simple projects (simpler than the platform initially) to get the hang of compiling, uploading, and generally working with microcontrollers.

Also try Google and YouTube. There are a lot of Arduino projects out there.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Buzzer - Does the voltage change with the frequency?
So I have this project where the component "buzzer" is implementet. I was wondering if the voltage is changing along the change of frequency given to the buzzer?
Note that the project just says "buzzer" - not any more details.
Project: http://www.instructables.com/id/Arduino-Distance-Detector-with-a-Buzzer-and-LEDs/?ALLSTEPS

Please supply more details, this is just unanswerable. What project?

http://www.instructables.com/id/Arduino-Distance-Detector-with-a-Buzzer-and-LEDs/?ALLSTEPS

What voltage? The buzzer voltage? The frequency will change, not the voltage.

So the voltage in the circuit is not affected by the buzzer; say when it's on and when it's off?

The buzzer would consume some current which may lower the voltage. Why are you asking all this?

No, the frequency of the "buzzer" has no relationship to the voltage.
The duty cycle of the generated tone is proportional to the average voltage though.  Typically the duty cycle is 50% - that is it's turned on for half the time, and turned off the other half the time, to make a square wave.  This means that the average voltage is 50% of the supply voltage.
If you were to low-pass filter the signal (say through an RC filter as many people do to create a crude DAC) you would end up with a voltage around 2.5V.
Changing the frequency doesn't change the duty cycle, it only changes the audio pitch.
The only caveat to that is that if the buzzer draws more current that the IO pin (or the power supply) can source then it may cause the voltage on that IO pin to droop.  That has nothing to do with the frequency though and it would droop just the same at all frequencies.  Basically the IO pin has a small resistance to Vcc through the MOSFET that drives it internally - the higher the current the more voltage is dropped across that resistance, and the lower your resultant output voltage.  Draw too much current and the heat dissipated by that MOSFET's resistance becomes too great and damages the chip.


text:
How to troubleshoot the Arduino Mini and Arduino usb2serial?
I am trying to get an Arduino Mini (R5, mega 328p) working.
Just connecting it to power has following effect: the on-board LED lights up. It's the power-on-led, I presume.
Since other Arduino devices often come with the blink-example pre-flashed I hooked up a LED to pin 13 - result: no blinking.
Curiously, connecting the LED to pin 12: blinking
Does the Mini come pre-flashed with a blink 'sketch' that blinks pin 12 instead of 13?
To test uploading I've connected it to an Arduino USB2Serial module. The module is labeled with 'made in Italy' and has printed 'USB2SERIAL LIGHT' on it where the LIGHT is overwritten with a blue marker.
I've connected it like described in the arduino mini guide.
In the IDE I've selected the board 'Arduino Mini' and the '328' CPU.
Unfortunately, uploading fails with:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00

The external reset is connected like in the guide. But I also tried to manually press the reset button (immediately before the upload, or long press and release after upload button is clicked). Still, the same error.
When the manual reset is pressed the pin-12-blinking stops for a while (perhaps the bootloader is then executed) but then starts again.
The Arduino2serial has 3 LEDs. The ON-LED lights up when connected to the USB. When hitting the upload button in the IDE, the RX-LED flashed shortly one time after a while. That's it.
Thus my question: How to I troubleshoot this? Can I test the arduino usb2serial on its own? What's up with the pin-12 blinking of the mini?
In case this matters, I am on Fedora Linux, uploading to other Arduino devices (Uno, Micro) works as expected.
update usb2serial: I just hooked up the Arduino usb2serial and connected the TX/RX pins via a jumper cable - a minicom session then results in text being displayed and the rapid flashing of the RX/TX LEDs. Disconnecting RX/TX again shows no display of any text inside minicom, and no flashing of the RX/TX LEDs.
I used following command line:
$ minicom -D /dev/ttyACM0 -b 115200

Thus, the usb2serial module seems to work.
update: I've checked all the jumper cables and there was a faulty one. With that replaced flashing works. After hitting the reset-button. The 'ext reset' pin is connected but the remote-reset does seem to work. Anyways, hitting the reset-button is easy-enough, for now.
final update: The root cause for remote-reset (a.k.a. auto reset) that the capacity of the used capacitor was too small. After exchanging it with a 100 nF one (as specified in the guide) the remote-reset works as expected. That means just hitting the upload button in the IDE automatically resets the device and the sketch is uploaded.

Did you try uploading just after reset?

@IgnacioVazquez-Abrams, yes, I did - ultimately, the root cause was a cable (cf. update) - now, the point when I hit the reset-button is relatively non-time-critical.

The remote reset is done through the DTR line, iirc, so if that is not wired, reset won't work. You can refer to the schematics for UNOR3, to reproduce the wiring.

@Igor, the 'ext reset' pin of the USB2Serial 'mirrors the DTR line of the virtual serial device on the computer' - and was connected to the reset pin of the Mini. Problem was that out of a mistake I used a too small capacitor (< 100 nF). With 100 nF the software-reset works as expected.

As always, it makes sense to check the parts in isolation, if possible.
Host system (Linux):

Tail the system log for errors
Check that ModemManager does not occupies the /dev/ttyACM0 device

USB2Serial:

Connect it via USB to the host without anything else connected -> the ON-LED should be on, the RX/TX LEDs should be off, the system log should display some udev progress messages (including vendor ids), the system should have a new serial device, e.g. /dev/ttyACM0
Open the serial port with a terminal (e.g. via minicom -D /dev/ttyACM0 [-b baudrate], disable local echo and type something -> nothing should be displayed
Connect the RX/TX pins to each other with a jumper cable -> typing in the terminal session should now result in rapid flashing of the TX/RX LEDs and the echoing of the text

Arduino Mini:

Connect just the minimum, e.g. just power from a 9V battery/5V power supply and the reset pin to +5 (with a 10KOhm resistor in series) -> the power-on led should turn on
The chance is high that the device comes with a pre-flashed blink examples that either uses pin 12 or 13 -> connect external LEDs to pin 12 and 13 (in series with 220 Ohm resistors) -> one LED blinks after power on
Hit the reset button on the mini -> any LED blinking should stop for a while and then continue

Arduino Mini with USB2Serial:

Make sure that both RX/TX pairs are crosslinked (like a nullmodem cable), i.e. RX <-> TX and TX <-> RX.
Follow the mini guide on arduino.cc or arduino.org it includes a picture of the cabling
Verify that the capacitor connected between the USB2Serial 'ext reset' pin and the Mini reset pin has a capacity of 100 nF, otherwise, the auto-reset might not work
In case the automatic reset does not work, press the on-board-reset-button just before the upload
In case the error persists, check for dodgy cables with a multi-meter

IDE:

Make sure that it works with 'easier' stuff, e.g. flashing to a Uno (the Uno is easier because the USB-2-Serial part is integrated)
Enable verbose logging during upload (in the preferences)
Update the IDE in case it is very old


text:
problem using std::map. Are there known obstructing macros?
I have a header file, where I try to collect global variable declarations. When trying to typedef a map I get the following error:
n file included from Dis0_10.ino:7:
/var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build8295701509021940161.tmp/globals.h:23: error: expected initializer before '<' token

relevant code snippets from global.h are:
#ifndef GLOBALS
#define GLOBALS
#include <map>

...
typedef std::map<uint8_t,uint8_t> memmap_t;

I have no clue, why this statement should fail. I consider it rather straight forward. So I think there must be some problems of this kind here. Or am I missing another include?

The C++ standard library is not available for arduino.
Some implementations of similar containers or certain functions exist on the web, but for the most part the standard library is impractical on a device with such small amounts of both RAM and program memory.
An implementation of SGI STL for AVR has been documented here: http://andybrown.me.uk/wk/2011/01/15/the-standard-template-library-stl-for-avr-with-c-streams/
map is mentioned as being particularly impractical for anything less than an arduino mega(1280). An example of maps working is included on the page so it seems like a good lead if you really must use one, but I've never done this myself so I cant guarantee it still works.

In general, any sort of dynamic memory allocation is usually considered poor practices in embedded code development.

Ok this is definitely decision making information. I thought of map as a way of saving memory and cpu time. If the memory overhead is rather, I can go back to a sparse array and put into program memory. Thanks for the clue.


text:
Arduino Serial Hex Values
Apologies if I have missed a relevant post somewhere, but have search for days to try figure this out...
I have written some C# code to send a Byte Array over Serial from my PC to an Arduino Nano board (Through a USB to Serial Converter)
Why would I not receive the same HEX Values (in the Arduino serial monitor) as the Values I sent?
(The Values should be the HEX for numbers 0 - 9)
C# Code:
if(!serialPort1.IsOpen)
    {
        serialPort1.BaudRate = 9600;
        serialPort1.DataBits = 8;
        serialPort1.StopBits = System.IO.Ports.StopBits.One;
        serialPort1.Parity = System.IO.Ports.Parity.None;
        serialPort1.PortName = "COM" + cbCOMPort.Text;

        serialPort1.Open();
    }

    byte[] ByteArr = new byte[10];
    ByteArr[0] = 0x30;
    ByteArr[1] = 0x31;
    ByteArr[2] = 0x32;
    ByteArr[3] = 0x33;
    ByteArr[4] = 0x34;
    ByteArr[5] = 0x35;
    ByteArr[6] = 0x36;
    ByteArr[7] = 0x37;
    ByteArr[8] = 0x38;
    ByteArr[9] = 0x39;

    serialPort1.Write(ByteArr, 0, ByteArr.Length);
    serialPort1.Close();

Arduino Code:
void loop()
{
while (Serial.available()) {
delay(250);

byte thisByte = Serial.read();

Serial.print(thisByte,HEX);
Serial.print(" | ");
}
}

Values received in Arduino Serial Monitor:
D6 | B6 | 96 | 76 | 56 | 36 | 16 | F6 | 8D | 0 |

COMPLETE ARDUINO CODE WITH BLINKING LED TEST CODE
void setup()
{
// start serial port at 9600 bps:
Serial.begin(9600);
}

void loop()
{
while (Serial.available()) {
delay(250);
// get the new byte:
byte thisByte = Serial.read();
// add it to the inputString:
//inputString += char(intChar);

if(thisByte == 0x30 || thisByte == 0x39)
{
digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
delay(50);             // wait for a second
digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
}
Serial.print(thisByte,HEX);
Serial.print(" | ");
}
}

Because you have a serial baud rate mismatch? Because you have a pointless delay() in your serial receiving code? Try showing all your Arduino code - it might help us diagnose it.

@Majenko, I have Tripple Checked the baud rate, and the "pointless delay()" is there from testing in frustration - But surely has no effect on the comms.
The C# code is everything, below is the complete Arduino code, with a little added, to show you the reason for the delay - I added a blinking LED out of frustration, thiking that maybe because I was talking to the Serial PINs and had the USB connected for the Serial Monitor at the same time, it could cause an Issue (I need to add here that I am a Newbie to Arduino)

Added Code mentioned to the Original (Edited) post

@Majenko The examples above work if I send from C# to Arduino through the COM3 usb port (USB on PC to USB on Arduino) but does not work when sending to the Arduino Nano through the Serial PINs from the PC's USB to Serial converter.

Ah, we may be getting somewhere now.  What USB to serial converter?

Standard cable type from PC store.. USB one side, DB9 other side (Have tried two different ones), I then wired the pins 2,3,5 (TX,RX,GND) to my breadboard.

Ah well, there you go then.  Firstly, you may have killed the Arduino's serial pins, and secondly that cable is not suitable for direct connection to a microcontroller. You need an RS-232 to TTL converter chip like a MAX232, or the right kind of cable (USB to TTL UART), like an FT232 or PL2303 cable.


text:
Storing and parsing data with Arduino
I use Ethernet Shield and Arduino to GET data from the server in JSON format. Request looks like this:
client.println("GET http://ramp.local/api/actions?");

The response I get is:
[{"action_id":1,"action_type":"up","action_status":"new","ramp_id":31,"user_id":17},
{"action_id":2,"action_type":"down","action_status":"new","ramp_id":32,"user_id":20},
{"action_id":3,"action_type":"up","action_status":"completed","ramp_id":32,"user_id":17},
{"action_id":4,"action_type":"up","action_status":"failed","ramp_id":31,"user_id":17}]

How to collect a data in a string variable and parse it to get action_status?

Ideally, you would use a proper recursive JSON parser, like the one
suggested in prakharsingh95's answer. However, if code speed and size
are critical considerations, and if the format of the response is
narrowly constrained, then you can build a fast special-purpose parser.
Here is a simple example. It assumes the response has been stored in the
response char array:
static const char key[] = "\"action_status\"";
const char *p, *q;
char action_status[16];

for (p = response; ; p = q) {
    p = strstr(p, key);    // find key
    if (!p) break;         // not found
    p = strchr(p, ':');    // find ':' between key and value
    p = strchr(p, '"');    // find opening quotes for the value
    q = strchr(p+1, '"');  // find closing quotes

    // Report finding.
    strncpy(action_status, p+1, q-p-1);
    action_status[q-p-1] = '\0';
    Serial.print("Found action status: ");
    Serial.println(action_status);
}

Of course, in production code you would check that every strchr call
returns a non-NULL pointer. And you would check that the status you
found fits in your buffer.
Edit about the pros and cons of this method:
Compared to a proper JSON parser, this approach will give you smaller
and faster code, the drawback is it being more fragile. For example,
this will not detect a corrupted JSON, and it will return garbage if the
action_status happens to be a number instead of a string, or is a
string with embedded double quotes, or if the string "action_status"
appears as a value of some other field... A full JSON parser should
correctly handle all these cases.
On a non-embedded computer, a proper JSON parser would probably be the
only appropriate answer. On a constrained microcontroller environment,
you sometimes have to make trade-offs. In this particular instance, the
“best” answer depends on how much you weight speed and size vs.
robustness against unexpected input.

I would recommend a JSON parsing library. Checkout https://github.com/bblanchon/ArduinoJson
var response = [] ; // get response here
int response_length = 4; //Put length of the response array here
StaticJsonBuffer<200> jsonBuffer;

String action_ids[] = new String[response_length];
String action_types[] = new String[response_length];
String action_statuses[] = new String[response_length];
String ramp_ids[] = new String[response_length];
String user_ids[] = new String[response_length];

for (int i=0; i < response_length ; i++) {
    JsonObject& data = jsonBuffer.parseObject(response[i]);
    // Note the '&' above

    action_ids[i] = data["action_id"];
    action_types[i] = data["action_type"];
    action_statuses[i] = data["action_status"];
    ramp_ids[i] = data["ramp_id"];
    user_ids[i] = data["user_id"];
}

Of course, you only need to extract those fields that you need.

Welcome to Arduino SE! Please do not abuse the edit functionality of our site by superfluous edits and rollbacks. To prevent misuse of the edit functionality here, I've locked this answer for a week; after this time, you will be able to edit your answer again. Thanks for your cooperation and feel free to reply with any questions.

Try this on for size.
This is an arduino based, open source, JSON processor.


text:
Can someone help me figure out why only one wheel is spinning?
I am attempting to use a code which I have posted below for two wheels. However, when connected to power, only one wheel spins. I am using a 9V battery which is what was suggested so I am not sure why only one wheel spins. When both wheels are connected, the wheel that was originally working stopped spinning.
#include <SPI.h>      //SPI library for communication with the nRF24L01+
#include "RF24.h"  //The main library of the nRF24L01+
#include "Wire.h"

RF24 radio (8, 9); // CE,CSN

//Create a pipe addresses for  communication
const uint64_t pipe = 0xE8E8F0F0E1LL;

struct package
{
  int X = 1;
  int Y = 1;
};

typedef struct package Package;
Package pos;

int buttonState;
int spinnerState = false ;
int motora_1 = 3;
int motora_2 = 4;
int motorb_1 = 5;
int motorb_2 = 6;
int spinner = 2;

void setup()
{
  Serial.begin(9600);
  radio.begin();                    //Start the nRF24 communicate
  radio.openReadingPipe(1, pipe);   //Sets the address of the transmitter to which the program will receive data.
  radio.startListening();
  pinMode(motora_1, OUTPUT);
  pinMode(motora_2, OUTPUT);
  pinMode(motorb_1, OUTPUT);
  pinMode(motorb_2, OUTPUT);
  pinMode(spinner, OUTPUT);
  digitalWrite(spinner, LOW);
  delay(100);
}

void loop()
{

  if (radio.available()) {
    radio.read(&pos, sizeof(pos));
    radio.read(&buttonState, sizeof(buttonState));
    Serial.print("X:");
    Serial.print(pos.X);
    Serial.print("      Y");
    Serial.print(pos.Y);
    Serial.print("      buttonState");
    Serial.println(buttonState);
  }

  int xAxis = pos.X;
  int yAxis = pos.Y;
  int forward = map(yAxis, 570, 1024, 0, 255);
  int backward = map(yAxis, 480, 0, 0, 255);
  int right = map(xAxis, 570, 1024, 0, 255);
  int left = map(xAxis, 480, 0, 0, 255);

  if (yAxis > 570) {          // Move Forward
    // Set Motor A forward
    analogWrite(motora_1, forward);
    analogWrite(motora_2, 0);
    // Set Motor B forward
    analogWrite(motorb_1, forward);
    analogWrite(motorb_2, 0);
  } else if (yAxis < 480) {                     //Move Backward
    // Set Motor A backward
    analogWrite(motora_1, 0);
    analogWrite(motora_2, backward);
    // Set Motor B backward
    analogWrite(motorb_1, 0);
    analogWrite(motorb_2, backward);
  } else if (xAxis > 570) {                     // Move Right
    // Set Motor A forward
    analogWrite(motora_1, right);
    analogWrite(motora_2, 0);
    // Set Motor B stop
    analogWrite(motorb_1, 0);
    analogWrite(motorb_2, 0);
  } else if (xAxis < 480) {                     // Move Left
    // Set Motor A stop
    analogWrite(motora_1, 0);
    analogWrite(motora_2, 0);
    // Set Motor B foward
    analogWrite(motorb_1, left);
    analogWrite(motorb_2, 0);
  } else  {     //stop
    // Set Motor A stop
    analogWrite(motora_1, 0);
    analogWrite(motora_2, 0);
    // Set Motor B stop
    analogWrite(motorb_1, 0);
    analogWrite(motorb_2, 0);
  }

  if (buttonState == 0 ) {
    spinnerState = ! spinnerState;
    delay(50);
  }

  if (spinnerState == true) {
    digitalWrite(spinner, HIGH);    //turn On spinner
    delay(100);
  } else {
    digitalWrite(spinner, LOW);      //turn Off spinner
    delay(100);
  }

}

With "9V battery" do you mean the standard 9V block batteries, that are often used in smoke detectors? If yes, please try to use a different power source. These batteries are made for very low power applications, not for driving motors

A connection diagram would be nice!

You have int motora_2 = 4;  and analogWrite(motora_2, backward); and an arduino-uno tag.  Pin 4 on the Arduino UNO is not a PWM capable pin.  analogWrite basically becomes digitalWrite on a 0x80 threshold when you use it with non-PWM pins.  So you have at least one problem in your sketch that can't be identified as the problem without a better description of the problem.

Firstly, the 9V batery is going to struggle with driving two motors. Change this 9V battery out with another power source.
As @timemage points out in his comment, you are using a PWM command on a non-PWM pin. For the Arduino Uno, the PWM pins are: 3, 5, 6, 9, 10, 11. Move the wiring and change the code so that it is using pin 9, 10 or 11 instead of pin 4.
It sounds like you are trying to test your hardware setup and your firmware at the same time. It is much easier to test your hardware first and make sure that works as expected before testing your firmware. I suggest writing a simpler program (the simpler the better) that just drives the motors full forward - one at a time and then together. Verify that it works and then change your test program so the motors spin in (full) reverse. Then change your test program so it changes the speed of the motors. Then with known working hardware test your firmware.

Yeah, it may be helpful for them to break the code down into more functions to make it more testable also.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Arduino millis() fuction execution problem
I am new to Arduino development. I want to use millis function instead of delay because delay is blocking further execution of program.
Program description: In this code I want to control 2 solenoid valves with DS3231 RTC alarm and also with infrared remote control button pressed.
But when I press one button for valve ON program does not turn valve on.
Please check this program and correct my mistake.
#include <DS3231.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include "IRremote.h"
#define LED1 2
int receiver = 6;
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'
#define VALVE1 7
#define VALVE2 12
DS3231  rtc(SDA, SCL);
Time  t;
//-------------millis timer----------------------------------
unsigned long last1 = millis();

void setup()
{
  irrecv.enableIRIn(); // Start the receiver
  rtc.begin();
  Serial.begin(9600);
  pinMode(VALVE1, OUTPUT);
  pinMode(VALVE2, OUTPUT);
}

void loop()
{
  t = rtc.getTime();   // Get data from the DS3231
  delay(200);
  if (irrecv.decode(&results)) // have we received an IR signal?
  {
    translateIR();
    irrecv.resume(); // receive the next value
  }

  //------ALARM FOR AUTO WATERING GARDEN----
  //MORNING Routine FOR VALVE========
  if (t.hour == 16 && t.min == 15 && t.sec == 00)  //Open valve1 8AM morning
  {
    void G_valve1On();
  }

  if (t.hour == 16 && t.min == 20 && t.sec == 00)  //close valve1 8:10AM morning
  {
    void G_valve1Off();
  }

  //---------FUNCTIONS-----------------------------
  //IR COMMAND FUNCTIONS
  void translateIR()
  {
    switch (results.value)
    {
      case 0x843509F6:         //valve 1 turn on for 10minute delay
        if (millis() - last1 > 600000) //when remote button pressed valve turn on for 10min
        { G_valve1On();
          Serial.println("valve ON");
        }
        G_valve1Off();
        Serial.println("valve off");
        delay(250);
        break;
      case 0x84350AF5:                 //2nd button for 15 min delay
        G_valve2On();

        //Serial.println("valve on 15minutes...");
        //Help me to use MILLS FUNCTION.

        G_valve2Off();
        //Serial.println("valve off");
        delay(250);
        break;
    }
    delay(300);
  }
}

  //----VALVES- FUNCTION------

  void G_valve1On()
  {
    digitalWrite(VALVE1, HIGH);
    Serial.println("...turning valve1 on...");
  }
  void G_valve1Off()
  {
    digitalWrite(VALVE1, LOW);
    Serial.println("...turningvalve1 off...");
  }
  void G_valve2On()
  {
    digitalWrite(VALVE2, HIGH);
    Serial.println("...turning valve1 on...");
  }
  void G_valve2Off()
  {
    digitalWrite(VALVE2, LOW);
    Serial.println("...turningvalve1 off...");
  }

UPDATE:
Thanks for the replies. I have made some changes in the program that user ratchet freak provided below, but it is giving error.
Program:
#include <DS3231.h>
#include <boarddefs.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <ir_Lego_PF_BitStreamEncoder.h>
#include "IRremote.h"
#define LED1 2
int receiver = 6;
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'
#define valve1 13
#define valve2 12
DS3231  rtc(SDA, SCL);
Time  t;

struct valve_state {
  bool on;
  unsigned long on_timestamp;
  unsigned long on_time;
}
valve_state valve1;
valve_state valve2;
void setup()
{
  irrecv.enableIRIn(); // Start the receiver
  rtc.begin();
  Serial.begin(9600);
  pinMode(valve2, OUTPUT);
  pinMode(valve1, OUTPUT);
}

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

  //read ir
  //read rtc
  if (irrecv.decode(&results))
  {
    if (ir.value == 0x843509F6 ||                              //VALVE 1ON OFF
        (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)) {
      valve1.on = true;
      valve1.on_timestamp = millis();

      valve1.on_time = 10 * 60 * 1000;
    }
    if (valve1.on && (millis() - valve1.on_timestamp > valve1.on_time)) {
      valve1.on = false;
      digitalWrite(valve1, LOW);

      if (ir.value == 0x843509F6 ||                                      //VALVE 2 ON OFF
          (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)) {
        valve2.on = true;
        valve2.on_timestamp = millis();
        digitalWrite(valve2, HIGH);
        valve1.on_time = 10 * 20 * 1000;
      }
      if (valve2.on && (millis() - valve2.on_timestamp > valve2.on_time)) {
        valve1.on = false;
        digitalWrite(valve2, LOW);

      }

But the Arduino IDE gives following errors:
:\Users\ABHI's\AppData\Local\Temp\arduino_2447f9e2b3111c537660c536aa9c2330\sketch_nov11a.ino:23:13: note: in expansion of macro 'valve1'

 valve_state valve1;

             ^

sketch_nov11a:12: error: expected unqualified-id before numeric constant

 #define valve2 12

                ^

C:\Users\ABHI's\AppData\Local\Temp\arduino_2447f9e2b3111c537660c536aa9c2330\sketch_nov11a.ino:24:13: note: in expansion of macro 'valve2'

 valve_state valve2;

             ^

C:\Users\ABHI's\AppData\Local\Temp\arduino_2447f9e2b3111c537660c536aa9c2330\sketch_nov11a.ino: In function 'void loop()':

sketch_nov11a:43: error: 'ir' was not declared in this scope

     if(ir.value == 0x843509F6 ||
sketch_nov11a:44: error: 'class DS3231' has no member named 'hour'

    (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)){

sketch_nov11a:44: error: 'class DS3231' has no member named 'min'

        (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)){
                            ^
sketch_nov11a:44: error: 'class DS3231' has no member named 'sec'

        (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)){

sketch_nov11a:45: error: request for member 'on' in '13', which is of non-class type 'int'

         valve1.on = true;

sketch_nov11a:46: error: request for member 'on_timestamp' in '13', which is of non-class type 'int'

         valve1.on_timestamp = millis();                ^

sketch_nov11a:55: error: request for member 'on_time' in '13', which is of non-class type 'int'

         valve1.on_time = 10*60*1000;

sketch_nov11a:57: error: request for member 'on' in '13', which is of non-class type 'int'

     if(valve1.on && (millis() - valve1.on_timestamp > valve1.on_time)){

sketch_nov11a:57: error: request for member 'on_timestamp' in '13', which is of non-class type 'int'
     if(valve1.on && (millis() - valve1.on_timestamp > valve1.on_time)){

sketch_nov11a:57: error: request for member 'on_time' in '13', which is of non-class type 'int'

     if(valve1.on && (millis() - valve1.on_timestamp > valve1.on_time)){                                                              ^

sketch_nov11a:58: error: request for member 'on' in '13', which is of non-class type 'int'

         valve1.on = false;                ^

sketch_nov11a:69: error: 'ir' was not declared in this scope

      if(ir.value == 0x843509F6 ||          ^

sketch_nov11a:70: error: 'class DS3231' has no member named 'hour'

        (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)){             ^

sketch_nov11a:70: error: 'class DS3231' has no member named 'min'

        (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)){                              ^
sketch_nov11a:70: error: 'class DS3231' has no member named 'sec'

        (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)){                                                ^

sketch_nov11a:71: error: request for member 'on' in '12', which is of non-class type 'int'
         valve2.on = true;                ^

sketch_nov11a:72: error: request for member 'on_timestamp' in '12', which is of non-class type 'int'

         valve2.on_timestamp = millis();

                ^

sketch_nov11a:81: error: request for member 'on_time' in '13', which is of non-class type 'int'

         valve1.on_time = 10*20*1000;                ^

sketch_nov11a:83: error: request for member 'on' in '12', which is of non-class type 'int'

     if(valve2.on && (millis() - valve2.on_timestamp > valve2.on_time)){
               ^

sketch_nov11a:83: error: request for member 'on_timestamp' in '12', which is of non-class type 'int'

     if(valve2.on && (millis() - valve2.on_timestamp > valve2.on_time)){                                        ^

sketch_nov11a:83: error: request for member 'on_time' in '12', which is of non-class type 'int'

     if(valve2.on && (millis() - valve2.on_timestamp > valve2.on_time)){                                                            ^

sketch_nov11a:84: error: request for member 'on' in '13', which is of non-class type 'int'

         valve1.on = false;                ^

sketch_nov11a:97: error: expected '}' at end of input
 }

exit status 1
expected initializer before numeric constant

Can you please reconstruct complete program for me?

loop is not closed with }

you have a condition which enables turning on the valve after 10 minutes from program start. and the on the next line you turn it off

correct my mistake. which is?

The best way to handle this kind of thing is by state machine. Each valve is its own state machine and is handled one at a time.
The state machine for the valve seems to be trigger valve on based on RTC or remote. Turn off when timeout triggers
So you handle each event based on the current state:
struct valve_state{
    bool on;
    unsigned long on_timestamp;
    unsigned long on_time;
}

valve_state valve1;
valve_state valve2;

void loop(){

    //read ir
    //read rtc

    if(ir.value == 0x843509F6 ||
       (rtc.hour == 16 && rtc.min == 15 && rtc.sec == 00)){
        valve1.on = true;
        valve1.on_timestamp = millis();
        digitalWrite(VALVE1,HIGH);
        valve1.on_time = 10*60*1000;
    }
    if(valve1.on && (millis() - valve1.on_timestamp > valve1.on_time)){
        valve1.on = false;
        digitalWrite(VALVE1,LOW);
    }

    //repeat for valve2
}

The code you posted doesn't compile. I fixed the missing brace and used the auto-format command of the IDE to fix the mess in indentation.
I then inserted the necessary code for the two buttons.
#include <DS3231.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include "IRremote.h"
#define LED1 2
int receiver = 6;
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'
#define VALVE1 7
#define VALVE2 12
DS3231  rtc(SDA, SCL);
Time  t;
//-------------millis timer----------------------------------
unsigned long last1 = 0;
unsigned long last2 = 0;
void setup()
{
  irrecv.enableIRIn(); // Start the receiver
  rtc.begin();
  Serial.begin(9600);
  pinMode(VALVE1, OUTPUT);
  pinMode(VALVE2, OUTPUT);
}

void loop()
{
  t = rtc.getTime();   // Get data from the DS3231
  if (irrecv.decode(&results)) // have we received an IR signal?
  {
    translateIR();
    irrecv.resume(); // receive the next value
  }

  // turn of valves if they are on for enough time
  if (last1 && millis() - last1 > 600000)
  {
    G_valve1Off();
    Serial.println("valve off");
    last1 = 0;
  }
  if (last2 && millis() - last2 > 900000)
  {
    G_valve2Off();
    last2 = 0;
  }

  //------ALARM FOR AUTO WATERING GARDEN----
  //MORNING Routine FOR VALVE========
  if (t.hour == 16 && t.min == 15 && t.sec == 00)  //Open valve1 8AM morning
  {
    void G_valve1On();
  }

  if (t.hour == 16 && t.min == 20 && t.sec == 00)  //close valve1 8:10AM morning
  {
    void G_valve1Off();
  }
}

//---------FUNCTIONS-----------------------------
//IR COMMAND FUNCTIONS
void translateIR()
{
  switch (results.value)
  {
    case 0x843509F6:         //valve 1 turn on for 10minute delay

      G_valve1On();
      Serial.println("valve ON");
      last1 = millis();
      break;

    case 0x84350AF5:                 //2nd button for 15 min delay
      G_valve2On();
      last2 = millis();
      break;
  }
  delay(300);
}

//----VALVES- FUNCTION------

void G_valve1On()
{
  digitalWrite(VALVE1, HIGH);
  Serial.println("...turning valve1 on...");
}
void G_valve1Off()
{
  digitalWrite(VALVE1, LOW);
  Serial.println("...turningvalve1 off...");
}
void G_valve2On()
{
  digitalWrite(VALVE2, HIGH);
  Serial.println("...turning valve1 on...");
}
void G_valve2Off()
{
  digitalWrite(VALVE2, LOW);
  Serial.println("...turningvalve1 off...");
}


text:
ino.hex vs ino.with_bootloader.hex
I'm working on a Android App able to update the content of my Arduinos. Start to work (reset the Arduino, communicate with STK500 protocol, get id of ATmega and so on).
But I face a question about the two hex files produced by the compiler.
Some FAQ, forum... give replies about the two, explaining: "the ino.hex file has only the code and the other as the code + the code of the bootloader".
After having a look at the hex files, that's true: you can find in the "with_bootloader" the code of the bootloader.
The "why" gives the following answer: "that's because when the bootloader receive the code, it erases the flash so the installed bootloader destroy itself. So if you send without bootloader, you will not have a bootloader any more in the Arduino".
Problems:
1) In that case, in order to change the bootloader why use an ISP? Just add the HEX code of your new bootloader in the main HEX file, send it with AVRDUDE and that's all...
2) When you use the Arduino IDE with AVRDUDE in Verbose mode you'll see AVRDUDE send the file....
without the bootloader!
So the question is: when you want to update the content of the flash, sending "manually" the data using STK500 protocol, do you need to send the "ino.hex" or the "ino.with_bootloader.hex" file? And why?

If flashing with AVR In System Programing (ISP) the bootloader is not needed. Only the flashing over Serial needs a bootloader.
The ISP erases the flash including the bootloader. To be able to use the serial flashing after ISP, the hex with_bootloader can be used.
I flash AVR over WiFi with esp8266's core AVRISP library and I use the hex with_bootloader to have the option of flashing later over USB.
Your Android app will use the serial flashing utilizing the bootloader. The bootloader doesn't delete itself. So you should use the hex WITHOUT bootloader.

Nice answer, coming from one who use and not only copy answer from others. Thanks VERY MUCH!

While flashing the Arduino over USB (UART) you use the bootloader in that case the bootloader doesn't delete itself that's why the Arduino IDE sends the file without the bootloader. You need to use the file with a bootloader only when you are programming using an ISCP programmer and want to keep the ability to flash through USB.


text:
Single & multi sensor code
I have been having problems trying to run multi sensor code for my project, this requires four KY-024 Linear magnetic Hall sensors as position sensors that trigger NC independent relays to make a circuit.
I can get the code to run on one independent circuit, one hall switch one relay with no problems.
But when I try the code for 4 hall sensors + relays I get no response from the circuit at this point I am at a loss where to go from here the code compiled with no problems.
int hallswitch = 1;
int val = 0;
int RELAY1 = 6;

void setup() {
  pinMode(hallswitch, INPUT);
  pinMode(RELAY1, OUTPUT);
}

void loop() {
  val = digitalRead(hallswitch);

  if (val == HIGH) {
    digitalWrite(RELAY1, HIGH);
  }
  else {
    digitalWrite(RELAY1, LOW);
  }
}

and
int hallswitch1 = 1;  //Pin for Hall switch
int hallswitch2 = 2;  //Pin for Hall switch
int hallswitch3 = 4;  //Pin for Hall switch
int hallswitch4 = 5;  //Pin for Hall switch

int val = 0;       //Integer for reading Hall statu

int RELAY1 = 6;    // The socket number on the Arduino that the relay1 will go to.
int RELAY2 = 7;    // The socket number on the Arduino that the relay1 will go to.
int RELAY3 = 8;    // The socket number on the Arduino that the relay1 will go to.
int RELAY4 = 9;    // The socket number on the Arduino that the relay1 will go to.

void setup()
{
  pinMode(hallswitch1, INPUT);
  pinMode (RELAY1, OUTPUT);

  pinMode(hallswitch2, INPUT);
  pinMode (RELAY2, OUTPUT);

  pinMode(hallswitch3, INPUT);
  pinMode (RELAY3, OUTPUT);

  pinMode(hallswitch4, INPUT);
  pinMode (RELAY4, OUTPUT);
}

void loop() {
  val = digitalRead(hallswitch1);               //Read Hall pin status
  val = digitalRead(hallswitch2);               //Read Hall pin status
  val = digitalRead(hallswitch3);               //Read Hall pin status
  val = digitalRead(hallswitch4);               //Read Hall pin status

  if (val == HIGH) {                        //If there is a magnet infront of Hall switch...
    digitalWrite(RELAY1, HIGH);             // Turn RELAY1 on:
    digitalWrite(RELAY2, HIGH);
    digitalWrite(RELAY3, HIGH);
    digitalWrite(RELAY4, HIGH);
  }
  else {
    digitalWrite(RELAY1, LOW);               // Turn RELAY1 off:
    digitalWrite(RELAY2, LOW);
    digitalWrite(RELAY3, LOW);
    digitalWrite(RELAY4, LOW);
  }
}

You are writing all four sensors to the save variable 'val'    Although that will not stop the code from running, but it means the only one you are actually doing anything with is hallswitch4, and you using that value to turn on or off all of the relays,

What do you mean 'get no response'? If you are only trying switches 1,2, or 3 you will not get any response as their values are being over written.

how could i get the code to run 4 hall sensors independently ?

This is the quick and dirty way, I would suggest re writing it to use arrays rather then having to declare all these variables and copy paste pinMode, read,writes if statments a bunch of times.
 int hallswitch1 = 1;  //Pin for Hall switch
 int hallswitch2 = 2;  //Pin for Hall switch
 int hallswitch3 = 4;  //Pin for Hall switch
 int hallswitch4 = 5;  //Pin for Hall switch

 int val1 = 0;       //Integer for reading Hall statu
 int val2 = 0;
 int val3 = 0;
 int val4 = 0;

 int RELAY1 = 6;    // The socket number on the Arduino that the relay1 will go to.
 int RELAY2 = 7;    // The socket number on the Arduino that the relay1 will go to.
 int RELAY3 = 8;    // The socket number on the Arduino that the relay1 will go to.
 int RELAY4 = 9;    // The socket number on the Arduino that the relay1 will go to.

void setup()
{

  pinMode(hallswitch1, INPUT);
  pinMode (RELAY1, OUTPUT);

  pinMode(hallswitch2, INPUT);
  pinMode (RELAY2, OUTPUT);

  pinMode(hallswitch3, INPUT);
  pinMode (RELAY3, OUTPUT);

  pinMode(hallswitch4, INPUT);
  pinMode (RELAY4, OUTPUT);

}

void loop() {

  val1 = digitalRead(hallswitch1);               //Read Hall pin status
  val2 = digitalRead(hallswitch2);               //Read Hall pin status
  val3 = digitalRead(hallswitch3);               //Read Hall pin status
  val4 = digitalRead(hallswitch4);               //Read Hall pin status

  if (val1 == HIGH) {digitalWrite(RELAY1, HIGH);}
  else {digitalWrite(RELAY1, LOW);}

  if (val2 == HIGH) {digitalWrite(RELAY2, HIGH);}
  else {digitalWrite(RELAY2, LOW);}

  if (val3 == HIGH) {digitalWrite(RELAY3, HIGH);}
  else {digitalWrite(RELAY3, LOW);}

  if (val4 == HIGH) {digitalWrite(RELAY4, HIGH);}
  else {digitalWrite(RELAY4, LOW);}

}

also all of the 'pin' variables RELAYx and hallswitchx dont need to be variables since you are not changing them, they are constants.   use #define RELAY1 6     ect

Chad thank you for your help the code works as intended


text:
Digispark ATtiny85 not recognized (bootloader problem)
I recently bought an ATtiny85 based development board. (picture below)

I managed to install it correctly following the official guides, without a problem.
Drivers are installed correctly, and I used the Arduino IDE to actually upload a few sketches and tested them in two computers.
SUDDENLY
It has stopped working, based on my research, it seems that the bootloader got damaged. Any idea on how to fix this? I thought about burning the bootloader using Arduino, but I have barely got an idea on how to begin.
Backside of the Attiny85

You'd need a high voltage programmer to change the bootloader on the digispark. I've used a separate Arduino with a high voltage programmer sketch, a transistor and a stack of three coincells (for the high voltage), to change the fuses, to enable the reset pin. But it's not a very beginner friendly process. I'd cut my losses and get a new board.

That sounds like a wonderful beginner project! In any case, if I buy a new one, this will probably happen again, so it is time to start getting into it right away.
Do you have any resources on how to start doing this? I'm getting an Arduino Uno this week @Gerben

I like your enthusiasm. I'm not sure what code I used, but https://github.com/ArminJo/ATtiny-HighVoltageProgrammer_FuseEraser seems like it will do what you want. It will reset the fuses of the ATTiny85 to the default values, re-enabling ISP on the ATTiny. It uses a boost converter to generate the 12V, but you could also stack 3 coincells and hold two jumperwires to each end (like I did). After that you can program the bootloader using the Arduino-as-ISP method.

Wonderful @Gerben. I'll look at it and try it within a few days when my Arduino gets delivered. Thanks for the help (I'll let you know how it turns out).

The 3 default ways to re-program your tiny on that board are:

micronucleus bootloader (sketches only)
ISP prog. (sketches & set-fuses, InSystemProgramming)
HV prog. (re-set fuses, HighVoltage = 12V don't worry)

The bootloader in itself is like a sketch on the chip (at the beginning, taking up flash space) and talks through the software USB port on that board. It then rewrites parts of its own flash from the data the host sends, when you upload new sketches.
If that part gets damaged it won't get recognized by the host anymore and you can't use the board to reprogram itself. Unless the chip/parts died to ESD or other reasons, you still can use ISP/HV programming on the chip, which is the solution to your problem.
Read up on fuses, they are the init settings of your chip (like a BIOS) defining its behaviour. There are some fuses which can only be set once, after which they can only be changed by the HV method. Depending their setting on your chip, this could also be done with normal ISP programming.
This instructables shows how to build a HV programmer, but also demonstrates using an Arduino as normal ISP programmer (Step 4).
The original Digispark comes with the RSTDISBL fuse set, meaning you can't directly use ISP (which requires the reset pin). Thats why HV programming is neccessary, to regain the reset pin, after that you can reflash the bootloader via ISP. From then on you can use the bootloader again, to reprogram (upload) your sketches.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Using the LED pin for input
I have an Arduino-like device with few GPIO pins (DigiSpark clone). It is based on an 8-pin AtTiny85 IC so there are Power, Ground and six other pins, two of those six are being used for USB keyboard simulation which leaves 4 GPIO which I want to connect 4 buttons to with minimal circuitry. The normal way to do this is to enable the internal pullups and have the buttons connect the pin to ground. This works well for most pins.
The problem is the equivalent to Pin 13 (Pin 1 in this case) which is connected via a resistor and LED to ground. The internal pullup is too weak to raise the voltage enough. Consequently that pin always appears to be in a "button pressed" state.
One solution is to cut the tracks connecting the LED, but the board is so tiny and crowded that I doubt I have the eyesight and steadiness of hand to do this.

Problematic resistor + LED are at bottom right of AtTiny85 IC
It occurs to me I could either

Add an external pullup to this input,
Change the button wiring so when pressed, it connects the pin to 5v. Change the code to look for high, not low.

Are there any problems with either of these approaches?

You have forgotten the reset pin. So effectively you only have 3 pins left (8 pins minus Vcc, ground, reset and 2 pins for USB = 3)

@chrisl - I plan to disable the reset fuse using avrdude. I don't have a high voltage  programmer but I don't need to use ICSP or change the bootloader so should be OK. I was considering adding Pin 5 issues as a separate question if I hit problems.

P.S. Fixing P5 on DigiSpark clones

How do you plan to program the digispark, if you cannot reset the chip? The bootloader, which does programming over Serial is only activated, when the chip is reset.

@chrisl - by unplugging from USB, clicking the IDE's upload button and then waiting for the IDE's prompt ("Plug in device now... (will timeout in 60 seconds)") then plugging the DigiSpark back in. This is the normal method for reprogramming a DigisSpark. So far as I know this enables you to reprogram the Digispark without pulling RESET low. Presumably the "micronucleus" bootloader becomes active after initial power-on, waits for USB activity from the IDE (uploader/avrdude) for n seconds and only then jumps to the existing user code ("sketch").

For me it's option 2. I would not expect any problem.

I'd remove the LED. Takes but a moment with a soldering iron.

In the end, stimulated by Majenko's advice to desolder the LED,  I instead carefully studied the PCB layout online, checked that it corresponded to my PCB, checked the location of nearby traces I didn't want to cut and then used multiple magnifying glasses and a fresh blade in my smallest utility knife and carefully cut the track leading from the LED to the IC. All was well.


text:
Check pin capabilities at compile time
Are there board-independent functions to check pin capabilities at compile time? I.e.

Can the pin be used as output, as in digitalWrite()?
Does the pin support PWM, as in analogWrite()?
Does the pin support ADC, as in analogRead()?
Does the pin support interrupts, as in attachInterrupt()?

I'm looking for functions/macros like e.g. isDigitalOutput(pin) which would return false for input-only pins such as A6 and A7 on a 328P, but true on a Mega where those pins are input/output.

I'm afraid not, Its best to look up documentation or schematics for the board, if you would like to do it by yourself, you can set any pin to any of the states and test whether it works properly, and take some notes

@Coder9390 I wanted to do a check in a library function which requires an analog pin, but I think I'll just drop the idea. No way I'm going to look up every analog pin on every possible board.

maybe a check for a definition of A0 would work

Firmata contains a large list of pin definitions for boards. The official version https://github.com/firmata/ConfigurableFirmata/blob/master/src/utility/Boards.h is a bit outdated, but the most common Arduinos are included

https://github.com/arduino/ArduinoCore-avr/blob/9f8d27f09f3bbd1da1374b5549a82bda55d45d44/variants/mega/pins_arduino.h#L27

For compatibility with analogWrite() there's digitalPinHasPWM(p) macro which returns 1 when PWM is supported on pin p.
For analogRead() there's analogInputToDigitalPin() which can be used as
#if ((p-PIN_A0 < 0) || (analogInputToDigitalPin(p-PIN_A0) != p))
#error Not an analog pin!
#endif

For attachInterrupt() there is digitalPinToInterrupt(p) which returns NOT_AN_INTERRUPT if the pin p doesn't support interrupts.
I still haven't found anything to test compatibility with digitalWrite().

you asked about compile time

@Juraj Right, A0 is not a macro (PIN_A0 must be used instead).

but the answer is about runtime

@Juraj No, all of the above checks are macros.

sorry, I see. after edit it is a macro


text:
Is there a working combination of Arduino IDE + Ardublock?
I'm trying to set up Ardublock, but the last release they have is from 2014 and in a recent Arduino IDE it fails when I try to upload the program to the Arduino board:
Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError: processing.app.Editor.setText(Ljava/lang/String;)V
    at com.ardublock.ArduBlockTool.didGenerate(ArduBlockTool.java:72)
   ....

I assume there is a different API in the recent Arduio IDE for copying the generated code into the editor. This is the block diagram I'm trying to upload. As you can see there are no libraries involved:

Is there a known combination of Arduino IDE and Ardublock which works? Or perhaps an addon similar to Ardublock which is maintained?

tinkercad has an online block editor in their circuits feature (drag out an uno to get to the editor).

@dandavis Looks pretty nice, too bad they don't seem to have support for subroutines. I struggle to find examples of programming environments with such a severe limitation, brainfuck interpreter and my first programmable calculator come to mind.

I found that Ardublock project was forked on Github, and the latest release indeed works with up-to-date Arduino IDE.


text:
Set SPI MOSI pin to idle low on a Due?
I have an SPI slave connected to Due. I send the SPI slave into sleep mode. During sleep, I need to pull all pins low, including MOSI. What's the best way to pull the SPI-4 pin low on a Due?
Here's a similar question but it's about an AVR chip and the answer obviously doesn't apply to SAM3X8 which is an ARM.

Is it the only slave that is connected to the Due?

@SimSon Yes it's the only one.

Then you could disable the SPI and set the MISO pin as output low

Disable SPI, disable peripheral clock for SPI, change back corresponding pins from alternate functions to normal pin functions and set proper outputs. But you should also disable power for the slave. Otherwise low on its chip select pin means it'll be active

@KIIV Is SPI-4 available as a digital IO pin? Which one?

@DmitryGrigoryev There are just two SPI's and another four USARTs with SPI mode. However it doesn't matter, pins are fixed and so alternate functions for that pins. You have to use datasheet for the MCU to figure it all out.

@KIIV I'm talking about the SPI-4 pin available on the Duo

@DmitryGrigoryev https://www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf -> SPI header pin 4 is PA26. So, you have to take a look into datasheet and figure out, how to set/reset it's alternate function

I have managed to set MOSI to low by setting bit 26 in PIOA->PIO_PER, PIOA->PIO_OER and  PIOA->PIO_CODR registers. To use SPI again, bit 26 in PIOA->PIO_PDR has to be set (this cancels the effect of PIOA->PIO_PER).


text:
How fast an Arduino mouse would be?
I'm thinking about making a custom Arduino-based mouse and I expect not to be the first one to have the idea. Does anybody know what speed I can expect to achieve? Suppose I use a mechanical mouse as a base, meaning I'll have to monitor 3 buttons and 3 axes (X, Y and wheel), debounce the signals coming from the buttons and transmit all that data via USB. How many times per second will I be able to do this, theoretically? Are there any projects which did something similar, and if so, what speed were they able to achieve?
To make a good mouse, I suppose I should at least beat my display's refresh rate which is 60 Hz, otherwise pointer movement won't be smooth. My current (commercially produced) mouse runs at 100 Hz.

I suppose that 1000 times per second could be possible, but I don't know if that is somewhere slowed down, for example in the driver on the computer. The pro micro board uses a usb interface which is very fast. Please add to your question why you ask this. You know someone who presses a button 1000 times per second? or is the button only shortly pressed and you don't want to miss it?

Thanks for updating your question. 100 Hz is no problem, and there is still time to debounce the buttons. What kind of mechanical mouse? With rotary encoders? With two interrupts per encoder and 3 axis you need 6 interrupts. The pro micro has 4 normal interrupts and 6 pcint interrupts. Pinmapping: http://www.pighixxx.com/test/portfolio-items/pro-micro/


text:
Power Supply Problem with Arduino Yún: Using a long USB cable
I want to use an Arduino Yún as a kind of outdoor weather station. I want to supply the power for the Yún with a 5V USB-Charger. Using a normal USB cable everything works fine. But as the weather station shall be far from the next power socket, I made the USB cable about 10 meters longer. Now the Yún does not power up any more.
Has anybody an idea why?
Should I use a 12 V power supply and a 7805 power converter instead?

Dmitry's answer is generally correct but I disagree with the notion that “voltage drop” is the problem, unless you used extremely thin wire in the extension.   You don't say how you made the USB cable longer.  If your experience with building cables is limited, it's more likely that one or more of the connections is open or wrong than that too much voltage drop is occurring.

After failing with a rather thin cable (a former telephone cable soldered into a normal USB cable) I tried a much thicker cable, but the Yun would not start either. As I think I am rather experienced with soldering, I do not think the connections are the problem.
Does it make sense to measure the resistance of the cable?
So I will try the power converter solution within the next days.

The USB specification limits the length of a cable between two devices to 5 meters. When you make a longer cable, you're going out of spec, which means it is not guaranteed to work anymore.
Since you're only supplying power, the issue is (as you have guessed) the voltage drop in the cable. However, the voltage drop will depend on how much current Arduino is consuming at any given moment. Supplying it with a higher voltage without a converter is dangerous, because it will lead to overvoltage you won't be able to control.
I'd suggest trying better cables first: thicker and stiffer cables have thicker wires, and may have less voltage drop. You can also make your own cable (provided you can solder) using only two thick wires for power.
The ultimate solution, like you said yourself, is to deliver higher voltage over the wire (12V would do) and install a power converted (12V to 5V) near your Arduino. That way, the voltage drop in 5V line will be small, and the voltage drop in 10m 12V line will be compensated by the converter. Actually, the intermediate voltage may be higher: you can simply drop a mains line (220V or whatever you have) to your weather station and place the same USB charger near the Arduino.

It works now. I replaced a 12 V power supply and added a 12V / 5V DC converter just before the Arduino Yun.  The first try with a change of the cables with a higher diameter had no effect.

@bhneuner I'm glad it worked out, and thanks for taking time to report back!


text:
Arduino Uno + Ethernet shield stability question
i have a climate control software which reports data back through the web browser.  Everything seems to be working however I am running into an issue where
1 - after a bit it seems the page doesnt refresh completely and instead displays a long list of the same webpage, so i have like 30 pages of the same thing as you scroll down
2 - when i woke up in the morning i could not load the page at all
What i am wondering is how can i get this to be stable and reliable so that the climate control software / sensors can run non-stop.
Currently as long as i dont use the ethernet shield reporting everything else seems to work great, i leave it on for 12 -20 hours and it still runs, but not with the ethernet reporting.
any help wold be apreciated thanks.
this is my code:
//Define Start
#define NOTE_D2  73 //sound note for beep
#define DHTPIN 2
#define DHTTYPE DHT22
#define DHT2PIN 3
#define DHTTYPE2 DHT22
#define MAGENTA //Define a color for screen
#define sclk 8 //screen pin
#define mosi 5 //screen pin
#define cs   6 //screen pin
#define dc   7 //screen pin
#define rst  rstpin  // you can also connect this to the Arduino reset
#define ANALOG_IN 0 // for cds light sensor

//Define End
//Include start
#include <DHT.h>//dht sensor library
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>//needed to run screen
#include <Wire.h>
#include "RTClib.h"
#include <Ethernet.h>
//Include end
//declare start
DHT dht2(DHT2PIN, DHTTYPE2);
DHT dht(DHTPIN, DHTTYPE);
int powerswitch1 = A0;
int powerswitch2 = A1;
const int ledPin =  A2;
const int ledPin2 =  A3;
Adafruit_ST7735 tft = Adafruit_ST7735(cs, dc, mosi, sclk);
char* myString = { "OFF" };//relay1 on / off status
char* myString2 = { "OFF" };//relay2 on / off status
const int chipSelect = 4;
RTC_DS1307 RTC;
byte mac[] = {
  0x90, 0xA2, 0xDA, 0x00, 0x23, 0x36 }; //MAC address found on the back of your ethernet shield.
IPAddress ip(192,168,1,40);
//decalare end
EthernetServer server(80);

void setup() {
pinMode(ledPin, OUTPUT);
pinMode(ledPin2, OUTPUT);
tft.initR(INITR_BLACKTAB);   // initialize a ST7735S chip, black tab
tft.fillScreen(ST7735_RED);//make screen red
  pinMode(powerswitch1, OUTPUT);
  pinMode(powerswitch2, OUTPUT);
  Serial.begin(9600);
  Wire.begin();
  RTC.begin();
if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
 //   RTC.adjust(DateTime(__DATE__, __TIME__));
  }

// get time to display "sensor up time"
  uint16_t time = millis();
 // tft.fillScreen(ST7735_BLACK); //black screen
  time = millis() - time;

Serial.println(time, DEC);

  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}
void loop(){
  //Tone Start
    tone(9, NOTE_D2);
    delay(65);
    noTone(9);
//Tone End

//clock start
  DateTime now = RTC.now();

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

 //hour conversion to 12 hour start
   int x;
   int timeresult;
   x = (now.hour());
   if (x > 12) {
   timeresult = x - 12;
   }
   else
   {
    timeresult = x;
   }
   Serial.println(timeresult);
    //hour conversion to 24 hour start
//clock end
//sensor 1 start
    //Serial.println("read DHT22 #1");
    float h = dht.readHumidity();
    float t = dht.readTemperature();
    float f = dht.readTemperature(true);
    //sensor 1 end
    //sensor 2 start
    //Serial.println("read DHT22 #2");
    float h2 = dht2.readHumidity();
    float t2 = dht2.readTemperature();
    float f2 = dht2.readTemperature(true);
    //sensor 2 end
    //temp average begin
    //Serial.println("average calculation");
    float havg = (h + h2) / 2;
    float favg = (f + f2) / 2;
    float tavg = (t + t2) / 2;
    //temp average end

//Relay 1 Start
    if (h < 42) //top threshold
    {
        if (h < 39) //bottom threshhold
        {
            digitalWrite(powerswitch1, HIGH);
            // Turn the Powertail on
            Serial.println("Switch ON");
digitalWrite(ledPin, HIGH);
            myString = "ON";
        }

    }
    else
    {
                myString = "OFF";
        digitalWrite(powerswitch1, LOW);    // turn the Powertail off
digitalWrite(ledPin, LOW);
        Serial.println("Switch OFF");

    }
//Relay 1 End
//Relay 2 Start
    if (f < 60) //top threshold
    {
        if (h < 60) //bottom threshhold
        {
            digitalWrite(powerswitch2, HIGH);
            // Turn the Powertail on
            Serial.println("Switch ON");
digitalWrite(ledPin2, HIGH);
            myString2 = "ON";
        }

    }
    else
    {
                myString2 = "OFF";
        digitalWrite(powerswitch2, LOW);    // turn the Powertail off
digitalWrite(ledPin2, LOW);
        Serial.println("Switch OFF");

    }
//Relay 2 End
//Screen start

delay(500);

tft.fillRect(20,19,80,140, ST7735_RED);//clear text
//(left wall,top wall px from top,right wall,bottom wall px from top)
tft.drawRect(20,19,80,140, ST7735_RED);//cleartext
//active text
tft.setCursor(35, 20);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(f);
tft.setCursor(35, 40);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(t);
tft.setCursor(35, 60);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(h);
tft.setCursor(25, 120);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(timeresult);
tft.setCursor(50, 120);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(now.minute(), DEC);
tft.setCursor(75, 120);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(now.second(), DEC);

//static text

tft.setCursor(105, 20);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println("F");
tft.setCursor(105, 40);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println("C");
tft.setCursor(105, 60);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println("%");
tft.setCursor(52, 80);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(myString);
tft.setCursor(105, 80);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println("H");
tft.setCursor(52, 100);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(myString2);
tft.setCursor(105, 100);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println("T");
tft.setCursor(52, 140);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println(millis() / 1000);
tft.setCursor(105, 140);
tft.setTextSize(2);
tft.setTextColor(ST7735_WHITE);
tft.println("-");

tft.print(millis() / 1000);
//Screen end

 EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
   client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("");
          client.println("");
          /////CSS
            client.println("");
          ///CSS

          client.println("
");
          client.println(""); //how to change color adruino version

            client.println("
");
            client.println("<text4>");
            client.print("Sensor 1");
            client.println("</text4>");
            client.println("
");
            client.println("<text1>");
            client.print(h);
            client.print(" %\t");
            client.println("</text1>");
            client.println("
");
            client.println("<text2>");
            client.print(f);
            client.println(" °");
            client.println("F");
            client.println("</text2>");
            client.println("
");
            client.println("<text2>");
            client.print(t);
            client.println(" °");
            client.println("C");
            client.println("</text2>");
            client.println("
");
            client.println("
");
            client.println("
");
            client.println("<text4>");
            client.print("Sensor 2");
            client.println("</text4>");
            client.println("
");
            client.println("<text1>");
            client.print(h2);
            client.print(" %\t");
            client.println("</text1>");
            client.println("
");
            client.println("<text2>");
            client.print(f2);
            client.println(" °");
            client.println("F");
            client.println("</text2>");
            client.println("
");
            client.println("<text2>");
            client.print(t);
            client.println(" °");
            client.println("C");
            client.println("</text2>");
            client.println("
");
            client.println("
");
            client.println("
");
            client.println("<text5>");
            client.print("Humidifier: ");
            client.println("</text5>");
            client.println("<humidifier>");
            client.print(myString);
            client.println("</humidifier>");
            client.println("<text5>");
            client.print("Heater: ");
            client.println("</text5>");
            client.println("<heater>");
            client.print(myString2);
            client.println("</heater>");
            client.println("<text6>");
            client.println("
");
            client.print(millis() / 1000);
            client.println("</text6>");
            client.println("<text6>");
            client.print(timeresult);
            client.print(":");
            client.print(now.minute(), DEC);
            client.print(":");
            client.print(now.second(), DEC);
            client.println("</text6>");
             client.println("
");
              client.println("
");
          client.println("");
          client.println("");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disonnected");
  }

delay(3000);

}

I have had to program in a reset for the network connection on quite a few of my ethernet projects.  I am not entirely sure the cause, but adding a close connection; open connection to run every x minutes seems to have helped prevent both the duplicating content and the timeout issues.

I used to encounter weird issues, e.g. starting a new instance of a program with Arduino Yun. The issue in the end was power supply, a large capacitor before the voltage regulator has solved the problem. What do you use for power supply?

Hey, i just started this arduino stuff like 3 weeks ago and have literally 0 knowledge of terminology or anything what so ever.  I know this power issue is something of concern. Currently it has been powered directly from USB, now starting today, (a few hours after this post) i am using the ac power adapter directly to the arduino Uno.  I will leave it on till tomorrow to see what happens.  I dont really understand much about the voltage regulation or anything like that. Im learning though. :P

I have noticed lower than 5V voltages when powering Arduino from the computer's USB. Better results were with ordinary mobile phone chargers/power adapters (USB), but the most stable power supply was with a dedicated AC/DC transformer/rectifier to 9V and then reduced to 5V with a linear regulator (LM7805 or similar + capacitors). The last version has the highest losses, needs additional circuit, but works in rather harsh conditions. Might be overkill for home, if ordinary AC power adapter works, stick to it. And as Stephan pointed out, checking free memory is your friend, too.

Thanks for the info. So far its been 2+ days and it has been running non stop with AC power brick, i am going to give it 3 days until i consider it stable.

I would go for a memory issue - try to rewrite your code in a way that consumes less memory, the easiest first step is to avoid any Serial.printl("String"); and replace that with Serial.println(F("String"));. But in general you are using a lot of String objects which should be avoided if possible (try to use char() instead).
To check memory consumption of your sketch you can use a function like this and log the values from specific points in the code:
int freeRam () {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}


text:
Photoresistor value drops when board stacked on Arduino Uno
I have a simple photoresistor displaying values on a serial monitor every second so I can establish a value that I want to use to have it activate a relay.
It has worked fine for a few weeks, with bright sunlight values about 1000, total dark is 0. I soldered only the headers on a protoshield, and stacked it on the Arduino. I have nothing else on the protoshield and I am still using jumper wires to a breadboard, which I have not changed.
Why would the photoresistor values drop to approximately 40 (from 900's) when I stack the second board on the Arduino?

Does the proto-shield have any LEDs on it?
You were probably connected to a pin unknowingly.
How is resistance being measured? A voltage divider with an analogRead()?
Using a cheapo multimeter can cause problems.
Possibly, his proto-shield has some trace "wires" etched into it that were unseen, and he was connected to a floating pin or ground.
Or maybe the shield was shifted over one pin, and he wasn't connected to the pins he thought.

It says it only has headers on it, so it looks like the answer is no

Can you provide more information to your answer? How can the OP test your theory. How do you suggest it should be fixed?

How is resistance being measured? A voltage divider with an analogRead? Using a cheapo multimeter can cause problems. Possibly his proto-shield has some traces that were unseen, and was connected to a floating pin. Or maybe the shield was shifted over one pin, and he wasn't connected to the pins he thought. Gotta love troubleshooting :)

@Chris - you need to address your comment to someone, probably the OP, as otherwise no one will ever get notification that you are asking for clarification (and it may not be read by whoever you except to read it). In fact, it is better to post your comment under the original question, rather than your answer, as it looks as if you are asking yourself for this additional information, rather than asking the OP.

Also, if you are adding more information to your answer, then it is preferable to edit your answer and add the information there, as comments can be deleted at any time. Plus, it consolidates the information, and saves other people from having to wade through comments in order to get the full picture.

@Greenonline Thanks, I didn't realize I needed to notify. I was providing more information and giving possible things to test at the request of sa_leinad.  My rep is not high enough to post on the OP, or I would have commented there in the first place.

It should not happen.
I have changed this answer, because at first I read that the resulting value was changed by -40, but I think it drops from 900 to 40.
The shield is doing something, so it is not empty. Perhaps it shortcuts the AREF to GND. Perhaps you are reading an open input, and the sensor is at another analog pin. Perhaps the shield does something to the voltage pins.
A breadboard can have bad contacts. The shield can have bad contacts.
Be sure that the sensor is connected to the channel that you are reading. Measure the voltage at that analog input with a multimeter with and without the shield. Check the 5V, 3.3V and AREF pins with and without the shield.

thanks.  i took off the shield and found out the readings did not change.  i completely redid the breadboard and fixed the issue.  what is weird, I even used a diagram from the sparkfun sik guide ( circuit 6) and ended up getting the inverse values (as it gets darker , the value goes up)   I reversed pos and negative leads from what the diagram shows and  got the right readings.  I put the shield back on hooked it up and the values are correct, so it was both on the breadboard, and following the diagram on that "how to do it" guide.

authors: Андрей Бабкин


text:
Need help with my urgent problem
Today I found a problem in my project, here is the video of problem
https://streamable.com/wamm9
code MASTER : https://www.dropbox.com/s/l4x3zwzv6szrs50/MASTER.ino?dl=0
#include <Wire.h>

const int BUTTON1 = 5;
const int BUTTON2 = 6;
int buttonchoose;

void setup() {
  // put your setup code here, to run once:
  pinMode(BUTTON1, INPUT);
  pinMode(BUTTON2, INPUT);
  Wire.begin();
  Serial.begin(9600);
}

void loop() {
  Serial.println("You want turn X motor");
  Serial.println("1-YES  2-NO");
  buttonchoose = fonctioninput();
  delay(500);
  if (buttonchoose == 1) {
    //Turn motor x for onerevolution
    Wire.beginTransmission(8); // transmit to device #8
    Wire.write('X'); // send M (milk)
    Wire.endTransmission();    // stop transmitting
    Serial.println("send X");
  }
  Serial.println("You want turn Y motor");
  Serial.println("1-YES  2-NO");
  buttonchoose = fonctioninput();
  delay(500);
  if (buttonchoose == 1) {
    //Turn motor Y for onerevolution
    Wire.beginTransmission(8); // transmit to device #8
    Wire.write('Y'); // send M (milk)
    Wire.endTransmission();    // stop transmitting
    Serial.println("send Y");
  }

  Serial.println("You want turn Z motor");
  Serial.println("1-YES  2-NO");
  buttonchoose = fonctioninput();
  delay(500);
  if (buttonchoose == 1) {
    //Turn motor Z for onerevolution
    Wire.beginTransmission(8); // transmit to device #8
    Wire.write('Z'); // send M (milk)
    Wire.endTransmission();    // stop transmitting
    Serial.println("send Z");
  }
}

int fonctioninput() {
  int val1 = 0;
  int val2 = 0;
  int buttonreturn = 0;
  while ( (val1 - val2) == 0) {
    val1 = digitalRead(BUTTON1);
    val2 = digitalRead(BUTTON2);
  }

  if (val1 == 1) {
    buttonreturn = 1;
  }
  else {
    buttonreturn = 2;
  }
  return buttonreturn;
}

code SLAVE : https://www.dropbox.com/s/2lg8ogjep80gtsa/SLAVE.ino?dl=0
#include <Wire.h>
#include <Stepper.h>

const int stepsPerRevolution = 64;
int led = A0;
Stepper motorX(stepsPerRevolution, 2, 3, 4, 5);
Stepper motorY(stepsPerRevolution, 6, 7, 8, 9);
Stepper motorZ(stepsPerRevolution, 10, 11, 12, 13);

void setup() {
  Wire.begin(8);
  // Wire.onRequest(requestEvent);
  Wire.onReceive(receiveEvent);

  pinMode(led, OUTPUT);
  motorX.setSpeed(60);
  motorY.setSpeed(60);
  motorZ.setSpeed(60);
  Serial.begin(9600);
}

void loop() {}

void receiveEvent(int howMany) {

  char choose;

  while (Wire.available() > 0) {
    //initialization
    choose = 'A';
    choose = Wire.read();

    if (choose == 'X')    {
      Serial.println("TURN MOTOR X");

      turnX();
    }
    else if (choose == 'Y') {
      Serial.println("TURN MOTOR Y");
      turnY();
    }
    else if (choose == 'Z') {
      Serial.println("TURN MOTOR Z");
      turnZ();
    }
  }
  analogWrite(led, 1020);
  delay(300);
  analogWrite(led, 0);
}

void turnX() {
  motorX.step(stepsPerRevolution);
}

void turnY() {
  motorY.step(stepsPerRevolution);
}

void turnZ() {
  motorZ.step(stepsPerRevolution);
}

When I choose yes to turn a motor it works well but the other motors that is after does not work.
I want the other motors to turn if I choose yes even if the previous motor is running.
Please, I need your URGENT help because my project is blocked
 :(

Please edit your question to include the code that you want help with.

Also asked at http://forum.arduino.cc/index.php?topic=503016

Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?

The step function from the Stepper library is blocking.  So it can only run one motor at a time.  You need a different stepper library that is non-blocking.  Try AccelStepper.


text:
Selling a product using Arduino microcontroller or bootloader
I was wondering if I am legally allowed to sell an Arduino based product.  I also want to know if it is easy for people to retrieve code from an Arduino based circuit (reverse engineer it) or upload code from Arduino microcontrollers.
If I'm posting in the wrong please, please let me know. If there is better place to redirect my question, letting me know would be helpful too.

The Arduino hardware is released under the creative commons license.
https://www.arduino.cc/en/Main/FAQ#toc3
"which allows for both personal and commercial derivative works, as long as they credit Arduino and release their designs under the same license"
It's possible for someone to retrieve the instructions from the MCU but they would be looking at assembly rather than the c code you wrote your sketch in.
This is a similar question and answer:
https://electronics.stackexchange.com/questions/67030/can-arduino-be-used-in-commercial-products

And what of the Arduino software ?  Also, your comment about retrieving information from the MCU is only conditionally accurate.