Fade sketch stuck in mathematical loop I tried to edit the Fade sketch such that the max intensity the PWM reaches is controlled by a potentiometer. I used analogRead() on the potentiometer and converted the 10bit value to 8bit equivalent(by dividing by 4 and rounding) to feed into analogWrite. I am new to arduino and I dont know a more elegant way to do this, sorry!

It worked generally but sometimes while turning the potentiometer, the LED would be stuck at a fixed level of brightness. I have to reset the Arduino or turn the pot to the extremes to remove this "loop". I set up serial monitor to look at the values of brightness. It does not always happen at the same position of the potentiometer.

I deduce that it is a mathematical error causing this loop, likely due to my poor use of the if() function. Can anyone offer me a reason for this?

*I tested with both the Uno and Nano, as well as TinkerCad simulator with similar results.

-----------------------------Fade sketch edited by me----------------------

/*
 Fade, edited with maximum intensity controlled by potentiometer reading
 */

int led = 11;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by
int potPin = A0;    // set the pin that reads the potentiometer voltage
int potValue = 0;   // declare and initialize potValue
int potValueConverted = 0; // 10bit potValue converted to 8bit equivalent

// the setup routine runs once when you press reset:
void setup() {
  // declare pin 9 to be an output:
  pinMode(led, OUTPUT);
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  //read the voltage at the pot
  potValue = analogRead(potPin);

  //convert 10bit input into 8bit output by dividing by 4, rounding to avoid need for float variable
  potValueConverted = round(potValue/4);

  // set the brightness of pin 11:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

Serial.println(brightness);

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= potValueConverted) {
    fadeAmount = -fadeAmount;
  }

  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

It seems like the problem occurs when brightness is a lot higher than potValueConverted.

For example, lets say our brightness=100, potValueConverted=50, this triggers the latter "if" condition, i.e.

  brightness >= potValueConverted

and at the next iteration, brightness = 105 (or 95), both of which will satisfy the condition for fadeAmount to flip its polarity, thus resulting in the brightness value oscillating between 105 and 100 (or 100 and 95).
This results in the LED getting stuck at the same level of brightness.

a quick hack fixes this problem (as far as I can tell)

 if (brightness <= 0 ) {
    fadeAmount = 5;
  }
 if (brightness >= potValueConverted +5 ) {
    fadeAmount = -5;
  }

**note the +5 for the second if statement is to ensure that the brightness value does not become negative.


2,5m cable too long for LCD connected to Arduino UNO? So i got that 2,5m cable wired with the LCD and the arduino, but i keep getting those weird characters showing up on the LCD. Clearly there is a signal loss between the components but there has to be a solution to the problem. Perhaps by connecting capacitors/resistors to the wires will help? Is there any solution other than not using this long cable?

If the interface you're using is I2C(only two cables from arduino to lcd, vice versa)you have a problem,you need to pull up the sda-scl channel with appropriate resistors, you could (maybe) boost the I2C signal using ti-p82b715 bus extender, I just assume you use I2C (2,5m length?), what interface do you use? SPI? I2C?


Loop one specific case inside of a switch I want to loop one specific case inside of my switch, until the button gets pressed a second time. How can i make this work?

Code:

const int ledrood = 9;
const int ledgroen = 10;
const int ledblauw = 11;
const int buttonPreset = 2;
const int buttonMix = 4;
float sensorWaarde = 0;
int switchtel = 1;

int roodval;
int groenval;
int blauwval;
int buttonState = LOW;

void setup() {
Serial.begin(9600);
pinMode(ledrood, OUTPUT);
pinMode(ledgroen, OUTPUT);
pinMode(ledrood, OUTPUT);
pinMode(sensorWaarde, INPUT);
pinMode(buttonPreset, INPUT);
pinMode(buttonMix, INPUT);

}

void loop() {
int sensorWaarde = analogRead(A0);
buttonState = digitalRead(buttonMix);
if (buttonState == HIGH) {

delay(200);
switch (switchtel) {
  case 1:
  roodval = 255;
  roodval = sensorWaarde / 4;

    groenval = 0;
    blauwval = 0;
    analogWrite( ledgroen, groenval );
    analogWrite( ledrood, roodval );
    analogWrite( ledblauw, blauwval);
    Serial.println(roodval);
    switchtel = switchtel + 1;
    break;

  case 2:

    roodval = 0; // cyaan
    groenval = 255;
    blauwval = 255;
    analogWrite( ledgroen, groenval );
    analogWrite( ledrood, roodval );
    analogWrite( ledblauw, blauwval);
    Serial.println("2");
    switchtel = switchtel + 1;
    break;

  case 3:

    roodval = 255; // magenta
    groenval = 0;
    blauwval = 255;
    analogWrite( ledgroen, groenval );
    analogWrite( ledrood, roodval );
    analogWrite( ledblauw, blauwval);
    Serial.println("3");
    switchtel = switchtel + 1;
    break;
    switch (switchtel) {

    }
   }
 }
}

You need to split your cases into multiple parts.

For example, you have a case which sets up a mode, and a case that runs a mode, and if needed a case that finishes a mode.

For example:

switch (mode) {
    case 0: // Idle
        break;
    case 1: // Start - do whatever to set up the mode here
        redValue = 100;
        greenvalue = 200;
        mode = 2; // Switch to the next case
        break;
    case 2: // Run - this is the bit that repeats
        if (digitalRead(3) == HIGH) {
            mode = 3; // Finish it
        }
        // Do whatever for each loop here.
        break;
    case 3: // It is finished.
        redValue = 0;
        greenValue = 0;
        // etc.
        mode = 0; // Or whatever you want to do next
        break;
}

The key thing here is that case 1 is equivalent to a mini setup() and case 2 is equivalent to a mini loop(). You switch to case 1, which does the setup, and that case then switches to case 2, which it stays at until you tell it otherwise. That case will keep getting executed until you tell it to move to another case.


Program an ATMega328P and use it without Arduino board I'd like to use an ATMega328P for my project, I hope to do it without the Arduino board.

I know with the Arduino IDE and an Arduino board I can program the microcontroller. However, would it be possible once I've programmed and debugged the program with Arduino IDE + Arduino board, to take away the microcontroller from the Arduino board and to use the ATMega328P separately, without the board?

If yes, what additional configurations I should do the ATMega328P to work correctly on the breadboard?

You can remove an ATMEGA from an Arduino and use it in your own board, however when used on a typical Arduino board the chip will be fused for an external crystal as a clock source, rather than the (simpler but less accurate) internal clock.

You cannot change the clock source over ISP unless the clock source the chip is currently expecting is operational, so if you want to change the clock selection you will want to do that before removing the chip from the Arduino.

However, you can also provide a clock crystal and its two capacitors (or a substitute resonator which often has this built in) on your external board.

Typically chips (even those pre-flashed with a bootloader as a convenience) are cheaper than boards, so it's unclear why you would want to move the same chip off the Arduino as opposed to using another.  You will want a USB-logical level serial adapter anyway, and once you have that you can do development on the bare chip on your board, even if you do initial testing on the Arduino.  In a pinch if you don't have the USB converter you can either pull the chip out of an Arduino board and run wires from its D1 and D0, or hold the on-board chip in reset to allow you to borrow those serial lines without interference.


Connect USB cable to GPIO pins on an Arduino Uno Electronics Newbie!!

I want to connect a USB cable to my Uno's GPIO pins (and then connect it to a USB port on my computer). I have chopped off a USB cable from a keyboard, I read this and I'm hoping that the wires will be in the correct order (the keyboard was made by Dell). I'm a little confused about which wires go where.

The reason you are confused about which wires go where is simply because the Uno has no connection on it for a USB cable's wires.

You cannot directly interface an Uno to a USB port without extra hardware.  What hardware you require depends on exactly what it is you think you are trying to achieve.

(There have been some attempts to create a USB device interface purely in software, but personally I wouldn't touch it with a barge pole - the GPIO of the Arduino is not electrically compatible with USB.)


Arduino Uno - What can I make with just the base board So I just bought my first Arduino (an Uno r3), and dove right in.

All I have currently is the base board (I didn't want to invest too heavily and then realize arduinos weren't for me), so I made a quick script that translates input letters to morse via the LED on the top.

Now that I'm done with that, I figured I'd come here to ask: do you guys have any random ideas for things I can make with JUST the uno? I understand that I should probably just start buying kits and shields, but I'm just curious as to what I can make with the most minimal of items. I consider it a test :)

Thanks in advance guys!

Well,

Your question is very broad. But the Arduino essentially needs controlling gadgteers to make things easy ( and funny ).

However if you know a bit of electronics, then you may be able to use the IN/OUT analog ports and build other interfaces to control, for example the lights of your home, or even better. You can measure and control priate things should be linked. Increasing the power of your home.

If you have interest in cars, then you can perform to connect the on-board computer of your car to the Arduino, like this.

Well, there are numerous ideas, none of these I'm saying is new and there are even libraries ready to be used in these segments mentioned above.

Regards,
Andrew Paes


Convert String to IPAddress How can i convert a String to IPAddress on arduino / esp ?

etc. "192.168.1.2"  -> IPAddress(192, 168, 1, 2)

Tried this

void setup() {

  Serial.begin(115200);

  IPAddress apip;

  const char *apipch;
  apipch = "192.168.4.1";

Serial.println(apip.fromString(apipch));

}

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

But i just get an output "1"

The IPAddress class has a member function bool fromString(const char *address).


QRPrint library characters limit I am trying to use this library to print QR codes using Arduino. There is a limit on the number of characters allowed in the string to be printed.

printQR("This is the string to be QR encoded !!! Tralalala. Some other random characters !!!");

When I scan the generated QR code, the string seems to be truncated. Did anyone run into this before? Or is there any way to get around this issue by raising the number of characters allowed in the string?

Thank you.

The code in the library truncates to 47 characters for some reason:

void printQR(String message) {

...

  // create QR code
  message.toCharArray((char *)strinbuf,47);
  qrencode();

The buffer is actually 116 bytes, oddly.

unsigned char strinbuf[116];

It's a little unclear why the limit of 47, or 116, was chosen.

You could try changing that line in qrprint.cpp to increase the number from 47 to at least 115.

Edit

After reading some of the comments, I doubt that will help. The QR code looks like it is generated into an internal array, which would have to have some size limits due to the amount of RAM available. The current array size is:

unsigned char qrframe[600];

That is already 1/3 of the available memory on a Uno.


When accessing a variable from an ISR, is a volatile pointer enough? Let's say I want to modify a global variable from inside an interrupt service routine. I must ensure that any variables I modify are volatile. Does it work to use a volatile pointer to data I want to modify if the data itself is not volatile?
In my case the data is a struct, but does the answer change if the data is a class, array, or just a variable?
#include <Arduino.h>

#define PIN_INTERRUPT  2

typedef struct MyStruct
{
    int a_field;
} MyStruct;

MyStruct struct_data;
int array_data[32];

volatile bool _flag_ISR = false;
volatile MyStruct *_struct_ISR = &struct_data;
void myISR()
{
    // just some example stuff
    int read = digitalRead(PIN_INTERRUPT);
    _struct_ISR->a_field = read;
    _arr_data_ISR[4] = read;

    _flag_ISR = true;
}

void setup()
{
    attachInterrupt(digitalPinToInterrupt(PIN_INTERRUPT), myISR, CHANGE);
}

void loop()
{
    if (_flag_ISR)
    {
        // do processing here...
        _flag_ISR = false;
    }
}

First, beware that what you have written is not a volatile pointer, it's
a pointer to volatile data. If you always access the object through this
pointer, you should be fine. If you use the pointer in the ISR, but
access the data directly in the main code (bypassing the volatile
qualifier), then the program could fail.
Consider the following:
void loop()
{
    if (_flag_ISR) {
        _flag_ISR = false;
        Serial.println(struct_data.a_field);
    }
}

Once the compiler inlines the call to loop() from main(), the
main program looks like
int main()
{
    init();  // Arduino core initialization
    setup();
    for (;;) {  // inlined loop()
        if (_flag_ISR) {
            _flag_ISR = false;
            Serial.println(struct_data.a_field);
        }
    }
}

And now, since struct_data is not volatile, the compiler can
legitimately optimize the code by avoiding repeatedly accessing the same
RAM location:
int main()
{
    init();  // Arduino core initialization
    setup();
    register int data_copy = struct_data.a_field;
    for (;;) {  // inlined loop()
        if (_flag_ISR) {
            _flag_ISR = false;
            Serial.println(data_copy);
        }
    }
}

And now the program prints only zeros.


How do I code the release of a momentary touch sensor in IDE? I am a performing musician and quite new to the Arduino community.  Just learning as I go.  I am interested in using a momentary touch sensor with Adafruit's MP3 shield or Wave Shield.  I have successfully connected a touch sensor to the MusicMaker MP3 shield (which is sitting on the Adafruit Metro).  I combined some code from two independently working code sequences: one, to play MP3s and, two, to trigger with the sensor.  This works successfully except that the music starts but does not stop when I lift my finger off the sensor.  I want the music to stop when the touch sensor is not being touched.  When the sensor is touched again, I want the music file to start again from the beginning.  I'm printing the code IDE is running below and attaching an image of the touch sensor I am using.  I appreciate any advice on the code!  Thank you.

/*
  AnalogReadSerial

  Reads an analog input on pin 0, prints the result to the Serial Monitor.
  Graphical representation is available using Serial Plotter (Tools > Serial Plotter menu).
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/AnalogReadSerial
*/

// include SPI, MP3 and SD libraries
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>

// define the pins used
//#define CLK 13       // SPI Clock, shared with SD card
//#define MISO 12      // Input data, from VS1053/SD card
//#define MOSI 11      // Output data, to VS1053/SD card
// Connect CLK, MISO and MOSI to hardware SPI pins.
// See http://arduino.cc/en/Reference/SPI "Connections"

// These are the pins used for the breakout example
#define BREAKOUT_RESET  9      // VS1053 reset pin (output)
#define BREAKOUT_CS     10     // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8      // VS1053 Data/command select pin (output)
// These are the pins used for the music maker shield
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)

// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

Adafruit_VS1053_FilePlayer musicPlayer =
  // create breakout-example object!
  //Adafruit_VS1053_FilePlayer(BREAKOUT_RESET, BREAKOUT_CS, BREAKOUT_DCS, DREQ, CARDCS);
  // create shield-example object!
  Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  Serial.println("Adafruit VS1053 Simple Test");

  if (! musicPlayer.begin()) { // initialise the music player
     Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
     while (1);
  }
  Serial.println(F("VS1053 found"));

   if (!SD.begin(CARDCS)) {
    Serial.println(F("SD failed, or not present"));
    while (1);  // don't do anything more
  }

  // Set volume for left, right channels. lower numbers == louder volume!
  musicPlayer.setVolume(20,20);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  if(sensorValue > 100) {
    Serial.println(F("Playing track 001"));
  musicPlayer.playFullFile("/track001.mp3");
  }
 else(sensorValue < 100); {
    Serial.println(F("Paused"));
  musicPlayer.pausePlaying("/track001.mp3");
 }      }

You have a semicolon that doesn't belong in your code. Your current code (With the indentation cleaned up a little)

void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  if(sensorValue > 100) {
    Serial.println(F("Playing track 001"));
    musicPlayer.playFullFile("/track001.mp3");
  }
  else(sensorValue < 100); { // <<<--semicolon does not belong here.
    Serial.println(F("Paused"));
    musicPlayer.pausePlaying("/track001.mp3");
  }
}

Should be:

void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  // print out the value you read:
  Serial.println(sensorValue);
  if(sensorValue > 100) {
    Serial.println(F("Playing track 001"));
    musicPlayer.playFullFile("/track001.mp3");
  }
  else(sensorValue < 100) { // <<<--semicolon removed from this line
    Serial.println(F("Paused"));
    musicPlayer.pausePlaying("/track001.mp3");
  }
}

With the semicolon after the else, your code reads "...else do nothing" and then I would expect it to execute the pause logic no matter what value is in sensorValue.

You should pick an indentation style and then be absolutely consistent with it. Most C/C++ programmers use K&R style, which is what I used in my edit. (Opening braces are on the same line as the if statement/function that begins the scope, code inside braces is indented, and closing brace is at the same indentation level as the line that contains the opening brace.)


How to send RPM data as analog input from arduino to Xbee I am new to arduino and Xbee these stuff.
Trying to send RPM (obtained and calculated by arduino using puulse function) data from arduino to Xbee as analog input to xbee series1.

It seems XBee analog input read a range of 0 volts to 1.2 volts.
However, not quite sure how to implement and write the corret code.
Following are Arduino code and schematic circuit.
Any idea?
I really appreciate your help.

int pin = 7;  //7
float rpm;
float duration;
float y;

unsigned long val;
float rps;
float read_rpm;
int pin_out=10;

void setup()
{
   Serial.begin(9600);
  pinMode(pin, INPUT);
  pinMode(pin_out,OUTPUT);
}

void loop()
{
 val =  pulseIn(pin, LOW,70000000);

 duration=(float)val/1000000.00;
 rps= 1.00/duration;
rpm=60.00*rps;

analogWrite(pin_out,(int)rpm);

Serial.print("RPM=\t");

Serial.print(rpm);

Serial.print("\t rps= \t");

Serial.print(rps);

Serial.print("\t dt=\t");

Serial.println(val);

}

I would suggest you to send bytes instead of "analog value". When you calculate your value, not sure why you use float and then convert it to int, but here is how i would do. Communicate to xbee via serial communication, send bytes to xbee(its even easier than "analog value"). Added if statment to print RPM every second.

Here is my code:

#include <SoftwareSerial.h>
/* Serial communication with Xbee.
On Arduino pin 9 is Rx connect to Xbee Tx,
pin 8 is Txconnect to Xbee Rx*/
SoftwareSerial xbeeSerial(9, 8); // RX, TX

int pin = 7;  //7
float rpm;
float duration;
float y;

unsigned long val,time;
float rps;
float read_rpm;
int pin_out=10;

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  pinMode(pin, INPUT);
  pinMode(pin_out,OUTPUT);
  Serial.println("I am ready to send some RPM!");

  // set the data rate for the SoftwareSerial port
  xbeeSerial.begin(9600);
  time = millis();
}

void loop()// run over and over
{
 val =  pulseIn(pin, LOW,70000000);

 duration=(float)val/1000000.00;
 rps= 1.00/duration;
rpm=60.00*rps;

/* Sending float to Xbee
Float is 4 byte size*/
serialFloatPrint(rpm);

int floatToInt = (int)rpm;

/* To send INT to XBEE
Int is 2 byte size*/
xbeeSerial.write(highByte(floatToInt));
xbeeSerial.write(lowByte(floatToInt));

/*Print RPM every second*/
If(millis()-time>1000){
  Serial.print("RPM=\t");
  Serial.print(rpm);
  Serial.print("\t rps= \t");
  Serial.print(rps);
  Serial.print("\t dt=\t");
  Serial.println(val);
  time = millis();
 }
}

void serialFloatPrint(float f) {
  byte * b = (byte *) &f;
  //xbeeSerial.print("f:");
  xbeeSerial.print(b[0]);
  xbeeSerial.print(b[1]);
  xbeeSerial.print(b[2]);
  xbeeSerial.print(b[3]);
  /* DEBUG */
  Serial.println();
  Serial.print(b[0],BIN);
  Serial.print(b[1], BIN);
  Serial.print(b[2], BIN);
  Serial.println(b[3], BIN);
  //*/
}


Encoder + Bounce2 Library I am working towards debouncing my keyes rotary encoder using the Bounce2 library found here ( https://github.com/thomasfredericks/Bounce2 ).

I believe the problem lies in my code as there isn't much in terms of a circuit. The encoder is connected to my arduino as follows

5V : connected to 5v out on arduino
GND : connected to GND
SW : connected to pin A1
DT : connected to pin 3
CLK : connected to pin 2

I am trying to call an ISR from a CLK input. When the ISR is called it should increment or decrement a value based on the direction the encoder was turned. This encoder is tied to an ISR because it will be used for user input and I would like it to remain responsive throughout the sketch.

Previously, I was using millis() to debounce the encoder, but I was still having trouble receiving more than one input from the encoder. I was hoping that this libary would resolve this issue.

The current output of the code I have included never increments/decrements the starting value no matter which direction the encoder is turned. In short, it always outputs 0.

If someone could explain what I am doing wrong that would be wonderful! Then maybe, but just maybe, I can stop beating my head against my desk. :p

Thanks,
Kevin

#include <Bounce2.h>

#define sw A1
#define LED_PIN 9
#define clk 2
#define dt 3

int ledState = LOW;
int onOff = LOW;

volatile int virtualPosition = 0;
int lastCount = 0;

// Initiate bounce objects
Bounce debouncerSW = Bounce();
Bounce debouncerROT = Bounce();

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

  pinMode(sw, INPUT_PULLUP);
  pinMode(clk, INPUT);
  pinMode(dt, INPUT);
  pinMode(LED_PIN, OUTPUT);

  // set up button instace
  debouncerSW.attach(sw);
  debouncerSW.interval(100);

  // set up rotary encoder instance
  debouncerROT.attach(clk);
  debouncerROT.interval(10);

  // setup the LED
  digitalWrite(LED_PIN, ledState);

  // attach ISR
  attachInterrupt(digitalPinToInterrupt(clk), isr, LOW);

  Serial.println("Start"); // just to let me know sketch has finished setup
}

void loop() {

  debouncerSW.update();

  if ( debouncerSW.fell() ) {
    ledState = !ledState;
    onOff = !onOff;
    digitalWrite(LED_PIN, ledState);

    //read-outs
    Serial.print("onOff = ");
    Serial.println(onOff);
  }
  virtualPosition = lastCount;

  //read-outs
  Serial.print ("lastCount = ");
  Serial.println (lastCount);

  delay(1000); // for readability / simulates delay time for rest of main sketch
} // end main loop

void isr ()  {

  // Update the Bounce instance :
  debouncerROT.update();

  if (debouncerROT.fell()) {
    if (digitalRead(dt) == LOW)
    {
      virtualPosition -- ; // Could be -5 or -10
    }
    else {
      virtualPosition ++ ; // Could be +5 or +10
    }

    // Restrict value from 0 to 100
    virtualPosition = min(100, max(0, virtualPosition));
  }
} // end ISR

The ClickEncoder library works very well with the Keyes rotary encoder: https://github.com/0xPIT/encoder. The Button reports multiple states: Clicked, DoubleClicked, Held and Released. It uses analog pins A1, A0, A2. You will also need the TimerOne library: https://code.google.com/archive/p/arduino-timerone/downloads.

My keyes rotary encoders have 3 surface mount resistor locations on the bottom of the circuit board. R1 has nothing, R2 and R3 have a 10k ohm resistor soldered in place. Not sure if this makes a difference.


pH ORP sensor esp12 esp82666 I need to know if there is a sensor that mesure pH and ORP, I have already googled about this type of sensor but i found only AtlasScientific that commercialise this kind of sensor

thanks

Yes there are lots.  You might try search for "Arduino PH Sensor" and "Arduino ORP sensor" you'll get a lot more hits for Arduino than ESP8226.
This might be useful:
http://www.instructables.com/id/ORP-pH-Temperature-Data-Logger/?ALLSTEPS


Arduino autorestarts when powered externally I'm trying to finish  building an alarm system with relays, leds  and bluetooth. I finally made it working but when externally powered (12v source) after about 10 seconds it starts to reboot continuously.
This issue comes with no pc connection.

https://www.arduino.cc/en/Main/ArduinoBoardUno

Majenko has a good lead,

12V is just within spec of the voltage regulator.

Though this may be different per manufacturer or different in your environment.

To battle overheating you can:

Create beter airflow
Add a heatsink
Draw less current

But you should try a 9V source, that can deliver enough current (not the 9V "block" batteries).

Also check if the system draws excessive current, maybe the circuit has a low resistance or power hungry part (on the 5V rail)

If nothing works, you could try and use another Arduino board, maybe the regulator is faulty/damaged.


Can I program AVR Microcontrollers using Arduino Development board with AVR Studio? I know and I can program any AVR microcontroller with Arduino IDE and Arduino Uno board. Can I use Arduino board with AVR Studio? Or I have to buy an AVR Development board?

You can use Atmel Studio to write code for the MCU(s) on the Arduino boards. If the IDE itself does not support uploading the code to the Arduino then it is still possible to use AVRDUDE or BOSSA to upload it via the command line.


Arduino MotorShield code running but not motors I have a motor shield V2 on my Arduino, i compile the codes just fine and i'm trying to just run the example dc motor test. The code compiles the serial is printing out the "tick tock ...." but the motors are not running. They ran once before on my mac though.

Using a 9v battery to power a basic Dc motor.

I'm using the right ports on pc. Same exact port for motor as the code tells. I'm not sure where i am wrong. TYIA

Turns out the pins connecting the shield to the Arduino are quite loose and didn't "touch" the Arduino.


What are the SVG pins for on the SainSmart Uno clone? I bought a SainSmart clone board which is compatible with the Arduino Uno R3. Alongside each of the standard IO pins, there is a row of 3 additional pins (male). They are arranged in columns, marked S, V, and G.

They can be seen on this image:

Most of them are immediately above the SainSmart and UNO logos. The SVG pins corresponding to the analog pins can be seen immediately below the microprocessor.

What are these pins for? Is this a standard format for some applications, or is it something unique to the SainSmart?

SVG = Signal, Voltage, Ground.

The Signal pin will carry the actual output, which may be high or low at any given time. It's basically just a male version of the corresponding standard GPIO pin. The Voltage pin will always be high (which can be 5v or 3.3v on this board, depending on the output level switch). The Ground pin is exactly what the name suggests -- it's connected to the board's ground.

This obviously means there is a lot of duplication. Why have two signal pins? And why bother having so many Voltage and Ground pins if they're all the same anyway?

The reason is simply convenience.

If you have a standalone external component (such as a motor), you would normally have to run 3 separate wires to it. With the regularly-spaced SVG pins on the board, you can instead use a 3-way cable with a suitable female header block. You can run that to an equivalent set of 3 pins on the external component. That means you are able to attach/detach the component by plugging/unplugging (effectively) a single cable.

I don't think the SVG idea is a 'standard' as such, largely because (in this form) it's only really of benefit to people who are experimenting or prototyping (as opposed to designing a more permanent system). It seems to be fairly popular among hobbyists and enthusiasts though. You just need to watch out for components which may put their equivalent SVG pins in a different order.


Why is my LED blinking? I have this simple push button schematic:

The idea is that the LED is on as long as the button stays pushed, with the switch closed.
The code is below:
int ledPin=10;
int switchPin=5;

void setup()

{
  Serial.begin(9600);
  pinMode(switchPin, INPUT);
  pinMode(ledPin,OUTPUT);

}
void loop()

{
  digitalWrite(ledPin,LOW);//DBG
  if (digitalRead(switchPin)==HIGH)
{
 digitalWrite(ledPin,HIGH);//DBG
 delay(500);
}
 if (digitalRead(switchPin)==LOW);
{
digitalWrite(ledPin,LOW);//DBG
delay(200);
}
}

As I keep the button pressed, the LED blinks regularly, instead of staying on. Why?
I have tried using a capacitor between the switch and switchPin, with no change.

The beginning of your code in the loop:

void loop()  {
  digitalWrite(ledPin,LOW); //remove this line here
  if (digitalRead(switchPin)==HIGH)
{
     digitalWrite(ledPin,HIGH);//DBG
     delay(500);
}
 if (digitalRead(switchPin)==LOW);
 {
      digitalWrite(ledPin,LOW);//DBG
       delay(200);
     }
}

Before your first if(digital read(switch pin) == HIGH)  you turn the LED off, and then you have a delay, which gives the blinking effect, remove that and it will not blink.


Writing C Program outside of Arduino IDE? I like the idea of using the Arduino IDE for simple projects and for getting started with Arduino, but the consensus I've gotten so far is that it is for those who are new to Arduino and/or programming in general.

My understanding is that it is possible to write a C program from scratch, completely outside of the Arduino IDE, and then use a tool like AVRDUDE to upload it to an Arduino MCU. This option, albeit appealing and interesting, leaves me with a few concerns:

What Arduino libraries would need to be imported/linked by such a "raw C" program? I assume that when an Arduino IDE-based program executes a digitalWrite(...) it is really calling a C lib, probably provided by Arduino, under the hood. I am concerned about making sure all these "underlying libs" get included with my C program. Thoughts?
Is anything else "lost" by flying solo and venturing outside the Arduino IDE? Any capabilities/features that I would now have to "roll my own"?

You're absolutely right about needing to link against other libraries. However, you don't necessarily need to worry about all of the details yourself, unless you want/need to do something unusual. Several alternative IDEs already support Arduino, typically via plugins which handle a lot of the details automatically.

I normally recommend Eclipse as it's a very widely used IDE for various purposes. However, there are several other possibilities. See this question for more information:

What are the other IDEs for Arduino?


LED doesn't register as LOW after a switch has cut all power to it I have the following build:

And the following code:

const int buttonPin = 3;
const int ledPin = 2;
int buttonState = 0;

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

  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

}

void loop() {
  while (digitalRead(ledPin) != LOW){
    buttonState = digitalRead(buttonPin);

    if (buttonState == LOW){
      digitalWrite(ledPin, LOW);
    }
  }
}

But it doesn't seem like anything is registered, as my program doesn't respond to the shut down of the LED. What have I done wrong?

The diagram is open to several different interpretations, depending on what's inside the four-terminal switch.  On many such SPST switches, two adjacent terminals are connected to each other inside it, and the other two likewise.  Which are which in the diagram isn't indicated.

That aside, what is clear from the diagram is that pin 2 is connected by wires to +5V, and will always read in as high.

Edit 1:
The schematic [posted later] is unclear.  It should be arranged so that solid lines represent wires or pins, with solid lines between things that are connected.  Place items in the drawing to reduce unnecessary and confusing crossing lines.  For example, supposing that the dashed line from pin 2 of R1 represents a wire between pin 2 of R1 and pin 2 of LED1, it is unclear whether the wire bends around the top right pin of S1 (can't read number) or connects with that pin on its way to LED1.  For another example, nothing is shown connecting to pin 1 of R1, and only one long dashed line connects the R1/S1/LED1 group to the Uno.


Power supply voltage confusion I just ran into this article: Arduino: What adapter?.

It says that the external power supply should be 9-12V. That really surprises me, since my Arduino Uno can also be powered via USB, which is 5V.

Later he talks about a 9V pin. But I can only see a 5V and 3.3V pin on mine. Is he talking about a different version of Arduino?

Judging from the picture, his Arduino looks slightly different from my Arduino Uno R3, but I can't tell which version is on the picture.

The board has a voltage regulator which converts 9-12V to the 5V that the chip uses.

Why does it need 9V if the board works at 5V? Well, it doesn't need 9 exactly, but it needs something greater than 5. The reason for this is that the regulator has whats called a dropout voltage.

Looking at the schematic of the Uno we see it uses a NCP1117, which has a dropout of 1.2V. So the minimum voltage you can give it to get 5V is 6.2.

The 9V pin is the Vin pin which is at the same level as the input voltage (before converting).


Using a class instance with Wire.onReceive Is it possible to register a class instance member function with Arduino's Wire.OnReceive?

I'm trying to make my code object-oriented, and want a specific non-static class function to handle I2C data, but if I'm reading this thread correctly, onReceive is incompatible with classes since it only accepts a function pointer, which won't store context.

A non-static class member function has an implicit ClassName *this parameter inserted as the first parameter in the parameter list.

Because the function prototype required for Wire.onReceive() does not have that parameter specified in its parameter list a non-static member function is not compatible with it.

The same goes for attachInterrupt() and anything else that takes a function pointer.


Define preset colors using FastLed library I'm using an addressable 150 led strip and an Arduino Nano to control it, using FastLed library.

I'm tring do create a function turn_on_leds, which gets 4 parameters:

1) delay time for lighting a led in the loop, 2) direction ( not relevant for now), 3) color index for colors array , 4) brightness percentage.

Problem #1: a color array is defined to select from a preset definitions of colors (Fastled reference, but when selecting col_indx =2, meaning colors[2], leds are not lit in Red as they should, AND when setting leds[i]=0xFF0000, the right result is set.

Problem #2: at loop there is a for intended for raise bightness from 0 to 100, BUT the results are 0 for first iteration and 9 for all others.

Appreciate any HELP!!

Guy

Code:

#include <FastLED.h>

#define NUM_LEDS 10
#define BRIGHTNESS  55
#define DATA_PIN 7

char *colors[] = {0x000000,0xFFFFFF,0xFF0000,0x008000,0x0000FF}; // black, white,r,g,b
CRGB leds[NUM_LEDS];
int t = 0;

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

void turn_leds_on(int del_1, bool dir_1, int col_indx, int bright_1) {
  if (dir_1 == true ) { // start to end
    for (int i = 0; i <= NUM_LEDS; i++) {
      leds[i] = 0xFF0000;//colors[col_indx];
      FastLED.setBrightness(bright_1*255/100);
      FastLED.show();
      delay(del_1);
    }
  }
}

void loop() {
  Serial.println(t);
  turn_leds_on(50, true, 2, 100);
  delay(1000);
  //  turn_leds_on(50, true, 0, t);
  //  delay(1000);

  if (t < 100 ) {
    t += 10;
  }
  else {
    t = 0;
  }
}

Your colors array should be CRGB type, not char *.

CRGB colors[] = {0x000000,0xFFFFFF,0xFF0000,0x008000,0x0000FF}; // black, white,r,g,b

For your second problem - you are overflowing the bounds of your LEDs array:

for (int i = 0; i <= NUM_LEDS; i++) {
  leds[i] = 0xFF0000;//colors[col_indx];

You are going from 0 to 10 inclusive. That's 11 iterations. There is no such array slice as leds[10], so the value you write to it ends up overwriting the next two bytes in memory - and those happen to be occupied by the variable t.


Receiving i2c bytes on an attiny85 I've been trying to write a small i2c lib in C over the past week. I managed to get writing to slaves working (for example I can write to an ssd1306 oled) but reading (for example date/time from an ds3231) never works as my slaves don't seem to set SDA high when I request bytes.

uint8_t
i2c_read(uint8_t ack)
{
    uint8_t i, val;

    val = 0;
    cbi(SCL);
    DDRB &= ~(1 << SDA); /* Use SDA for input. */
    cbi(SDA); /* We need to pull down SDA to receive input. */

    /* Read 8bit from the slave. */
    _delay_us(DELAY);
    for (i = 0; i < 8; ++i) {
        sbi(SCL); /* Request one more bit. */
        _delay_us(DELAY); /* Wait a little so the slave can send his answer. */
        if (PORTB & (1 << SDA)) { /* Here the slave should have set SDA to 1 but it never does. */
            PORTB |= (1 << PB4);
            val = (val << 1) | 1;
        } else {
            val = (val << 1);
        }
        cbi(SCL);
        _delay_us(DELAY);
    }

    /* Send back an ACK or NAK. */
    DDRB |= 1 << SDA; /* Use SDA for writing. */
    if (ack)
        cbi(SDA); /* Set SDA to 0 to send ACK. */
    else
        sbi(SDA); /* Set SDA to 1 to send NAK. */

    sbi(SCL);
    _delay_us(DELAY);
    cbi(SCL);
    cbi(SDA);

    return val;
}

I set PB4 with to 1 when a slave actually sends a 1. Apparently that never happens.
I also had a look at how the various other libs out there do it but I didn't spot anything that would make a difference.

Any clues on what I migth be missing? Before reading my program sends the slave address to the bus. Also: please don't tell me to use other libraries since this is a learning project.

Not sure, if this is the only problem, but you are reading from the wrong register.

There are 3 registers associated with a digital output pin: DDR, PORT and PIN. To read a pin, you need to read from the PIN register. Currently you are reading the PORT register, which will only ever have the value, that you set it to (zero in this case, because you cleared the bit beforehand with cbi(SDA);). When you configure the pin as input with the DDR register, the PORT register determines, if the internal pullup resistor is activated or not, so it cannot reflect the actual state of the pin. For this you need the PIN register.

Besides that, you might want to look into another thing, that might or might not be a problem in your case: I2C is an open drain bus, meaning, that it is driven actively low and passively high (through pullup resistors). I guess you already have external pullup resistors on your lines, so that you really can deactivate the internal pullup without breaking the communication. But imagine the following situation: The slave get's a request, but cannot clock it out that fast (for whatever reason). It can pull the clock to LOW, until it is ready to push out the data bit, slowing down the clock speed. (This can be done for every bit, unless you are in highspeed mode, then only before the start of a new byte). (This behavior is called clock stretching - Thanks to Edgar for the information) You don't monitor the line, so it can happen, that you drive the clock line actively to high, before the slave has released it. This results in a significant current between master and slave, since the master drives actively high and slave actively low.

There are implementations of I2C communication, that are just doing that and are working fine in most situations. I just wanted to give you this information. And if you at some point want to implement bus arbitration (to allow a multi-master setup), you definitely need this open drain behaviour.


Making a menu through serial I'm working on a project for a robot and I'm trying to make a menu that can run on start up where the user can calibrate the mid-point for the servos (so they're stationary) and the ldrs so it can tell between black lines and white paper. So, I've made the menu a switch case where it calls the calibration when user enters a value, the calibration routines are their own functions.

What I want to know how to do is how to make it so when the user is finished with a calibrator it will go back to the menu function and also how to get the menu to exit on user input. So far when the menu calls a function it will just loop on it.

The menu:

void Menu(){

  Serial.println("|****************************|");
  Serial.println("|**|Ardnoid Configuration |**|");
  Serial.println("|**|        Menu          |**|");
  Serial.println("|****************************|");
  Serial.println("");
  Serial.println("Select one of the following options:");
  Serial.println("1 LDR configuration");
  Serial.println("2 Servo calibration");
  Serial.println("3 Exit configuration menu");

  while(!Serial.available()){}
  int i = Serial.parseInt();

  switch(i){

  case 1:
    break;
  case 2:
    while(srvConOn == true){
      srvConfig();
      }
    break;strong text
  case 3:
    Serial.println("Leaving configuration menu");
    break;
  default:
    Serial.println("Unrecognized command, try again!");
    }
 }

and the servo calibration:

void srvConfig(){

Serial.println("");
Serial.println("Begin servo stop calibration routine");

int x = 0;

  while(x == 0){

    Serial.println("Enter values for servos until both are stationary");
    delay(100);

    Serial.println("Enter value for left servo");
    while (!Serial.available()) {;}
    left = Serial.parseInt();
    Serial.println(left);
    delay(100);

    Serial.println("Enter value for right servo");
    while (!Serial.available()) {;}
    right = Serial.parseInt();
    Serial.println(right);
    delay(100);

    srvR.write(right);
    srvL.write(left);

    Serial.println("have both servos stopped?");
    Serial.println("1 = Yes | 2 = No");

    int j;
    while (!Serial.available()) {;}
    j = Serial.parseInt();

    if (j == 1) {
      Serial.println("Saving calibration");
      EEPROM.write(leftMid, left);
      EEPROM.write(rightMid, right);
      srvConOn == false;
      x == 1;
      } else if (j == 2) {
        Serial.println("Try again");
        Serial.println();
        }
  }
}

You could put your switch/case inside an infinite loop, and return from
the Menu() function when the user presses '3'. E.g.:

void Menu() {
    Serial.println(menu_banner);
    for (;;) {
        switch (Serial.read()) {
            case '1': ldrConfig(); break;
            case '2': srvConfig(); break;
            case '3': return;
            default: continue;  // includes the case 'no input'
        }
    }
}


'Basic electronics' resources I've seen that there are many resources on programming basis for arduino for people that have some electronics basis or background. Are there similar resources on the opposite? Basics electronics for programmers? Things that cover:

How to read schematics (different elements that appear there)
What different pins are used for (yeah, even on a more basic level than arduino documentation)
General idea of how a protoboard/protoshield works and how to connect components
General common components (resitors, capacitors...) and when and how to use them...
Safety rules, what happens when you do something wrong

From zero to Arduino (maybe a HOWTO someday?)
Rule zero:

Don't overestimate the other Arduino users! They all were not born with this knowledge too.
Never be too shy to ask!
Making mistakes is ok as long as they trigger learning.

(-: short break :-)
You'll find lots of HOWTOs and other tutorials in the wild wild web.
I assume, the confusing thing is to read them in the wrong order.
Forget your Arduino(s) for a while and start with reading about:

General common components (resitors, capacitors...) and when and how to use them...

This will at least partially answer:

Safety rules, what happens when you do something wrong
How to read schematics (different elements that appear there)

If not already done:

Read about ANDs, ORs, NANDs, NORs, FLIPFLOPs...

This will show how their schematic symbols look like.

...compare them to creating the same behaviour by programming (if,
and (&&), or (||), ...)
Have a look at bit operations (&, |, ... on whole number variables.

The programming up to this point can be done on your PC.
After this, dedust your Arduino again and jump into:

What different pins are used for (yeah, even on a more basic level
than arduino documentation)

(Happy end. At least for now.)
(I make this a community wiki answer to invite others to expand this text.)


L1 is not declared in this scope error I have a project where I have to control a DC motor.
In this code the purpose is that every time you press a button the direction of the motor changes.

I only get the error that L1 (and L2,R1 and R2) are not declared in this scope. the place in the loop.
How do I define the variables so that the code works?

int Motorforward = 10;   // MotorDirectionPin set to pin10
int Motorbackward = 11;   // MotorDirectionPin set to pin11
const int button1Pin = 2; //button control set to pin 2

int state = L1;
int state = L2;
int state = R1;
int state = R2;

int button1State;  // current reading from the input pin
int previous = LOW; //the previous reading from the input pin

char input;

void setup(){
pinMode(button1Pin, INPUT); //set pin as input
Serial.begin(9600);

pinMode(Motorforward, OUTPUT); // sets the pin as output
pinMode(Motorbackward, OUTPUT);
 }

  void loop(){
button1State = digitalRead(button1Pin);
input = button1State;

switch(state){
  case L1:
    if (state == L1){
    if (button1State == HIGH){
        state == L2;
    }
  }
  break;

case L2:
  if (state == L2){
    if (button1State == LOW){
      state == R1;
    }
  }
  break;

case R1:
  if (state == R1){
    if (button1State == HIGH){
      state == R2;
    }
   }
  break;

case R2:
  if (state == R2){
    if (button1State == LOW){
      state == L1;
    }
  }
  break;
}

I have the feeling you need only one state which can have 4 values: L1, L2, R1 or R2.

For this, use an enum:

enum EState { L1, L2, R1, R2 };

Now create one state variable of that type and give it an initial value.

EState state = L1;

Some other problems I see at first sight:

case L1:
  if (state == L1){
  if (button1State == HIGH){
      state == L2;
  }
}
break;

In this statement, when there is case L1, it means the code following ( until the break) is only handled when the state (because of switch(state) is L1, so you can remove the check if (state == L1). What is left is:

case L1:
  if (button1State == HIGH)
  {
    state == L2;
  }
  break;

Than you use state == L2 to set a new state. However, the == only compares two values, if you want to assign it, you have to use a single =, thus the code should be:

case L1:
  if (button1State == HIGH)
  {
    state = L2;
  }
  break;

Of course you have to do this also for the other case statements.

Tip: align your code (make the { and } aligned under each other; this will make your code readability much better.


Creating a webserver on a Wemos D1 mini pro I am trying to put a web server on my Wemos D1 mini pro. I am using this example for the Arduino code:
https://github.com/wemos/Arduino_D1/blob/master/doc/esp8266wifi/server-examples.rst

#include <ESP8266WiFi.h>

const char* ssid = "GL-AR300M-ceb";
const char* password = "********";

WiFiServer server(80);

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

  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");

  server.begin();
  Serial.printf("Web server started, open %s in a web browser\n", WiFi.localIP().toString().c_str());
}

// prepare a web page to be send to a client (web browser)
String prepareHtmlPage()
{
  String htmlPage =
     String("HTTP/1.1 200 OK\r\n") +
            "Content-Type: text/html\r\n" +
            "Connection: close\r\n" +  // the connection will be closed after completion of the response
            "Refresh: 5\r\n" +  // refresh the page automatically every 5 sec
            "\r\n" +
            "<!DOCTYPE HTML>" +
            "<html>" +
            "Analog input:  " + String(analogRead(A0)) +
            "</html>" +
            "\r\n";
  return htmlPage;
}

void loop()
{
  WiFiClient client = server.available();
  // wait for a client (web browser) to connect
  if (client)
  {
    Serial.println("\n[Client connected]");
    while (client.connected())
    {
      // read line by line what the client (web browser) is requesting
      if (client.available())
      {
        String line = client.readStringUntil('\r');
        Serial.print(line);
        // wait for end of client's request, that is marked with an empty line
        if (line.length() == 1 && line[0] == '\n')
        {
          client.println(prepareHtmlPage());
          break;
        }
      }
    }
    delay(1); // give the web browser time to receive the data

    // close the connection:
    client.stop();
    Serial.println("[Client disonnected]");
  }
}

It uploads fine and when I open the serial monitor get this:

Connecting to GL-AR300M-ceb . connected
Web server started, open 192.168.8.119 in a web browser

When I go to the IP address that it gives in the monitor, I only see a blank page. I also can't inspect element, so it doesn't load the HTML part I guess.
When I change the code like this:

if (client.available())
{
//        String line = client.readStringUntil('\r');
//        Serial.print(line);
//        // wait for end of client's request, that is marked with an empty line
//        if (line.length() == 1 && line[0] == '\n')
//        {
//          client.println(prepareHtmlPage());
//          break;
//        }
          client.println(prepareHtmlPage());
      }

then i see this

And when i add the break in the code like so:

client.println(prepareHtmlPage());
break;

in the code, i get the blank page again.

Does someone have an idea what the problem might be?

you should go for the "Advanced Webserver" example provided by the ESP8266 libraries in your Arduino IDE.
The webserver is using callbacks like

server.on ( "/", handleRoot );
server.on ( "/test.svg", drawGraph );

and so on.
Then you can use these handles to give back a html page to your browser like

server.send(200, "text/plain", message);       //Response to the HTTP request

Note how the function returns an 200 http code to your browser, which is mandatory for showing up your web page!


Arduino fast start not working properly I have an Arduino 328p (custom) and I can program it using a FTDI header.

However, when I power it from the FTDI using only the RAW (5V) and GND, it only executes simple programs (example blink). If in my sketch I attempt to use SPI for example, it will just get stuck.

If I power the arduino from the FTDI with the DTR pin connected, it will work just as expected for any sketch. I can even remove the DTR pin at this point and there will be no issue.

What could be the cause of this behavior?
Can it be an issue with optiboot fast start?

PS: FTDI is configured for 5V but VCC for the Arduino is 3.3V (I'm using the MCP1703 regulator). This means that the Arduino is powered by 3.3V but the RST pin will have 5V.
PPS: The Arduino is running at 16MHz

The reason for this issue is to do with SPI.

Basically in my custom arduino I have a 4Mbit flash and it communicates over SPI.
It seems that when the RST pin is connected it also automatically initializes the SPI protocol.

When the arduino is powered from RAW + GND directly from an external power source you need to initialize SPI manually.

In your sketch you need to:

    #include <SPI.h>

    void setup() {
        SPI.begin(); // this needs to be invoked before any SPI device gets initialized

        // initialize and use SPI devices
    }


Why can't I use just the digital pins and a ground to use a potentiometer? First of all I am a newbie. So please excuse.

After doing the first basic project, in which I had hooked up the positive of a LED to a digital input of the Arduino and the negative to the ground of the board, I am assuming that the digital pins in Arduino are positive (are they 5v?).

So why can't the potentiometer be connected in the same way?

Thank you.

A potentiometer is an analog device, meaning it communicates its position by varying the voltage rather than sending discrete ones and zeros.

If a linear potentiometer is turned half way then the output of the pot will be at half the voltage of the input. If it is turned all the way then the output will equal the input voltage and if it is not turned at all then the output will be 0V.

In order to make sense of the potentiometer you must connect the output to the analog pins and it will give you a 10 bit number, the higher this number the closer the output voltage of the potentiometer is to 5v (or whatever you set the Analog Reference voltage to be, but don't worry about the AREF pin for now).

Digital pins are either on or off, there is no in between, so they do not work for this application

This page has an excellent potentiometer user guide: https://www.arduino.cc/en/Tutorial/Potentiometer


Arduino MKR GSM 1400: Can I tell from code if the power has tripped Is there a way to tell if an Arduino MKR GSM 1400 has lost power and has to rely on the connected battery?
Ideally, I'd like to do this without adding additional circuitry. Alternatively, can I connect VIn to an analogue input pin?
On the schematic, there are two lines that seem promising. One named VBATT\2.4B that go into PB09 of U1 via a voltage divider and another named VBAT\1.4B. Also the BQ24195L is an I2C device which would probably be connected the the main micro controller.
What I need to do is to send an SMS as soon as the incoming power is lost to notify a user that the power supply has tripped. Does anyone have any code samples?

VBATT/2.4B is used for measuring the batter voltage using the internal ADC of the MCU. It can't really tell if the battery is being used or not - except by maybe monitoring it over time and see if the voltage goes up or down.
However the BQ24195 is where all your hope lies.  It has a status register that can tell you all sorts of things.
For example it can tell you if there is incoming power, and what that incoming power is coming from (a USB host, a USB power adaptor, or operating in OTG mode). It can also tell you what the battery is doing - if it's charging, or not for example.
A quick google search throws up this library specifically for the purpose.


Sending struct from Arduino to Raspberry Pi - wrong types I'm using Raspberry Pi and Arduinos for my home automation project where Raspberry Pi is the controler of Arduino nodes.
I use nRF24 wireless transceivers to communicate.

My problem is that when I was sending a structure like following

struct TempSensorData

{
      uint32_t result;
      uint32_t temperature;
      uint32_t humidity;
    };

From Raspberry to Raspberry everything went fine but now when I use Arduino as sender I get very strange results:

received: status: 335544320, temperature: 754974720 degrees, humidity: 0%

While on Raspberry it was

received: status: 0, temperature: 22 degrees, humidity: 44%

Can this be a problem with types? Or with different type of architecture (like different sizes on 3-2bit and 64-bit arch)?

EDIT:

Code on Raspberry:

if (radio.available())

{
        // dump the payloads until we've got everything
        Message receivedData = {0};
        radio.read(&receivedData, sizeof(Message));
        TempSensorData data = receivedData.msgData.tempSensorData;
        std::cout << "received: status: " << data.result << ", temperature: " << data.temperature << " degrees, humidity: " << data.humidity << "%" << std::endl; //TODO here we have some strange numbers - check if we have proper types
    }

Before that I have:

radio.begin();
radio.setPALevel(RF24_PA_LOW);
radio.setChannel(0x4c);
radio.openReadingPipe(1, RASPI_READ_ADDR);
radio.openWritingPipe(RASPI_WRITE_ADDR);

radio.enableDynamicPayloads();
radio.setAutoAck(true);
radio.powerUp();
radio.startListening();

And on Arduino:

Header header = {thisNodeId, thisNodeType, 0, static_cast<uint8_t>(MsgType::TEMP_SENSOR_DATA), 12345, Status::ok};
TempSensorData dhtData;
dhtData.result = DHT.read11(DHT11_PIN);
dhtData.humidity = (int)DHT.humidity;
dhtData.temperature = (int)DHT.temperature;
Message message = {0};
message.header = header;
message.msgData.tempSensorData = (dhtData);
radio.stopListening();
radio.write(&message, sizeof(message));
radio.startListening();

I also use a common header with defined structures for both Arduino and Raspberry, which contains:

#define RASPI_WRITE_ADDR 0xF0F0F0F0F0LL
#define RASPI_READ_ADDR 0xF0F0F0F0E1LL

struct TempSensorData {
  uint32_t result;
  uint32_t temperature;
  uint32_t humidity;
};

enum class Status : uint8_t

{
        ok,
        error,
        fail
    };

enum class MsgType : uint8_t {
    INITIALIZATION,
    RESET_REQUEST,
    ACK_NACK,
    TEMP_SENSOR_DATA,
};

struct Header {
  uint8_t nodeId;
  uint8_t nodeType;
  uint8_t location;
  uint8_t msgType;
  uint16_t checksum;
  Status status;
};

union MsgData {
  InitMsgData initMsgData;
  AckNack ackNack;
  TempSensorData tempSensorData;
};

struct Message {
    Header header;
    MsgData msgData;
};

radio is an item of RF24 class from https://github.com/TMRh20/RF24/

Unfortunately the RF24 repo is 64 commits ahead of what I use.

EDIT2:

Maybe the problem lays in that

enum class Status {};

which I use in both files.

I must add that I use g++-4.7 when compiling on Raspberry and when compiling on Arduino I use avr-g++-4.8.2

It is not a size problem: uint32_t is always 32 bits. Converting the
numbers to hex gives:

Raspberry to Raspberry: 0x00000000, 0x00000016, 0x0000002c
Arduino to Raspberry: 0x14000000, 0x2d000000, 0x00000000

There seems to be an offset between the two. You may just have lost one
byte when the Arduino is the sender. There may be also a byte order
issue, but your test is not sufficient to say. You can, e.g., send a
series of 0x12345678 to know for sure.

You need to devise a way of synchronizing the communication, i.e. to
identify, in the byte stream, which is the first byte of the packet.

Edit: Let me illustrate how this can happen both with and without
and endianness issue. I'll assume you are transmitting
{status: 0, temperature: 20, humidity: 45} and the first byte(s) of
the first packet are lost. On the receiving side, you combine the
remaining bytes of the first packet with the first byte(s) of the second
packet, and interpret the whole as a single packet. You get:
{status: 335544320, temperature: 754974720, humidity: 0}.

In a little endian to little endian scenario, you only need to loose one
byte:

original data:     0x00000000, 0x00000014, 0x0000002d
transmitted bytes: 00 00 00 00 14 00 00 00 2d 00 00 00
received bytes:    00 00 00 14 00 00 00 2d 00 00 00 00
received data:     0x14000000, 0x2d000000, 0x00000000

In a big endian to little endian scenario, you get the exact same result
if you loose 4 bytes:

original data:     0x00000000, 0x00000014, 0x0000002d
transmitted bytes: 00 00 00 00 00 00 00 14 00 00 00 2d
received bytes:    00 00 00 14 00 00 00 2d 00 00 00 00
interpreted data:  0x14000000, 0x2d000000, 0x00000000


Two-way communication on multimaster I2C bus I'm trying to send data both ways between an Arduino Mega 2560 slave and 2  Arduino Nano Zero (ATSAMD21G).

This example is a simplified setup and code. There will be more masters along with passive slaves on the bus (LCD, EEPROM).

Code and results (txt files)

My code is working fine with one master only and the slave active on the bus (data is sent both ways every 2s). I however notice missing transfers to the masters when more than one master is active. The 2 masters to slave transfers are working properly (once the 2 masters are on, the data is received by the slave every 2s from each master).

Is this problem due to collision? How can I handle it?

notice missing transfers to the masters when more than one master is active.

Because you didn't provide a way for the master's to know of a transmission ISS in progress. Lack of conflict resolution. A problem with all multimeter transmission.

A simpler approach is for the slave to signal a transmission from the master. That can be done via a slave requestion pin from the slave to the master.


Can you access the EEPROM of an ATtiny with Arduino Code? I'm attempting to reduce the amount of RAM being used by my program by writing some values to the EEPROM of my micro controller. I'm currently programming on the ATtiny85 which has 512 Bytes of EEPROM. According to the documentation this is how you write to EEPROM:

#include <EEPROM.h>

void setup() {
  EEPROM.write(0, 1);
  EEPROM.write(1, 0);
  EEPROM.write(2, 3);
  EEPROM.write(3, 2);
  EEPROM.write(4, 1);

}

For some reason this isn't working for me and I can't seem to find the error. Am I programming this wrong or can the EEPROM of the ATtiny simply NOT be accessed with Arduino Code?

Here is the Datasheet: http://www.atmel.com/Images/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet-Summary.pdf

Here is the second sketch I'm using to test the EEPROM:

    #include <EEPROM.h>

void setup() {
  EEPROM.write(0, 1);
  EEPROM.write(1, 0);
  EEPROM.write(2, A3);
  EEPROM.write(3, A2);
  EEPROM.write(4, A1);

byte CLK = EEPROM.read(0);

}

void loop() {

  if(CLK == 1)
  {
    for(int i = 0; i < 3; i++)
    {
    digitalWrite(0, HIGH);
    delay(1000);
    digitalWrite(0, LOW);
    delay(1000);
    }
    exit(0);
  }
  else
  {
    for(int i = 0; i < 100; i++)
    {
    digitalWrite(0, HIGH);
    delay(1000);
    digitalWrite(0, LOW);
    delay(1000);
    }
    exit(0);
  }

  exit(0);

}

The Arduino EEPROM library is compatible with the ATTiny range of AVR microcontrollers as the library itself is built on the standard Atmel AVR avr/eeprom.h 'library' so it is compatible with all the AVR microcontrollers.

The EEPROM also doesn't take to being written or read to often as EEPROM can wear very quickly. Reading though does not cause much damage though.

Also note that using exit(0); will stop the ATTiny from doing anything else after it is called so I hope your intention is to only run the loop once, if not this would account for either not seeing anything or it only ever running the blinking cycle once.

To answer your follow up question. Yes you can run one sketch to set you values in EEPROM and then use another sketch to read those. That us usually the point of EEPROM it is a memory type that "keeps its value while there is no power".

Also you need to make sure the ATTiny is set to preserve EEPROM during upload with the ISP, this is done with the fuse settings. You need to look for a tutorial on fuse calculators for the AVRs. To set the EESAVE you need to set the High fuse to 0xD7, you can change this in the boards.txt file. Here is a fuse calculator.

If the code that is on your question at the moment is being used you won't be seeing anything as it needs the pins to be set with pinMode. That's a note for others that see this.

Next what you can do is run a basic test code which blinks the LED without anything else going on.

Basically:

void setup(){

 pinMode(0, OUTPUT);

}

void loop(){

 digitalWrite(0, HIGH);
 delay(1000);
 digitalWrite(0, LOW);
 delay(1000);

}

Below is the code you have written, it works I have it running in front of me.
I have commented it and changed a few things to make it work as intended, although the intention is not clear.

#include <EEPROM.h>

byte CLK = 0; //This is a global variable with an initial value

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

  EEPROM.write(0, 1); //set the pin to D1
  delay(5);

  //read from EEPROM address 0
  //this sets the value of the global variable CLK
  CLK = EEPROM.read(0); //place this inside a function

  //just to give an example...
  byte PIN = CLK;   //PIN variable is a local variable

  pinMode(PIN ,OUTPUT); //using that local variable

}

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

  // Note: the below if() will always be true as the value
  // of CLK is never change and shouldn't be changed as
  // it will change the pin number of the output

  if (CLK == 1) {
    for (int a = 0; a < 3; a++) {
      digitalWrite(CLK, HIGH);  //this uses the global variable
      delay(1000);
      digitalWrite(CLK, LOW);
      delay(1000);
    }
    //putting exit(0); will actually stop the program
    //remove it
//    exit(0);
  }
  else {
    for (int a = 0; a < 100; a++) {
      digitalWrite(0, HIGH);  //this has a predefined pin no.
      delay(500);
      digitalWrite(0, LOW);   //this has a predefined pin no.
      delay(500);
    }
    //putting exit(0); will actually stop the program
    //remove it
//    exit(0);
  }
}


Can I damage an arduino by setting pins high with no load I have an Arduino project that has 15 different output pins set.  Some are currently attached to devices and others are not.  Will testing my program cause a problem / damage if it sets pints to HIGH that do not have anything connected to them?

Nope, you should be just fine.

Having a pin set to any state while unplugged will not cause any problems with your microcontroller.


Memory usage in AnalogBinLogger of SdFat library The AnalogBinLogger.ino file of SdFat library says the following:

  Each 512 byte data block in the file has a four byte header followed by up to 508 bytes of data. (508 values in 8-bit mode or 254 values in 10-bit mode).
   Each block contains an integral number of samples with unused space at the end of the block.

I was wondering why only 254 values can be stored in 10-bit mode instead of (508*8 bits/ 10 bits ~ 406 values ).

Is this because of the memory being byte-addressable and hence does a 10-bit value take up 2 bytes?
If so, how will a file-reader differentiate between a 10-bit value taking 2 bytes and two 8-bit values?
The AnalogBinLogger.ino says:

  The logger will use SdFat's buffer plus BUFFER_BLOCK_COUNT additional buffers.

BUFFER_BLOCK_COUNT is 1 for the Arduino Uno since it has 2KB of SRAM. Each buffer is 512-byte long. Is SdFat's internal buffer also in SRAM? If I am not wrong, the libraries the program uses and the program code reside in the Flash memory, can SdFat write into a buffer in Flash memory?

how will a file-reader differentiate between a 10-bit value taking 2
  bytes and two 8-bit values?

The file AnalogBinLogger.h, which comes with the example sketch you
mentioned, contains the following:

// First block of file.
struct metadata_t {
  unsigned long  adcFrequency;     // ADC clock frequency
  unsigned long  cpuFrequency;     // CPU clock frequency
  unsigned long  sampleInterval;   // Sample interval in CPU cycles.
  unsigned long  recordEightBits;  // Size of ADC values, nonzero for 8-bits.
  unsigned long  pinCount;         // Number of analog pins in a sample.
  unsigned long  pinNumber[123];   // List of pin numbers in a sample.
};

Thus, the file reader just needs to be aware of the format of this first
block, and read the recordEightBits field in order to know whether
this is 8-bit data or not.

  Is SdFat's buffer also in SRAM?

Yes, that's the only sensible place you could have a data buffer. It's
allocated on the stack, only during the execution of the
logData() function.


Trying to power 100 Arduino's from single power line I'm trying to power up to 100 Arduinos that will be spread across a 25m wall using a single power line.

The idea is each Arduino will have a few a few buttons, leds & an oled screen and will all communicate to a master server using rs485.

====[A0]====[A1]====[A2]====[A3]====[A4]== ... ==[A99]

I've already followed this brilliant post http://www.gammon.com.au/forum/?id=11428 to implement the data connection using an rs485 bus.

However I'm struggling to understand how I could power multiple Arduino's from the one line and not introduce surges/ground loops from the difference in group potential caused by the long power line.

Would I have to isolate each Arduino and rs485 driver? Or is there a simpler solution?

You are already using a differential signalling system that doesn't care about ground levels, so you don't need to worry about that side of things.

As for power distribution - a strategy known as point of load regulation is what you want. That is where you supply a higher voltage (but lower current) power feed to one, or in this scenario more likely a group of, boards and regulate that power down using a switching regulator to a lower voltage (5V) and higher current.

This has the advantage that:

You are only worrying about small groups of Arduinos, not the whole lot
You can use thinner wires to feed in the power to a group
You get less losses from wire resistance at high currents

For 100 Ardunos you may want to have maybe 10 to a group with a 3A switching regulator for each group, giving an average of 300mA per board (depending on your current needs, of course - you may want less per group and more groups to give more average current per board).

In that example you'd have a total output current limit of 30A in 10 sections at 5V. That equates to (P=V×I) 150W. So a 200W 24V power supply would be adequate.

At 24V, 150W would demand 6.25A (plus some more to account for the efficiency of the regulators, so call it 8A - hence the desire for a 200W supply).

For 3A you need at least 24AWG wire - but preferably considerably thicker - maybe 18AWG.  The 8A for the 24V would need minimum 15AWG, preferably bigger - although you don't need that size all the way to the end of your chain of regulators. If you had each regulator wired directly back to the power supply individually that would only need thin wires (absolute minimum 30AWG, which is tiny - though to keep losses to a minimum you'd want more like 20AWG).

So for simplicity and to reduce your wire costs, just stick to one size all the way through so you're buying only one gauge of wire (so you get a bigger discount for buying more).  You could quite easily use:

18AWG direct from the PSU to each POL regulator (24V, 0.8A)
18AWG from each POL regulator to all Arduinos in a group (5V, 3A)

Of course, this is all using numbers plucked out of thin air, and you'd need to adjust it to fit your specific project, but you get the idea - higher voltage to a group, regulate to 5V, then 5V to each Arduino in the group. You don't need to care about grounding etc because you're using RS-485.


Menus not changing when button is pressed TFT 128 x 128 I've just followed a tutorial so that when a button is pressed it goes through a menu. Click once, next slide. Only issue is it isn't appearing on my screen at all. It has uploaded but I'm a total novice when it comes to breadboards etc. Here is my code:

    #include "Ucglib.h" // library for this display
#include <TFT.h> // Hardware-specific library
#include <SPI.h>

#define CS   10
#define DC   8
#define RESET  9

#define up 5
#define down 6

TFT TFTscreen = TFT(CS, DC, RESET);
const int menuSize = 4;
String menuItems(menuSize);

bool upLastState = HIGH;
bool downLastState = HIGH;

int currentMenu = 0;
String temp;
char currentPrintOut(10);

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

  pinMode(up, INPUT_PULLUP);
  pinMode(down, INPUT_PULLUP);

  menuItems[0] = ":)";
  menuItems[1] = ":(";
  menuItems[2] = "X(";
  menuItems[3] = ":S";
  menuItems[4] = ":T";

  //initialize the library
  TFTscreen.begin();

  MenuChanged();
}

void loop() {
  if (digitalRead(up) != upLastState) {
    upLastState = !upLastState;
  }

  if (!upLastState) {
    if (currentMenu > 0) {
      currentMenu--;
    } else {
      currentMenu = menuSize - 1;
    }
    MenuChanged();
  } else {
  }

 if (digitalRead(down) !=downLastState) {
  downLastState = !downLastState;

  if (!downLastState) {
    if (currentMenu < menuSize - 1) {
      currentMenu++;
    } else {
      currentMenu = 0;
    }
    //Serial.printIn(menuItems[currentMenu]);
    MenuChanged();
  } else {
    //Release
  }
 }

   delay(50);
 }

 void MenuChanged() {
  Serial.println(menuItems[currentMenu]);

// clear the screen with a black background
  TFTscreen.background(0,0,0);
  TFTscreen.setTextSize(9);
  TFTscreen.stroke(255,255,255);

  temp = String(menuItems[currentMenu]);
  temp.toCharArray(currentPrintOut, 10);

  TFTscreen.text(currentPrintOut, 40, 32);
}

Edited back to original as per request

You can make things much simpler:

int count = 0;
int button = 5;
int buttonStatus;
unsigned long timer = 0;

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

void loop() {
  buttonStatus = digitalRead(button); // read the button status
  if (buttonStatus == LOW) {
    if (millis() - timer > 200) { //de-bouncing the button
      count++; // increase +1 each time button is pressed
      // clear screen function should be here
      timer = millis();
    }
  }
  if (count > 3){ // if count is bigger than 3 start over.
    count = 0;
    // clear screen function should be here
  }
  switch (count){
    case 1: // if count == 1
    // show charecter :)
    break; // break out of this case!
    case 2:
    // show charecter :(
    break;
    case 3:
    // show charecter :D
    break;
    default: // if none of above cases is valid
    count = 0;
    // clear screen function should be here
  }
  Serial.println(count);
  delay(100);
}

simulate this circuit – Schematic created using CircuitLab

So each time button is pressed count value will increase by 1. you can also add another button to decrease this value...

You might also notice when pushing the button it'll count more than once, you'll also need to De-Bounce the button. tutorial.

Edit: added de-bounce function.


ENC28J60 is not getting ping I bought a new ENC28J60 module and I tried to communicate with the PC through Arduino Uno board.

When I tried to ping the address that I gave in the program it's not getting the ping. Give me some solution.

I used the web server example that is in the example section of Arduino. I even turned off my firewall setting.

The code that I used is:

/*
  Web Server

 A simple web server that shows the value of the analog input pins.
 using an Arduino Wiznet Ethernet shield.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 * Analog inputs attached to pins A0 through A5 (optional)

 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe
 modified 02 Sept 2015
 by Arturo Guadalupi

 */

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 20);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // listen for incoming clients
  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("");
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            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 disconnected");
  }
}

You have an ENC28J60 based module. Your code is for the Wiznet-based module. The two are not interchangeable.

See this: http://nathanhein.com/2013/02/getting-arduino-online-with-an-enc28j60/

Good luck.


Detecting distance moved by accelerometer? I have an accelerometer connected to an Arduino Uno board, is there a way I can detect the distance it this accelerometer moved on each of the 3 axis?

This is normally referred to as Dead Reckoning.  The processes of determining position using known values, such as acceleration.

First we have to relate acceleration, velocity and position mathematically.  Velocity is the integral of acceleration with respect to time:

Similarly, position is the integral of velocity with respect to time:

Here is an explanation that should tie this all together.  However, it appears this explanation goes in the reverse order.  That is using derivatives of position to find velocity.  And derivatives of velocity to find acceleration.  Simply put, finding a derivative is the opposite process of finding an integral.

A final note, this all works well on paper.  In reality Dead Reckoning based only on acceleration does not work very well.  For instance, I believe most vehicle GPS systems tend to use steering and speed if Dead Reckoning is to be used for guidance.

Added later...

Found this web site where someone talks specifically about Dead Reckoning using an Arduino. He is simply using the deltas of filtered acceleration readings:

velocity(i) = velocity(i-1) + acceleration (i)
position(i) = position (i-1) + velocity (i)

But goes on to say accumulated errors causes drift and positioning errors.


Pipe serial dump to SD card file I am using the RFID module to read mifare NFC chips and the library has only methods to send the data to the serial monitor. I need them to be saved to an SD card file. I have been adding custom methods to the library files to return strings that I then write to the SD card but this is a pain; there must be a quicker way to simply pipe all the data automatically but I do not know how to do this in cpp.

Here is an example of the function to dump to serial, that needs to be piped to the file on the SD card.

void MFRC522::PICC_DumpDetailsToSerial(Uid *uid) {
    Serial.print(F("Card UID:"));
    for (byte i = 0; i < uid->size; i++) {
        if(uid->uidByte[i] < 0x10)
            Serial.print(F(" 0"));
        else
            Serial.print(F(" "));
        Serial.print(uid->uidByte[i], HEX);
    }
    Serial.println();

    // SAK
    Serial.print(F("Card SAK: "));
    if(uid->sak < 0x10)
        Serial.print(F("0"));
    Serial.println(uid->sak, HEX);

    // (suggested) PICC type
    PICC_Type piccType = PICC_GetType(uid->sak);
    Serial.print(F("PICC type: "));
    Serial.println(PICC_GetTypeName(piccType));
}

Thanks!

Have the MFRC522 objects remember where you want them to send the output
by adding a data member to the class like this:

private:
    Print &output;

This is a reference to a Print object, i.e. any object where you can
print() or println() to. This reference should be initialized in the
constructor, like this

MFRC522:MFRC522(...other arguments..., Print &my_output = Serial)
: ...other initializations..., output(my_output)
{
    ...constructor body...
}

Notice that, by default, the output is initialiazed as a reference to
Serial. Thus, unless you explicitly ask for the output to go
elsewhere, the class will behave as before.

Last step is to change, in the implementation of the class, every
reference to Serial by output. This is just a global find and
replace.

At this point, the MFRC522 class can be used exactly as before, and it
will behave identically. This means that every user of the library
should be able to use your modified version with no issues. I thus
encourage you to submit the changes to the original author, so that they
have a chance to be incorporated into the canonical version of the
library.

Now, if you want this debugging output to be sent elsewhere, just
provide the destination as the last argument of the constructor:

MFRC522 my_RFID_module(...other arguments..., my_SD_card_file);

As long as the destination is an instance of the Print virtual class
(basically anything you can print() to should be OK), it should work
as expected.


Switch case (millis()) UPDATED I want to create a sketch that counts the days from the moment the "project" start and send and osc message every two days (or more) for 3 weeks. So:

day zero : osc message -> 0
day two. : osc message -> 1
day four : osc message -> 2

etc.
I'm trying to create a state machine to send the messages when the millis reaches a certain time it should print message and so on for the other times.
I'm giving a small example:
I went with @jsotola's suggestion and tried out the BlinkWithoutDelay approach. It seemingly works because I get serial prints around the correct millis() they are printed in 4fold or 3fold the messages.
EDITED CODE:
int daytwo = 25920; // for testing purposes other numbers then the actual millis()
int dayfour = 44400;

void loop() {
  unsigned long currentMillis = millis();   // store current time

  if (currentMillis == daytwo) {
    Serial.println("daytwo");
  }

  if (currentMillis == dayfour) {
    Serial.println("dayfour");
  }
}

Serial output:

    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.926 -> daytwo
    11:04:58.366 -> dayfour
    11:04:58.366 -> dayfour
    11:04:58.366 -> dayfour
    11:04:58.366 -> dayfour

The following code is not very "clean" but easy to understand. Use a variable to hold the day, you have already printed and check in which interval you are. If you change the 2 day interval print a message and set the actDay variable to the number of the day you have already printed; to avoid repprinting it again.
int daytwo = 25920;
int dayfour = 44400;

int actDay = -1;

void loop()
{
  unsigned long currentMillis = millis();
  if (currentMillis < daytwo)
  {
    if ( actDay != 0 )
    {
      actDay = 0;
      Serial.println("dayzero");
    }
  }
  else if (currentMillis < dayfour )
  {
    if ( actDay != 2 )
    {
      actDay = 2;
      Serial.println("daytwo");
    }
  }
  else
  {
    if ( actDay != 4 )
    {
      actDay = 4;
      Serial.println("dayfour");
    }
  }
}


How to use this 3-pin slide-switch? I purchased these slide switches recently because I want to use them in my project:

But I don't know what to connect up the three pins to and I can't find any information about them online. Nor can I find sample code. Can someone show me how to wire them up and provide sample code please? I just want to be able to check their state and save it as a boolean variable.

Since it has two possible positions, and three pins, you have a connection between pin 1 and 2 when position 1 is selected, and between pin 1 and 3 when position 2 is selected.
As BSF comment below, the middle pin is common. This means it will be connected to the outside pins depending on where the switch is moved towards.

However, you always can verify this, in the following way:

To find out which is pin 1, pin 2 and pin 3, use a multimeter. Set it to continuity mode, or if you don't have that mode, to resistance mode, and put the red/black probes to two random pins. Check if the resistance is 0, in that case you know those two pins will be connected when position 1 is selected. If there is resistance, try other pins with the probes, until you know which are connected.

Than switch the position, and do it again.

Instead of a multimeter you also can 'hardwire'  it to e.g. 5V -> pin 1, pin 2 -> resistor of 220 ohm -> LED -> GND
And change pin 1 and pin 2 until you found which pins connect for which positions.

To use it for you Arduino, check for a normal simple switch example, but these are two in one, one for each position.


Trying to control DC motor speed with PID i'm trying to control a DC motor with PID. I have already made a code where i control the motor with an ultrasonic sensor (for distance) but now i need to run the motor at a given RPM (the Output). I did a lot of resarch and found that i will have to use the PID Library. But with my existing code i'm not sure if it's going to work. I know that i will have to modify PWM values by the Input on the analogWrite(). Can you enlight me on this PID? Here is my code:

int enableBridgePin = 10;
int forwardPin = 11;
int backWardPin = 9;
int tickPin = 2;
const int trig = 5;
const int echo = 6;

int dt;
int distance;

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

  digitalWrite(forwardPin, LOW);
  digitalWrite(backWardPin, LOW);

  digitalWrite(enableBridgePin, HIGH);
}

void loop() {
  analogWrite(enableBridgePin,255);

  digitalWrite(forwardPin, HIGH);
  digitalWrite(backWardPin, LOW);
  Serial.println(distancefonction(dt,distance));

  if (distancefonction(dt,distance)<15 && distancefonction(dt,distance)>7){
    slowdown();}
}

int distancefonction(int dt, int distance) //function to show distance

void slowdown(){
  for(int i=255;i>=0;--i){
      analogWrite(enableBridgePin,i);
      delay(10);}
   Serial.println("SLOWDOWN");
}

PID- or any similar control needs

set point
actual value
controlling variable (your PWM value)

The difference between set point and actual variable and its change over time are combined to calculate the controlling variable in order to minimize that difference.

Control theory in general is too complex to answer the "how to" here in general.

Besides measuring the actual value you also need knowledge about the behavior of your system: e.g. If you change the PWM value from 50 to 100, how much and how quick will the motor speed change? Even the response form over time will affect the optimal parameters for your control loop. It's called (feedback) loop because any change of the PWM value will change that difference and lead to a different new value of the controlling PWM value again (Allowing for instable behavior in case of bad controlling parameters).

Getting the actual value is your first task. How your distancefonction affects the desired value (set point) might also need more clarification...


Genuino UNO 5V pin is reading 0.3V So I was trying to set up the LCD screen that came with my Genuino starter kit when I noticed that the board screen did not power on at all, unlike a few days ago when it worked.

In order to verify that the UNO was delivering power I simply connected an LED in series with a 220Ω resistor, between the 5V and ground pins. The LED did not power on.

I then, with the UNO still connected over USB, measured the voltage between across the resistor and LED and found it to be around 0.2-0.3V. Going further, reading the voltage between the 5V and ground solder connections on the back of the board and the reading is about the same.

I can power the LED from a digital pin that I set to HIGH, the issue seems to just be with the 5V pin.

Is there anything simple that I am missing (I hope there is) or is there likely a problem with my board? If there is a problem, could I use a digital pin to power a larger circuit such as that with an LCD or would the current supplied be too low?

There are a couple more places you can sample the 5V signal, see the photo here:

On the right, on the ICSP header, the pin marked VCC is also connected to the 5V signal. Try testing that.

(The other one is pin 2 of the ICSP interface for the USB chip, but the one on the right should be adequate for testing).

I don't know why you are mucking around with LEDs and resistors, just put your meter between Gnd and 5V.

I find sometimes that the hookup cable has failed, try testing that (or try with a different cable).


Can I connect an Arduino wifi module directly to my android phone? I would like to use my arduino even where there's no wifi router. I've only found people saying that it needs to connect to a router, but isn't the phone like a router when it's in tethering mode? Do I still need a mobile internet connection or can I do it directly?

A phone running in wifi tethering (mobile hotspot) mode is no different to a wifi access point or router. So yes, you can use that.

Chances are though that you will need a mobile internet connection in order to activate mobile hotspot mode in the first place.


How can I use an arduino as an intermediary step between my PC and a LED strip? Goal
My end goal is to have a NeoPixel LED Strip that I can control via software on my PC, with various automatic modes and manual control. Right now all I have is the idea and some research done, because I don't want to order parts if I can't get this working. That means no arduino, no leds, no power supply, and no experience with any of them.
What I know so far
I know enough Java to set up the software that would output some array of colors, including manual control and automatic modes like flashing/fading/etc.
From the research I've done, I'll need a microcontroller to make sure I output exactly the right signal(?) for my LED strip. Adafruit recommends an Arduino one or Arduino mega, which meet the timing requirements and have libraries available for use with NeoPixel products. Physically connecting the Arduino to the LED seems fairly easy.
What I don't know
Hardware and software wise, how can I transfer an array of color values from a java program to the Arduino?
This involves getting the data to a port on my PC, getting that to the Arduino via some wire/s, and making sure it's readable. I'd imagine sending an entire array to whatever input the arduino has would be difficult. Perhaps I could send a single color at a time together with an index, but that would probably add delay to the system.
On the software side, how do I set up the arduino to "forward" the input from my PC to the LED strip?
I'm not very comfortable with C, so this could be tough. How will I receive the data input? How easy and fast is it to turn that into output for the LED strip? What if I don't convert and output an update before I receive another one?
EDIT: It seems there are libraries available to deal with the actual data transfer, and encoding/decoding shouldn't be too hard after some thought. I think I'm going to use usb4java for communication between my PC and an Arduino, and roll my own mini "protocol" to convert. Then I'll use the NeoPixel libraries for the Arduino.

You should take a look at FadeCandy if you are dealing with NeoPixel LED Strip. Ived used that in conjunction with Processing (which is JavaBased) to send stuff into a 16x16 NeoPixel display. (4 8x8 matrix's linked together)
Fadecandy uses Open Pixel Control
http://openpixelcontrol.org/

I've got an example of it on youtube... https://www.youtube.com/watch?v=rz_U4dzjp1s&feature=autoshare


rfm69 on M0 Express... init() doesn't work I have already connected succesfully the rfm69 on my Feather M0 Express... but I cannot do it again.
The connections are (in the order of the rfm69):

Vin -> 3V
Gnd -> Gnd
En  -> (nothing)
G0  -> 9
SCK -> SCK
MISO -> MI
MOSI -> MO
CS  -> 10
RST -> 6

The code of the setup is
#include <SPI.h>
#include <RH_RF69.h>

#define RFM69_CS      10
#define RFM69_INT     9
#define RFM69_RST     6
#define LED           13

// Singleton instance of the radio driver
RH_RF69 rf69(RFM69_CS, RFM69_INT);

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

  Serial.println("Feather RFM69 RX Test!");
  Serial.println();

  // manual reset
  digitalWrite(RFM69_RST, HIGH);
  delay(10);
  digitalWrite(RFM69_RST, LOW);
  delay(10);

  if (!rf69.init())
    //***********************************
    Serial.println("init failed");
  else
    Serial.println("init ok");

  // Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM (for low power module)
  // No encryption
  if (!rf69.setFrequency(434.0))
    Serial.println("setFrequency failed");
  else
    Serial.println("setFrequency ok");

  // If you are using a high power RF69 eg RFM69HW, you *must* set a Tx power with the
  // ishighpowermodule flag set like this:
  //rf69.setTxPower(14, true);

  // The encryption key has to be the same as the one in the client
  uint8_t key[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
                    0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
  rf69.setEncryptionKey(key);

#if 0
  // For compat with RFM69 Struct_send
  rf69.setModemConfig(RH_RF69::GFSK_Rb250Fd250);
  rf69.setPreambleLength(3);
  uint8_t syncwords[] = { 0x2d, 0x64 };
  rf69.setSyncWords(syncwords, sizeof(syncwords));
  rf69.setEncryptionKey((uint8_t*)"thisIsEncryptKey");
#endif
  Serial.println("Fin du Setup");
}

But during the execution, the program stops at //**************************
I do not understand.
Can somebody help me?
Thanks a lot and merry Xmas

The "init failed" do not appear. Everything stops at "//******".
I have compared to another RFM69 program.
I have added a line " digitalWrite(RFM69_RST, LOW);" at the begining of the "//manual reset" and it works now.
the sequence
digitalWrite(RFM69_RST, LOW);
digitalWrite(RFM69_RST, HIGH);
delay(10);
digitalWrite(RFM69_RST, LOW);
seems to be more efficient.
... it remains a few mysteriuos for me.
Thank you


Use pointer in calculation results in error I'm building a project to measure/track flyball dog races.
The dogs timings are measured by photoelectric sensors at the start/finish line of the racing lane.
I have most of my code working (available on github) but I'm having some difficulties in handling very short crossings of dogs. Since I cannot realistically run a real race at home next to my development machine :-), I'm trying to build a simulator class which gives the triggers that would normally come from my photoelectric sensors.

I have a RaceHandler class which has the following in its header file:

class RaceHandlerClass
{
 public:
   long* lRaceStartTime = &_lRaceStartTime;

 private:
   long _lRaceStartTime;
}
extern RaceHandlerClass RaceHandler;

As you can see I made a public pointer lRaceStartTime which points to the private _lRaceStartTime member variable.
This might seem stupid/strange, but it really should a private member variable, I just want to 'temporarily' make it publicly available, so that I can use it in a temporary 'simulator' class to simulate a race towards my code.

Then I want to use this public pointer in the Simulator class like so:

long* lRaceStartTime = RaceHandler.lRaceStartTime;
long lRaceElapsedTime = micros() - lRaceStartTime;

However I get the following error when trying to compile this:

  error: invalid operands of types 'long unsigned int' and 'long int*'
  to binary 'operator-'

I'm afraid my c++ knowledge ends here and I have no clue what I should do different to fix this...
Any help would be greatly appreciated!

Try this:

long* lRaceStartTime = RaceHandler.lRaceStartTime;
long lRaceElapsedTime = micros() - *lRaceStartTime;

You assigned the pointer to lRaceStartTime on the first line, but on the second line you are subtracting the pointer from micros() which returns an unsigned long.  You need to dereference the pointer before subtracting. Also you might consider making all your longs unsigned to match the return type of micros() http://arduino.cc/en/reference/micros