Where do class files go in Sloeber Eclipse project? I'm attempting to create a new Arduino project using Sloeber (Eclipse). Assume it's a newly-created project whose main entry file is ".\ArduinoMainClass.ino"

Now... assume I want to create a half dozen new classes:

ExecutionState-- a C++ class that's intended to be functionally equivalent to a Java Interface. If you're wondering, I'm attempting to implement the 'State' pattern.
GoodState, BadState, UglyState, WeirdState-- C++ classes that all extend ExecutionState. If they were Java, they'd technically be implementing an interface... but since this is C++ and I'm still taking baby steps, for now ExecutionState is just a class with one method that does nothing, and all of THESE classes override it to do the actual work.
StateContainer-- a C++ class whose only purpose in life is to hold single instances of GoodState, BadState, UglyState, and WeirdState. If this were Java, they'd be Singletons... GoodState (and the others) would have something like:

    private static ExecutionState instance = new GoodState();
    // ...
    public static ExecutionState getInstance() { return instance; }

... but it's obviously not Java,  and I'm nowhere close to knowing enough about C++ to properly implement static singletons yet, so for now, I'm just going to create an instance of StateContainer to create and hold those single instances.

So... I now have Sloeber/Eclipse loaded, and I've created my project. If this were Java, I'd create a subdirectory like .\src\java\com\packagename\executionstate and stick the .cpp and .hpp files for ExecutionState, GoodState, BadState, UglyState, WeirdState, and StateContainer in it, and add "include com.packagename.executionstate.*" to it.

I know C++ namespaces have no direct connection to directory names
I've gotten the impression that "Arduino"-ish C++ auto-generates the #include files for things it regards as libraries. I have a hunch that I probably want to put all of the classes I mentioned above in a directory somewhere and present them to the IDE as an Arduino "library" so they'll all get implicitly included in one go within the .ino file.
I'm completely confused about what I need to #include in the classes I mentioned above so they can mutually find each other... and whether those #includes rightfully belong in the .hpp or .cpp files.

So... getting back to the big picture. If my project is in c:\users\moi\Documents\Slober-workspace\FirstSloeberArduinoApp...

Where do the .cpp and .hpp files for ExecutionState, GoodState, BadState, UglyState, WeirdState, and StateContainer go? (Assume I'd be inclined to put them all in a directory named "executionstates" somewhere in the project's directory hierarchy, but I'm not sure where that exact directory should go).
What #includes do I need to put in ExecutionState, Good/Bad/Ugly/WeirdState, and StateContainer... and do they go in the .hpp file, or the .cpp file for their respective class?
What do I have to do so the .ino file can find StateContainer?

In case you're totally confused at this point, my actual .ino file will look something like this:

void setup() {
    // executionStates is a global variable declared higher up
    executionStates = new StateContainer();
    executionState = executionStates.getGoodState();
    // StateContainer's constructor itself creates instances of the various subclasses of ExecutionState,
   // and passes references to itself to their constructors so they can
   // get the references to the others states as they need to return them.
}

void loop() {
    executionState = executionState->doSomething();
    /* executionState holds a pointer to an instance of an ExecutionState subclass.
       Each time doSomething() executes, it returns a pointer to its new state
     */
}

... and in reality, there will be dozens of subclasses of ExecutionState, each representing a unique execution state.

With Sloeber Eclipse plugin the ino files go to root of the project and the cpp, c and h files can be in root or in subfolders. example:

Folders created by Sloeber: core subfolder is a virtual folder with links to Arduino core files and variant files of the selected board. libraries folder is a virtual folder with links to libraries selected for the project. Release folder contains the generated make file, the .o files and the resulting elf, hex, bin files. (And sloeber.ino.cpp is a file generated by Sloeber)

Project folders: data folder in example picture is a convention for a folder with esp8266 SPIFFS files. utility is a subfolder with additional source files of the project.


Broken serial connection corrupting Arduino values I have a problem with my homemade fan speed controller powered by an Arduino Nano, which reads a value from Serial (Arduino serial monitor, or Processing sketch) and uses the 0~255 value to set a variable fanspeed1 to set a PWM pin to control the fan speed.

The problem is when I close the Processing sketch, or the Arduino serial monitor, fanspeed1 is changed to max value (the fan speeds up to full speed).

I would like to send serial to set the value and then close the serial monitor, or Processing sketch and the value of fanspeed1 should not change.

If I need to post some code I can simplify my sketch down to a send serial, receive serial, make pin pwm = serial(0~255), but I am guessing there is a simple solution to this unfindable with my googling.

Help please, these fans need controlling...

You could consider writing/reading the value to/from the EEPROM.
http://arduino.cc/en/Reference/EEPROM
This allows the board to be reset, or even turned off, and retain the value previously set.  What you would be doing is saving the value to the internal memory of the Arduino.  This is resettable and persistent over a "reboot".
Granted, there is a limited number of writes you can do, but that number is high enough (~100k) that you will probably wear out the fan before the EEPROM sector dies.

Syntax
EEPROM.write(address, value)
EEPROM.read(address)
EEPROM.update(address, value)

For objects:

EEPROM.put(address, data)
EEPROM.get(address, data)


Arduino Pin won't go LOW I have something strange going on with an output. When the following code is called the LED goes on, but it stays on, there is no blinking. If I comment out the set HIGH statement the LED never comes on (as expected).

#define devicePin 10

void setup() {
  pinMode(devicePin, OUTPUT);
}

void loop() {
    digitalWrite(devicePin, HIGH);
    delay(2000);
    digitalWrite(devicePin, LOW);
}

Could I have damaged the board in some way?

After you drive the pin low, you immediately go to the beginning of the loop and set the pin high (if you have an oscilloscope, you might see a very short downward pulse).
So, add another delay after digitalWrite(devicePin, LOW).


Delete line from text file In order to make an algorithm work, I'd like to delete the first line of a text file. I'm having a hard time finding an example for that though. I was thinking that there should be the possibility to delete up to a \n. Could you point me to a solution?
Oh, I'm using a standard Arduino Uno

Thank you

What you can do is:

opening a file (to read)
opening a new file (to write)
since a line can be long (more than arduino's memory), it's best to read it character by character, thus:
use a boolean to denote when to start removing a line (set to e.g. Remove = TRUE)
For every character you read:

If Remove is TRUE, don't write to the output file, otherwise write it
If the character is \n or \r (check how line ends are), set the boolean to False (e.g. continue writing)

Remove file to read
Rename written file


Is Arduino stable enough to use it for a door lock? I want to replace my door lock with an one made with an Arduino and a servo, but I'm not sure if the platform is stable enough to use it for something like this.

If I do everything right (code, connections, constant power), could I trust in this?

I'm not sure if the platform is stable enough to use it for something like this.

Absolutely it is. As I describe in my post about an RFID door lock I use a Uno (and some additional parts) to unlock my door.

Since writing that I improved the software as described here so you can reprogram the valid list of cards "on the fly" (without uploading new code) as the valid cards are stored in EEPROM.

My system has been operating for over 5 years without any problems, except once when there was a brownout in the area and I had to power cycle the system (possibly the RFID reader failed and not the Arduino).

My system "fails shut" so it keeps the door locked in the event of a power failure. However I have alternate ways of leaving the building in the event of a power failure combined with a fire.

You are talking about a servo rather than an electric strike. That is likely to be the weak point, and not the Arduino as such. You would need to ensure it was powerful enough to do whatever-it-is you are planning to do, and that it had suitable drivers (eg. MOSFET or driver board).

My system gets used dozens of times each day. We never have a problem with it.


What will use less memory, an array or if ... else? I'm trying to make my sketch smaller. Right now I use an array for the AM/PM part of my time display. My thinking is this makes it easy to change the formatting:

char* ampms[]= {"am", "pm"};

void loop() // run over and over again
{     //get time from RTC
     getDateDs1307(&second, &minute, &hour);

      //change to 12 hour format.
      if (hour>12) { hr = hour - 12; ampm=1; } else { hr = hour; }

      //add leading 0 for hours
      if (hr<10) { lcd.print("0"); }

      //print hour in 12 hour format.
      lcd.print(hr, DEC);

      lcd.print(":");

      //add leading 0 for minutes
      if (minute<10) { lcd.print("0");}

      //print minutes
      lcd.print(minute, DEC);

      //print am or pm using array.
      dataFile.print(ampms[ampm]);
}

I could do this instead:

void loop() // run over and over again
{     //get time from RTC
     getDateDs1307(&second, &minute, &hour);

      //change to 12 hour format.
      if (hour>12) { hr = hour - 12; } else { hr = hour; }

      //add leading 0 for hours
      if (hr<10) { lcd.print("0"); }

      //print hour in 12 hour format.
      lcd.print(hr, DEC);

      lcd.print(":");

      //add leading 0 for minutes
      if (minute<10) { lcd.print("0");}

      //print minutes
      lcd.print(minute, DEC);

      //print am or pm using array.
      if (hour>12) { lcd.print("am");} else {lcd.print("pm"); }
}

No more am/pm array. But, I have to add an if... is one better than the other for memory? Why?

As Ignacio says, if the compiled size is the same both ways, look for something else.  (But note that having the constants in flash memory (program memory) may still use about the same amount of RAM, and typically will take more program space.)

When I compile the code you showed (together with minor additions like declaration of variables) I show the array method using 4 bytes less code and 5 bytes more RAM than the if method, so there are tradeoffs.

You can replace the clunky if statement and its two lcd.prints  with the following:

      lcd.print(hour>12? "am" : "pm");

Note that that line retains the two bugs that your if statement has, but it produces them more compactly. :) [One error is that your if statement prints pm for hours 0 through 12 and am for hours 13 through 23.  Another error is that it prints zeroes instead of twelves for the hours after midnight and noon.  More properly, a program should print like 12:xx am during hour 0 of the day, and like 12:xx pm, 1:xx pm, ... 11:xx pm during hours 12 through 23.]

Also note that as Gerben mentions, moving the "am" and "pm" strings into program memory via

lcd.print(hour>12? F("am") : F("pm"));

saves 6 bytes of RAM.  However, that improvement in RAM usage is offset by 74 additional bytes of program space! The following saves 6 bytes of RAM while increasing program size by only 12 bytes so may be preferable:

lcd.print(hour>12? 'p' : 'a');
lcd.print('m');

The following lines of C can replace much of the code you showed.  However, the printf library uses about 1300 bytes of program space, so the following compact-source-code approach cannot be recommended unless you are already loading some printf functions.  It replaces the lines from if (hour>12) { hr = hour - 12; } ... to the end with

enum { bufsize=8 };
char buf[bufsize];
snprintf (buf, bufsize, "%02:02%cm", hour%12, minute, hour>12? 'p' : 'a');
lcd.print(buf);


scroll text through multiple i2c connected dot matrix displays I have 4 dot matrix displays, every one of them connected to an i2c and accessible with 0x70, 0x71, 0x72 and 0x73. All these work just fine when I address them apart. What I want to achieve is a scrolling text throughout all 4 displays. How can I do this? Are there any libraries around that already do this? (I did not find any).

Basically, this is my code:

#include <Wire.h>
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"

Adafruit_8x8matrix matrix[4];

void setup() {
  Serial.begin(9600);
  Serial.println("4x(8x8) LED Matrix Test");
  matrix[0].begin(0x70);
  matrix[1].begin(0x71);
  matrix[2].begin(0x72);
  matrix[3].begin(0x73);
}

This is what I found behind the link @mikael-patel posted, and with a little configuration it does exactly what I want. Basically the scroll()-method handles anything neccessary.

#include <Wire.h>
#include "Adafruit_LEDBackpack.h"
#include "Adafruit_GFX.h"

#define NUM_MATRICES 2
Adafruit_8x8matrix matrix[NUM_MATRICES];

void setup() {
  Serial.begin(9600);
  Serial.println("8x8 LED Matrix Test");

  for(uint8_t m=0; m<NUM_MATRICES; m++) {
    matrix[m].begin(0x70 + m);
    matrix[m].clear();
    matrix[m].setTextSize(1);
    matrix[m].setTextWrap(false);  // we dont want text to wrap so it scrolls nicely
    matrix[m].setTextColor(LED_GREEN);
  }
}

void loop() {
  scroll("Hello World!");
}

void scroll(char* text) {
  int scrollPositions = (strlen(text) * 8) + 32;

  for (int x=(8 * NUM_MATRICES); x>=-scrollPositions; x--) {
   for(uint8_t m=0; m<NUM_MATRICES; m++) {
    matrix[m].clear();
    matrix[m].setCursor((x - (m * 8)), 0);
    matrix[m].print(text);
    matrix[m].writeDisplay();
   }
   delay(80);
  }
}


Is it possible to burn a bootloader to an ATTiny85 with USB TTL and avrdude? I have:

An Digispark clone (with no Arduino bootloader)
A USB -> TTL serial device
A development breadboard
Avrdude

I want to burn the micronucleus bootloader to the chip.

Is this possible, are there instructions?

ISP programmer is in the post but I'm not expecting it for 3 weeks.

No, you can't because a USB -> TTL serial device is not made for that. You CAN however use an Arduino Uno to burn a bootloader to another Atmel micro, including the Attiny85.

Now you may ask, can you use the Digispark in place of the Uno (and thus burn more Attiny chips). The answer is a qualified yes.  Another Arduino can do this -- search the web and find many examples.

You might (?) even adapt that sketch from the Uno to the Digispark (saving the cost of an Uno). I can't advise further and you're looking at a rabbit hole of possible issues.

Sparkfun does sell a chip which can perform boot-loading using minimal components:
https://learn.sparkfun.com/tutorials/how-to-install-an-attiny-bootloader-with-virtual-usb


Arduino as a custom I2C slave device I'm trying to interface with a master I2C device that doesn't exactly follow the normal I2C protocol.

The only difference really is in the read request. A "normal" I2C read operation looks like this ([M]aster, [S]lave):

S | SLA+R | ACK | Data | Ack | Data ...some number of bytes... Nack | P
^M  ^M      ^S    ^S     ^M    ^S                              ^M     ^M

But this device expects to do a read like this:

S | SLA+R | ACK | Data | Ack | Data | Ack | Data | Ack | P
^M  ^M      ^S    ^M     ^S    ^S     ^M    ^S     ^M    ^M

Essentially a read request goes to the slave device, and then the master sends an 8-bit register address, and then the master expects 2 data bytes back from the slave with the Master responding with an ACK on both.

I've been able to set up a master device to do this style of protocol pretty easily by just manipulating the I2C registers directly. But I can't seem to find a way to get the slave device to accept that it is going to receive a data byte after it has been selected by a SLA+R, which leads to a bus contention problem and the slave not giving the master an ACK.

Is this possible to do with the built in I2C hardware on the Atmel chips? Is there any alternative if it can't (bit-banging)?

I'm missing something on the bus operation. Pretty much whenever I get NAK'd I know I need to redo the operation. On the i2c bus it should be an ACK'd or NAK'd on every byte.

Usually you send the address of the device then the command. So the master initially sends the address, which is ACK'd and then the master sends the command that it wants executed. Your diagram has the slave answering when it's the master that's required to give it an operation?

Here's a good document on it... :)

Philips I2C Document


Using a photo resistor to detect objects of a certain color I am trying to build a robot that detects cubes of a certain color, and later picks them up.

I was planning to use a camera and process the image, but I was told that Arduino is not capable of image processing.

Now, I was thinking that I could maybe use a photoresistor that is enclosed by a green light filter sheet (so that only the light of a certain color can pass). Thus, if my robot is facing a cube of the color I want, the photoresistor should detect this.

Is this at all possible? I know how filters work in theory, but I have never used one before.

If not, is there another way to try to detect color using an Arduino?

Use a TCS230 photo sensor and a 6500K light source to color correct your objects.

This hookup will get you started

This sketch, courtesy of Best-Microcontroller-Projects  will get you going.  Read the tutorial and dont forget to calibrate.

//
// Detect colors using TCS230.
//

// Arduino uno pins for control of TCS230
#define TCS320_OE 7
#define TCS320_S0 10
#define TCS320_S1 11
#define TCS320_S2 2
#define TCS320_S3 3
#define TCS320_OUT 4

#define variance 50  // Acceptable detection error 2%.

#define SEL_RED  \
   digitalWrite(TCS320_S2,LOW);digitalWrite(TCS320_S3,LOW)
#define SEL_GREEN \
   digitalWrite(TCS320_S2,HIGH);digitalWrite(TCS320_S3,HIGH)
#define SEL_BLUE \
   digitalWrite(TCS320_S2,LOW);digitalWrite(TCS320_S3,HIGH)
#define SEL_CLEAR \
   digitalWrite(TCS320_S2,HIGH);digitalWrite(TCS320_S3,LOW)

#define TWO_PER \
   digitalWrite(TCS320_S0,LOW);digitalWrite(TCS320_S1,HIGH);

#define debug(a) Serial.println((a));

#define NUMCOL 5

// int RGB[NUMCOL][3]; // Five colors with 3 elements.
// Array of NUMCOL strings len 10. 11 for null.
// char colname[NUMCOL][11];

// Typical values for 2% dividers (set variance to 50).
int RGB[NUMCOL][3]={
   {248,647,393},
   {188,261,265},
   {404,710,546},
   {506,493,304},
   {930,1199,837},
};

char colname[NUMCOL][11]={
"red",
"yellow",
"brown",
"blue",
"black",
};

////////////////////////////////////////////////////////////////
void setup() {

   pinMode(TCS320_OE,OUTPUT);
   pinMode(TCS320_S0,OUTPUT);
   pinMode(TCS320_S1,OUTPUT);
   pinMode(TCS320_S2,OUTPUT);
   pinMode(TCS320_S3,OUTPUT);
   pinMode(TCS320_OUT,INPUT);

   TWO_PER;

   digitalWrite(TCS320_OE,LOW); // On always.

   Serial.begin(115200);
   Serial.println("TCS230 color detector");
}

////////////////////////////////////////////////////////////////
unsigned long get_TCS230_reading(void) {
  unsigned long val;
  noInterrupts();
  val = pulseIn(TCS320_OUT,HIGH,20000); // 2000us=2ms  2Hz min.
  interrupts();
  return val;
}

static int clr,red,green,blue;

////////////////////////////////////////////////////////////////
uint16_t detect(void) {
   unsigned long val;

    SEL_RED;
    red = val = get_TCS230_reading();
    Serial.print("RED: "); Serial.print(val);

    SEL_GREEN;
    green = val = get_TCS230_reading();
    Serial.print(" GREEN: "); Serial.print(val);

    SEL_BLUE;
    blue = val = get_TCS230_reading();
    Serial.print(" BLUE: "); Serial.print(val);

    Serial.print(" \n");
}

////////////////////////////////////////////////////////////////
int withinEQ(int c, int xl, int xh) {
   if (c>=xl && c<=xh) return 1;
   return 0;
}

////////////////////////////////////////////////////////////////
// Compare a value to a value and variance.
int compare(int c, int v, int err) {
int xh=v+err, xl=v-err;
   if (withinEQ(c,xl,xh)) return 1;
   return 0;
}

////////////////////////////////////////////////////////////////
void loop() {
uint8_t chr,i,fnd;

   if (Serial.available()>0) {

      chr = Serial.read(); // Consume.

      // Find color match.
      detect();
      fnd=0;
      for (i=0;i<NUMCOL;i++) {
     if ( compare(red,RGB[i][0],variance) &&
          compare(green,RGB[i][1],variance) &&
          compare(blue,RGB[i][2],variance)
        ) { // Found
          Serial.print("Col is :");
          Serial.println(colname[i]);
          fnd=1;
          break;
        }
      }
      if (!fnd) Serial.println("NOT Found");
   }
}


ESP32 + Fastled + WS2801 I'm using the ESP32 DevkitC board with Fastlib and a WS2801 LED strip.
The LED strips works fine, i connected it properly (sometimes all LEDs are on, no flickering).

I Connected the light strip's Data cable (blue) to GPIO16 and Clock cable (red) to GPIO17.
Compiling works but at first shows this error:

"No hardware SPI pins defined.  All SPI access will default to bitbanged output"

When the script starts, only the first 3 LEDs are glowing in light blue (instead of blinking) - here's my code:

#include <FastLED.h>

// How many leds in your strip?
#define NUM_LEDS 42

// For led chips like Neopixels, which have a data line, ground, and power, you just
// need to define DATA_PIN.  For led chipsets that are SPI based (four wires - data, clock,
// ground, and power), like the LPD8806 define both DATA_PIN and CLOCK_PIN
#define DATA_PIN 16
#define CLOCK_PIN 17

// Define the array of leds
CRGB leds[NUM_LEDS];

void setup() {
      // Uncomment/edit one of the following lines for your leds arrangement.
      // FastLED.addLeds<TM1803, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<TM1804, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<TM1809, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
      // FastLED.addLeds<APA104, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<UCS1903, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<UCS1903B, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<GW6205, DATA_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<GW6205_400, DATA_PIN, RGB>(leds, NUM_LEDS);

      // FastLED.addLeds<WS2801, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<SM16716, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<LPD8806, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<P9813, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<APA102, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<DOTSTAR, RGB>(leds, NUM_LEDS);

       FastLED.addLeds<WS2801, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<SM16716, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<LPD8806, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<P9813, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
      // FastLED.addLeds<DOTSTAR, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
}

void loop() {
  // Turn the LED on, then pause
  leds[0] = CRGB::Red;
  FastLED.show();
  delay(500);
  // Now turn the LED off, then pause
  leds[0] = CRGB::Black;
  FastLED.show();
  delay(500);
}

Any ideas what's wrong?

This is hard to debug from afar...

Your sketch looks correct (hardly surprising, since it's just the Blink example). But I'd try to use IO18/SPI_CLK for clock and IO23/SPI_MOSI for data, as these are the hardware SPI pins of the ESP32. It might very well be that using these pins removes the warning about hardware SPI.

As I don't know all the variants of a WS2801 strip... is it maybe one of those strips that runs at 12V and can only be cut every three LEDs? This would explain why there are three LEDs lighting up instead of one (because then there would be one chip for three LEDs -- in other words, each "pixel" in your leds array corresponds to three physical LEDs)

Then there might be a problem with the voltage output of your ESP32 board. The ESP is running at Vcc=3.3V. The chips of the strip are running at Vcc=5V and expect 5V on their inputs. A logical 1 is assumed when the input in question is 0.7 * Vcc, i.e. the input signal may not be less than 3.3V. Now imagine that the power regulator on your ESP board drives the ESP at a teensy bit less (e.g. at 3.25V) and the power supply for the strip outputs a teensy bit more (e.g. 5.1V) -- suddenly, a logical 1 from the ESP is at 0.637 times the strips' Vcc and therefore in the undefined limbo between 0.3*Vcc (highest definition for logical 0) and 0.7*Vcc (lowest definition for logical 1). A level shifter module would help here to increase the ESP's output signal voltage (costs a few cents when ordered directly from China).

Then, at last, are you sure that the color order of the strip is RGB (as stated in your setup line)? I've seen more strips using GRB or BGR... which would explain why you see blue instead of red.


How to alter joystick values with Arduino Uno? I'm trying to use an Arduino Uno to read values from a 2-axis joystick analogue input, and alter these values. Rather than the true joystick values, I arithmetically convert the values at neutral to range between 0 - 5, with 'neutral', i.e. when the joystick isn't being pushed, being at roughly 2.5 for each axis. These joystick values currently output to a live text file, to be graphed in real-time. One function I'm trying to implement is that when the joystick value is greater or less than a defined value (e.g. in the code, greater than 4.55, or less than 0.5)  that the Arduino sets that point to be the new 'neutral' position (i.e. 2.5), however my code at the moment isn't working and I'm not sure how to go about attempting this.

Any insight would be most appreciated!

Cheers

const int buttonPin = 2;
const int successPin = 13;

int buttonState = 0;

void setup()
{
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
pinMode (buttonPin, INPUT);
pinMode (successPin, OUTPUT);
while (digitalRead(buttonPin) == LOW) {};
}

void loop () {

int sensorValueY = analogRead(A0);
int sensorValueX = analogRead(A1);

//arithmetic operation that maps output values from 0 - 5 instead of 0 - 1023
float voltageX = sensorValueX * (5.0 / 1023.0);
float voltageY = sensorValueY * (5.0 / 1023.0);
Serial.print(voltageX);
Serial.print(" , ");
Serial.print(voltageY);

if (voltageX >= 4.55) {
  voltageX == 2.5;
  successPin==HIGH;
  delay(1);
  successPin==LOW;
}

if (voltageX <= 0.5) {
  voltageX ==2.5;
  successPin==HIGH;
  delay(1);
  successPin==LOW;
}

if (voltageY >=4.55) {
  voltageY == 2.5;
  successPin==HIGH;
  delay(1);
  successPin==LOW;
}

if (voltageY <= 0.5) {
  voltageY ==2.5;
  successPin==HIGH;
  delay(1);
  successPin==LOW;
}
Serial.println();

}

if (voltageX >= 4.55) {
  voltageX == 2.5;
  successPin==HIGH;

The last two lines (and all similar ones later) are wrong. == is for comparing, = is for assigning. So change it to:

if (voltageX >= 4.55) {
  voltageX = 2.5;
  successPin = HIGH;

You did that in a lot of places, so fix that up and get back to us.

const int successPin = 13;
...
  successPin = HIGH;

Assuming you fix the compare to an assign you will get an error message here. You define successPin as 13, and then try to change it to 1 (which is what HIGH is defined as). Do you mean, to write to that pin? Like this?

digitalWrite (successPin, HIGH);

You will need to change all those as well. And if you are hoping to see an LED on the pin flash, 1 ms is quite a small interval.


Questions about the Arduino Micro PCB I'm planning on integrating an Arduino Micro in the circuit of a small project of mine (USB gamepad). The whole thing will use USB for power and data transfer (between the board and the computer). Before I move on with prototyping, I need to clear up some questions I have about the Arduino Micro schematic (picture included for reference):

Since I'll be powering off of USB, I won't the 5 and 3.3 V regulators or the 5 V Selector (top-right in picture). Am I correct?
For the USB Micro header, does the schematic refer to any particular header (doesn't seem so to me), or will any generic one work? And what are the six pins on the right side (SH1/S1, SH2/S2, SH3/S3, SH4/S4, SH5/S5, SH6/S6)? What do they do? What are they used for? I found the pins on the left (VBUS, D-, D+, ID, GND) on generic USB Micro headers, but I did not find the pins on the right.
Out of curiosity, what do the asterisks in the schematic mean? You can see them all over; for example, look at the top-right of the MCU.
What do the circle and the smaller circle (with an X through it) towards the bottom-right mean?

The 5V regulator is only used when you are powering from external power (>5V). The 3.3V regulator is only used by things that you power from the 3.3V pin on the Micro.

So if you aren't using external power you don't need the 5V regulator. If you aren't using any 3.3V devices then you don't need the 3.3V regulator.

You can use any micro USB or even mini USB connector you like. If you ignore the "ID" pin you can even use an old-fashioned chunky USB B connector like on the Uno.

The circles are fiducial markers and are special patterns on the board used for aligning a pick-and-place machine when manufacturing.


Connecting an Arduino Nano, Mega and LCD via I2C works but fails when shutting down Mega I have connected an Arduino Nano, Mega and a LCD via I2C/TWI (SDA/SCL).

The Nano is playing the master while Arduino Mega and LCD are slaves. This works well till I power off the Arduino Mega. Of cause I don't expect the Mega to answer.

In particular the SCL line seems to pull-down the connection. Disconnecting SCL from the Mega will reestablish the connection to the LCD. I added two pull-up resistors 4.7k to both SDA SCL but no improvement from that.

Is there no way than physically disconnecting the lines?

See
How to setup an I2C bus which stays valid if a slave is powered down or fails?

Basically I2C uses pull-ups to have all lines HIGH until any device bring it LOW. Arduino uses INPUT_PULLUP / OUTPUT+LOW states for this. But if you switch Arduino off (turn off Vcc), internal diodes cut the power on pins to Vcc (which is zero) +diode voltage (which is small), effectively to logical LOW. And I2C see that as the device is activelly sending LOW all the time - so communication is blocked.

If you just add pullup resistors, you either have them high enought so it not prevent this state or you have them low enought to draw the lines HIGH even when there is LOW on device, which prevents other devices to draw them LOW for communication. You need "cut off" such incactive lines - either physically disconnect (pull wires from connector - such as if you just get the Mega out of socket, or use some relays powered from Mega Vcc, which disconnet them when the power goes out) or electrically disconnect - using some circuits designed for it. There are some already sold or you can create your own to the same efect (if you are skilled in this area - otherwise it is much easier and faster to pay for some already made solution)


Arduino Uno, HM-10 Bluetooth Module, Not Discoverable In short, I've hooked up an HM-10 to digital pins 10 and 11 on my Uno (required because TX/RX (0/1) can't be used whilst a serial connection is present). The Bluetooth module is a Sunfounder HM-10 which comes with a data sheet. I'm successfully communicating with the HM-10 and I've written a modified version of serial comms tutorial code provided so it stores the reads up in a buffer before outputting them which works fine, I can set all properties on the HM-10 using this method.

The delays were necessary as it seems the clock cycle can't 'keep up' - bytes go missing when reading/writing, so if I attempt to write by just using Serial.read() in loop() alone then not all of it is read/written.

Here's the code.

#include <SoftwareSerial.h>

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

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

  Serial.println("Goodnight moon!");

  delay(500);

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.print("Wake up wake up wake up wake up wake up! Wake up wake up wake up wake up wake up!");
}

void loop() // run over and over
{
  if (mySerial.available()) {
    String s = "";
    char c;
    while((c = mySerial.read()) != -1) {
      s += c;
      delay(10);
    }

    Serial.println("Received: " + s);
  }

  if (Serial.available()) {
    String s = "";
    char c;
    while((c = Serial.read()) != -1) {
      s += c;
      delay(10);
    }

    delay(10);

    Serial.println("Sent: " + s);

    mySerial.print(s);
  }
}

This allows me to show input and output as follows:

Sent: AT+ADDR?
Received: OK+ADDR:F4B85EB42D64
Sent: AT+ADVI?
Received: OK+Get:0
Sent: AT+ALLO?
Received: OK+Get:0
Sent: AT+BATT?
Received: OK+Get:077

So good so far. Here's what I can't figure out from the data sheet. How do I make the bluetooth module discoverable on, say, my Mac or from my iPhone? I've tested setting AT+ROLE0 or AT+ROLE1 followed by AT+RESET and also set AT+NAME so I know what to expect, yet I can't discover the module.

Also to note, the status LED is flashing as per the specification as an unconnected status (500ms high, 500ms low) which indicates AT+PIO10 is setup. AT+ADTY? is set to 0 which allows it to be advertising, responds to scanning and connectable.

I'm likely missing something quite obvious. Any ideas?

Ah, I jumped the gun. Just found out Mac/iPhone can't scan for BLE devices, so I downloaded a BLE scanning app and once I set AT+ROLE0 and AT+RESET it appeared.

So, the answer is you need a BLE scanning application.


Serial communication with Python I am trying to send integer from my Python program to Arduino MEGA.
If I send 1, the LED should turn on and If  I send 0 the LED should turn off.

I was able to write Python code correctly as I think. I have configure the port and made serialWrite(val) function for send data to Arduino only if data is changed.
This not a full program. It has while loop. So, it writes data to Arduino rapidly. I used serialWrite(val) function to prevent that.

But, the LED never turns off, if I send 0. It turns on only. What are the problems in my code?

import serial as ser

prt = ser.Serial(
port='COM3',
baudrate=9600,
parity=ser.PARITY_NONE,
stopbits=ser.STOPBITS_ONE,
bytesize=ser.EIGHTBITS
)

preSerVal=0
#function for send data..data will send only val is changed
def serialWrite(val):
    global preSerVal
    if(not preSerVal == val):
        prt.write(str(val)+'\r\n')
        preSerVal=val

This is my Arduino program.

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}
byte incomingByte;

void loop()
{
  if (Serial.available() > 0) {
    incomingByte = Serial.read();
      if (incomingByte == '1') {
        digitalWrite(13, HIGH);
    } else if (incomingByte == '0') {
        digitalWrite(13, LOW);
    }
  }
}

UPDATE 1

I write testing program like this.

Python code:

import serial as ser
import time

preSerVal=0
prt = ser.Serial(
port='COM3',
baudrate=9600,
parity=ser.PARITY_NONE,
stopbits=ser.STOPBITS_ONE,
bytesize=ser.EIGHTBITS
)
def serialWrite(val):
    global preSerVal
    if(not preSerVal == val):
         prt.write(str(val)+'\r\n')
         preSerVal=val

while 1:
   for i in range(0,10):
        serialWrite(0)
   time.sleep(1)
   for i in range(0,10):
        serialWrite(1)

Arduino code:

void setup() {
 Serial.begin(9600);
 pinMode(13, OUTPUT);
 digitalWrite(13, LOW);
}
byte incomingByte;

void loop()
{
  if (Serial.available() > 0) {
    incomingByte = Serial.read();
  if (incomingByte == '1') {
    digitalWrite(13, HIGH);
  } else if (incomingByte == '0') {
    digitalWrite(13, LOW);
  }
 }
}

This code gives this result.
see the video bellow:

https://www.youtube.com/watch?v=utC4vo8YDVU&list=PLM5AA5oFchgC25da44Q2X900pz0eojSQJ&index=1

UPDATE 2

This is a piece of code..it sends 0..i checked it.

try:
    circles = np.uint16(np.around(circles))
    for i in circles[0,:]:
        houghCenter=(i[0],i[1])
        cv2.circle(src,houghCenter,i[2],(0,255,0),2)
        cv2.circle(src,houghCenter,2,(0,255,255),1)
        cv2.circle(drawing,houghCenter,i[2],(0,255,0),2)
        cv2.circle(drawing,houghCenter,2,(0,255,255),1)
        #print (houghCenter,"   ",contourCenter)
        dx=math.fabs(houghCenter[0]-contourCenter[0])
        dy =math.fabs(houghCenter[1]-contourCenter[1])
        if (dx>diff and dy>diff):
            serialWrite(0)
        else:
            serialWrite(1)
except Exception:
    serialWrite(0)

You are missing a second time.sleep(1). That is why the first loop executes correctly and the the LED flashed faster. Without any time.sleep() at all, the LED is going OFF/ON so fast that you cannot see it happen (may be it's just not so bright as usually).

while 1:
   for i in range(0,10):
        serialWrite(0)
   time.sleep(1)
   for i in range(0,10):
        serialWrite(1)
   time.sleep(1)


nRF24L01 with antenna transmitter and receiver I am trying to use nRF24L01 with antenna  in my project, but when I do test with getting start from rf24 master is showing a serial monitor like in the picture abov e. What is the problem here?

Search in the code for the line Serial.begin(###) where ### is a number representing the serial speed, also known as baud rate.
This number must match with the baud rate of your serial monitor, otherwise all you get is garbage.

BTW, this has nothing to do with nRF24, this is plain Arduino serial connection.


Averaging input from multiple input over a fixed amount of time (estimated) I am trying to average input values for a number of inputs and have it then store those averages into a string to write to a txt doc on a sd card.

I am using:

// read 6 sensors and append to the string:
for (int analogPin = 0; analogPin < 6; analogPin++) {
  int sensor = analogRead(analogPin);
  dataString += String(sensor);
  if (analogPin < 6) {
    dataString += ",";
  }
}

to read the pins at the moment, but I want to change the analogRead(analogPin) to an average value and then use the averages to create the string.

but when I try to average the data I run into errors, or I get output that is 0 for something that should be higher (3.3V).

I am doing this to stabilize my values a bit better and remove jitter.

Any suggestions?

This function will average readings on an analog pin, include it and use it in place of analogRead(...) and it should do what you want.

int aveAnalogRead(int pin, int ave=10, int delayms = 0)
{
    int tot = 0;
    for(int i=0; i<ave; i++)
    {
        tot += analogRead(pin);
        if(delayms) delay(delayms);
    }
    return tot/ave;
}

in your loop():

for (int analogPin = 0; analogPin < 6; analogPin++)
{
   int sensor = aveAnalogRead(analogPin);
     <<do your work here>>
}


What is ECC608 crypto chip accelerator used for in Arduino Uno Wifi rev2? Arduino Uno Wifi rev2 includes an ECC608 crypto accelerator chip.

Even their documentation states "As for the WiFi connection, that's made secure with the new ECC608 crypto chip accelerator."

My question is: how exactly the ECC608 is used? I'd like to see the sources the Arduino makes the "WiFi secure" with it.

The library for the chip is ArduinoECCX08. It is used by the ArduinoBearSSL library. The ArduinoBearSSL is used by the ArduinoIoTCloud
 library and Arduino_OAuth library.
.


Using a class inside of another class I have a seemingly simple problem that seems to be popular, but after searching several forums I still have not found the answer: How do you use a class inside of another class?

I have simplified my problem:

class A {
  const int pin;
  public:
  A(int attachPin) : pin(attachPin) {
  }

  void setup() {
    pinMode(pin, INPUT_PULLUP);
  }
};

class B {
  A myA;
  public:
  B(int a_attach) : myA(a_attach) {
  }

  void setup() {
    myA.setup();
  }
};

B test;

void setup() {
   test.setup();
}

void loop() {
}

I think, the problem in that line B test. You are define a variable, but you forget to define default constructor ( B() ). You try to setup an A class with unknown pin! To avoid this you may define test variable in that way B test(2); or in that way const int test_pin = 2; B test(test_pin);. Also to avoid this problem you may to set default value to the constructor sucha as  B(int attach=2) : myA(attach) {} and define test variable, as you do in your code B test;.


Detect DS18B20 sensors and correctly assign them to relays I'm relatively new to microcontroller programming, so please excuse me if my question is dumb. I've created a simple device that allows me to control 4 relays based on temperature. I bought four DS18B20 sensors, 4 relay board and Wemos D1. Everything works fine - I'm able to read the temperature of each sensor based on their address.

But I started wondering how I can replace a single DS18B20 without recompiling the code; currently this isn't possible. After searching a bit I found a couple of questions about the order of 1Wire sensors. For example, this one. I have no control over the order in which sensors are detected.

Is there a best practice when it comes to configuring DS18B20 sensors?
I would like to set up my device. By set up, I mean that I would like to assign a specific DS18B20 to a specific relay.

I imagine it like so:

Take a new DS18B20, connect it to a device and power the device.
The device should scan for DS18B20 sensors. If it finds one then it should assign it to relay 1 and store its address in EEPROM.
Then unplug the device from power, plug the second DS18B20 and power the device again.
The device again scans for DS18B20 sensors. It finds 2 devices. The first one is known (the address was stored in EEPROM) so it is skipped. The second is assigned to relay 2 and the address is stored in EEPROM.
The same procedure is applied to the third and fourth sensors.
If four sensors are connected (the addresses are from EEPROM), then the device can run.
When the user wants to replace a non-functioning sensor, the same procedure can be used.

As I wrote, I'm new to microcontroller programming, so if there is a better way please let me know. I'm mostly learning by following examples and tutorials, so if anyone knows of an example showing such a configuration procedure I'll be grateful for any materials.

If you can easily disconnect the sensors one at a time then your way is fine.

If you can't easily disconnect them then you can maybe use readings to set the order, although this depends on the environment. If, for example, all the sensors are generally room temperature then you have the code check the temp of all the sensors at start up. If it finds one sensor at less than 0C then assign that sensor to the least-recently-replaced relay index (also stored in EEPROM).

Then when you want to put a sensor into the working set, hold an ice cube on it for a few seconds before powering up the controller. There are other combinations of this technique you can imagine that use a button or jumper wires to specifically set the index of the out-of-range-at-startup sensor.

Alternately if you have an extra pin on the Arduino, then you can make a procedure where you connect a new sensor to that pin before attaching it to the string. You can make a rule like "if you ever see a sensor on pin X then remember its device ID and assign it to relay Y". There are lots of UI ways to pick Y. Note that you do not even need any extra hardware for this.


How do I grab data from my Arduino device using a Python program? We are currently creating a system which can log student attendance using RFIDs. Currently, we have the RFID Scanner set up (MFRC522 reader and Arduino UNO microcontroller). The database for the student's info and time-logging is also already set up. We are; however, having problems with accessing the data the Arduino is sending. We want the Arduino device to send us the Tag IDs via a USB Connection and have set it up to send the relevant data through the Serial Port. However, we cannot access this data using a Python program with this code.

import serial

x = 1
while(x == 1 ):
    ser = serial.Serial("COM3", baudrate = 9600, timeout = 0)
    if(ser.is_open):
       print("Serial Port in Use")
    else:
       print("Card ID: " + ser.read)

We are attempting to read from Port COM3 (the SP the Arduino uses). If the serial port is in use, the program outputs the "Serial Port in Use" (for testing purposes only, to be removed in final code) and if not, it will output the Card ID. However, through this, we run into the problem of being unable to use the same serial port with the Arduino (we are running on Windows). We tried using a serial port splitter but replacing the "COM3" with the name of the virtual port does not work.

We would prefer not to use Processing and would be open to simply avoiding the use of a serial port completely.

It isn't a good idea to open serial in a loop. It can be opened once at the start (or you can retry once per few seconds, if it fails).

Also the method is_open should return true if the serial was successfully opened so you can use it.

Maybe some working example would be a good way to start.


Include statement not working I am creating my own library for the Arduino and I have the following code:

#include <Arduino.h>
#include <Servo.h>

class ServoMotorController {
    public:
        ServoMotorController(int servoPin, int motorPin, int angle);
        void setAngle(int angle);
        void setSpeed(int speed);
    private:
        Servo servo;

        int servoPin;
        int servoAngle;
        int motorPin;
        int motorSpeed;
};

I am getting the error that Servo does not name a type; however if I do

#include <Servo.h>
#include <ServoMotorController.h>

in my actual Arduino code then I do not get the error. Why is the include statement not working in my C++ lib?

This is a symptom of the arduino IDE. libraries can't add other libraries to the include path, but the can use other libs if they have already been included. you can use an error directive so your compiler output is more informative at least

#ifndef Servo_h
    #error "ServoMotorController Lib requires Servo.h to be included first to function"
#else

Arduino 1.5.6 beta's new library format has a section for dependencies in the new library.properties file that should allow one library to add another to the include path, but I'm not entirely sure if the functionality is fully implemented yet (its beta after all).


Encode & decode boolean values into a single integer? I'm trying to record the state of some pins over time. To save memory, I'm thinking about encoding the pin states into a single integer, like this:

Pin 1: TRUE
Pin 2: FALSE
Pin 3: FALSE
Pin 4: TRUE

Pin 1 = 1, Pin 2 = 2, Pin 3 = 4, Pin 4 = 8
1 + 0 + 0 + 8
Result: 9

This is pretty efficient.
But how do I decode the pin states from this best?
Or do you recommend a better way to do this?

You are almost there with that. Personally I'd use OR not +:

This is a better way of defining the pins instead of using 1, 2, 4 etc. It results in the same thing, but you can see the bit number in there. The << is left shift.

#define PIN0 (1 << 0)
#define PIN1 (1 << 1)
#define PIN2 (1 << 2)
#define PIN3 (1 << 4)

Now you can combine:

uint8_t val = PIN0 | PIN3; // 9

And you can check if one is set:

if (val & PIN3) {
    // ....
}

To loop through the pins you can use the << again:

for (uint8_t pin = 0; pin < 8; pin++) {
    if (val & (1 << pin)) {
        // ....
    }
}

etc.


Serial: What is different between Gammon's RS485 (blocking) and RS485 "non blocking" libraries? The RS485 master-slave communication library on Nick Gammon's page http://www.gammon.com.au/Arduino/RS485_protocol.zip is working for me OK, but on the same hardware wiring is not working for the non-blocking library http://www.gammon.com.au/Arduino/RS485_non_blocking.zip.

I can not find information about the connection of MAX485 on Arduino for non-block version. Is MAX485/RS485 from HW serial (ie Rx=0 and Tx=1)?

If so, how can a slave on the same line at the same time receive from master the message "hello world" and print it to the serial monitor?
Thank you for the explanation.

When I added the SoftwareSerial library into Nick's example for non-blocking, so it works, but is it still a non-blocking?

//Master:
#include <RS485_non_blocking.h>
#include <SoftwareSerial.h>
const byte ENABLE_PIN = 4;
SoftwareSerial mySerial(2,3); //RX = 2 TX = 3

size_t fWrite (const byte what) {
  return mySerial.write (what);
}

RS485 myChannel (NULL, NULL, fWrite, 0);

void setup () {
  Serial.begin (9600);
  mySerial.begin (28800);
  myChannel.begin ();

  pinMode (ENABLE_PIN, OUTPUT);  // driver output enable
}  // end of setup

const byte msg [] = "Hello world";

void loop () {
  digitalWrite (ENABLE_PIN, HIGH);  // enable sending
  myChannel.sendMsg (msg, sizeof (msg));
  digitalWrite (ENABLE_PIN, LOW);  // disable sending
  delay (1000);
}  // end of loop

//Slave:
#include <RS485_non_blocking.h>
#include <SoftwareSerial.h>
const byte ENABLE_PIN = 4;
SoftwareSerial mySerial(2,3); //RX = 2 TX = 3

int fAvailable () {
  return mySerial.available ();
}

int fRead() {
  return mySerial.read ();
}

RS485 myChannel (fRead, fAvailable, NULL, 20);

void setup() {
  Serial.begin(9600);
  mySerial.begin(28800);
  myChannel.begin();
  pinMode (ENABLE_PIN, OUTPUT);  // driver output enable
}  // end of setup

void loop() {
  if (myChannel.update()) {
    Serial.write (myChannel.getData(), myChannel.getLength());
    Serial.println();
  }
}  // end of loop

Regards, Vava
(Sorry for my English... :-)

Reference page: http://www.gammon.com.au/forum/?id=11428

The blocking library is intended where you want to wait for incoming data, and are prepared to do nothing else while it arrives. There is also a timeout parameter which lets the code proceed if nothing happens for a specified number of milliseconds.

The non-blocking library is intended for where you need to do other things (like control motors, or read switches) at the same time you are receiving data. For that situation you call an update function periodically which assembles the incoming packet, byte-by-byte if necessary.

When the data is fully received the update returns true, and you can process the packet.

  If so, how can a slave on the same line at the same time receive from master the message "hello world" and print it to the serial monitor?

As I stated above in neither case do you receive and print "at the same time", however the non-blocking one does not simply wait until all the data has arrived.

Example code from the linked page:

void loop ()
  {
  if (myChannel.update ())  // returns true when packet fully received
    {
    Serial.write (myChannel.getData (), myChannel.getLength ());
    Serial.println ();
    }

  // do other things while waiting

  }  // end of loop

  If in example for non-blocking libraries is the same wiring as in the example of blocking library, where is (in non-blocking example) definition of RX(=2) and TX(=3) pins?

The hardware is the same.

  there is limitation for use - only pins which supports change interrupts.

Of course. If the underlying protocol is SoftwareSerial then the usual limitations apply (that is for the Rx pin).


Programing other Atmel ARM chips using Arduino Ok, i know professionals generally hate Arduinos, but I would like to know if it would be possible to program Atmel ARM chips using the Arduino IDE. By which I mean, not needing to modify the source code, just add another entry into the "hardware" folder and that's it.

We already know the Atmel ATSAM3X8EA (Arduino DUE) is compattible, but how about a similar chip, like the Atmel ATSAM3X8CA. Or maybe a Cortex-M4 one, like the Atmel ATSAM4E16EA or the Atmel ATSAM4S8CA.

The Atmel ATSAM3X8CA is the closest one to the Atmel ATSAM3X8EA the Arduino Due uses, a bit smaller and with less I/O.

If it isn't possible without much source code modding, I would like to know what would it take to make it work.

Thanks for your answers.

Yes it is possible. IDE 1.5.+ support different platforms, as they call it. Where the AVR and sam are provided by stock. Others are possible.

It is fairly involved setup. In short; within each platform there are the following files:

boards.txt, defines the individual boards using the similar processor.
platform.txt, defines the compiler arguments
programmers.txt, defines how to program it.

With corresponding sub directories to match, under the variants/ folder.
I have not found an complete tutorial on the matter. However, their

Arduino IDE 1.5 3rd party Hardware specification

An overview of the platform architecture proposed for Arduino 1.5

are a great place to start.

I have not done much with SAM. I do notice that programmers.txt is empty. So it must be done another way.


Which Arduino microcontrollers are able to drive a parallel 8-bit ILI9341 display at 320x240@60fps with DMA or extra CPU core or both and how? I've always wanted to make my own game console. I don't know why the existing Arduino game consoles have this issue with framerate when a 2006's Sony handheld PC had 1GB of RAM and an Intel CPU running Windows XP. Why haven't normal DIY open-sourcing copyright-libertarian hobbyists been able to make something at that magnitude? Don't say money because money is the reason I'm in gamedev scene; wanting to make a game console or anything that has a screen, characters, multimedia and nerdiness to make money.

So the issue has always been how do I find a microcontroller that's enough fast to run a 320x240 display like ILI9341 at 60FPS without stuttering or having to do lots of precalculations for partial screen updates. What about the NES/SNES consoles which didn't even have a framebuffer but which used discrete logic?

My scheme was to use ATXMEGA128A1U with a parallel bus and DMA, but it was hard to find a board containing all the stuff I needed and the External Bus Interface.
Then I tried to use ESP32 with SPI, but SPI would go max to 80MHz while the screen could only handle 40MHz.
Then I tried ESP32 again with 8-bit IO pin permutation which didn't work; it was too slow; maybe it would be faster if I used Xtensa assembly to take advantage of the CPU pipeline in case the dumb C++ compiler compiled machine code that waited 7 cycles for every next operation.
But now I'd like to use ESP32 with an I2S bus and DMA which was used for a camera demo and it was really really fast, but I'd like to use it for I2S output for that ILI9341 display. According to my calculations, it should take 10MHz to write out all of the bytes if the bus is 16-bit wide (8 bits for data and 1 bit for Data/Command register) + Read/Write/Select strobes controlled by the bus interface. However, Bitluni has been able to drive it to out of spec values of 580MHz for his VGA library that's superfast, but that month he had nothing to pay his rent with so he licensed the code under a copyleft license (ShareAlike). You know what they say, "The love of money and the lack of money are the roots of all evil.". Money is important, but really... this just makes money an even worse enemy than it was before.

So I guess I'm out of options. There have been many attempts and they have failed. Yes, there's Teensy and stuff, but I need something in the EU which I won't have to pay for more in shipping than the actual product.

So, what are the solutions?

P.S. if I get one of those "off-topic" or "too-broad" or dislikes to my question, I'm deleting it and moving to Reddit and screenshooting how yet again StackExchange is just too formalistic and banhammersome to open conversations.

The problem is the whole concept of running an ILI9341 TFT screen at 60FPS from a microcontroller. You can't. It's just not fast enough.

To get those kind of speeds you need to directly interface the TFT panel with the microcontroller. And that takes a special microcontroller with a TFT interface built in.  As well as that you need the memory to store the image that you are displaying on the screen.

There are microcontrollers available that can do it quite happily.  But they aren't in the "maker scene". Simply because they aren't a common thing to do.

For many years now there has been the PIC24 "DA" range of microcontrollers with a built in GPU and TFT interface - but there is no free C++ compiler, so no Arduino support - so no easy route to using them for beginners.

There are now, though, the PIC32MZ "DA" rage which are more accessible - though still very hard to use.  These are much more viable for the kind of thing you want, with 32MB of built in DDR, a TFT panel interface, and available in a 144 pin TQFP chip that is possible for an experienced maker to hand solder.

But the barrier is still software.  While chipKIT has full support for the PIC32MZ "EF" range of chips the "DA" range is not yet supported.  That's not to say you can't work with them, just not with the Arduino API and IDE.

The more common way to make a games console like device is to take an ARM SoC and interface it with a TFT panel directly. The simplest way for a maker to do that is to put a TFT on a Pi and install Retropie.

And we're not against open discussion as people. It's the site. It's not a site for open discussion. It's a question and answer site. You ask a technical question that you need assistance with, and we tell you the answer. It's not a forum for general discussion.  As such, this question will be closed as either "top broad" or "primarily opinion based". However your question does deserve an answer anyway.


Increasing ADC resolution At this moment I am using oversampling to increase my analogread resolution.
This in combination with increasing the frequency of the ADC.
Is someone able to take a look at it?

#define FASTADC 1
// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

int value[100];   // variable to store the value coming from the sensor
int i=0;

void setup()
{
  Serial.begin(9600) ;
 int start ;
 int i ;

#if FASTADC
 // set prescale to 16 (1MHz)
 sbi(ADCSRA,ADPS2) ;
 cbi(ADCSRA,ADPS1) ;
 cbi(ADCSRA,ADPS0) ;
#endif
}

void loop()
  {
  for (i=0;i<100;i++)
  {
   value[i]=Read12bit(0);
  }
  for (i=0;i<100;i++)
  {
   Serial.println(value[i]);
  }
  Serial.println();//Some blanks between values
  Serial.println();
  delay(5000);

}

int Read12bit(uint8_t pin){
      int Result = 0;
      analogRead(pin);                      //Switch ADC
      for(int i = 0;i < 16; i++) {          //Read 16 times
        Result = Result + analogRead(pin);  //Sum results
      }
      Result = (int)Result/4;               //Divide by 4 for 12 bit value
      return(Result);
    }

At this moment the resolution of this oversampled analogread is 12-bits. With a little calculation the time to read will take 0,208milliseconds. If I want to increase my resolution more i.e. 13-bit. This will take the measurement 0,832 milliseconds. This seems rather big, so my question is can I do this in another way?

EDIT
Why?
I am trying to position multiple linear actuator using multiple arduino's connected via CAN-bus (the arduino's will not communicate with eachother unless an error occures) THe positioning has to be precise (<0.1mm on a 30 cm rod).

Why is 12 or 13 bit accuracy and/or resolution needed?

12 is probably enough. But I just like to find out the boundaries of the equipment :)

What real world processes are being monitored that 0.012% perbit step sizes are not swallowed in the noise of reality?

Probably none 13-bit resolution is probably too high for my application anyways.

Other reason why I like a higher resolution
First couple of voltages I cannot use. My sensor gives a 4 to 20mA signal which i convert with resistor to ground.

Yes, you can use an external ADC chip. You can get SPI and I2C ΣΔ ADC chips at 16-bit and higher quite easily.

I often use the MCP3553 which allows 60sps at 22-bit.


How to get PPM value from MQ-3? I tried to build project to detect alcohol with Arduino Uno and an MQ-3 Alcohol sensor.

I already have the R0 value, but I faced problem here: I don't know how to convert it to PPM or BAC. I already tried some code from tutorial for convert it to BAC but when I gave the sensor alcohol the code gives me a value of 0.00, and I don't know why.

Here is the code to find R0 value:

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

void loop()
{
    float sensor_volt;
    float RS; //  Get the value of RS via in a clear air
    float R0;  // Get the value of R0 via in Alcohol
    float sensorValue;

    for(int i = 0 ; i < 100 ; i++)
    {
        sensorValue = sensorValue + analogRead(A0);
    }

    sensorValue = sensorValue/100.0;     //get average of reading
    sensor_volt = sensorValue/1024*5.0;
    RS = (5.0-sensor_volt)/sensor_volt; //
    R0 = RS/60.0; // 60 is found using interpolation
    Serial.print("R0 = ");
    Serial.println(R0);
    delay(1000);
}

Here is the code to determine BAC:

float R0= 0.28;
void setup() {
  Serial.begin(9600);
}

void loop() {
  float sensor_volt;
    float RS_gas; // Get value of RS in a GAS
    float ratio; // Get ratio RS_GAS/RS_air
    float BAC;
    int sensorValue = analogRead(A0);
    sensor_volt=(float)sensorValue/1024*5.0;
    RS_gas = (5.0-sensor_volt)/sensor_volt; // omit *RL

   /*-Replace the name "R0" with the value of R0 in the demo of First Test -*/
    ratio = RS_gas/R0;  // ratio = RS/R0
    float a = pow(ratio, 2);
    float b = ratio/10;
    BAC = (0.1896*a) - (8.6178*b) + 1.0792 ;  //BAC in mg/L
    Serial.print("BAC = ");
    Serial.println(BAC*0.0001);  //convert to g/dL
    Serial.print("\n\n");
    delay(1000);
}

I would to know what's wrong with the code, and if you know how to convert the R0 values to PPM, please tell me.

A series of if() statements and some simple division should be able to provide you with your PPM results.

From the datasheet, Alcohol Gas Sensor（Model：MQ-3), figure 5 shows the sensitivity curve:

It can be seen here

that there are three regions that the curve can be broken into:

The relationship is linearly proportional between 2.25 V and 3.25 V
Between 3.25 V and 3.8 V there is a curve
The relationship is linearly proportional between 3.8 V to 4.25 V

The slope of the straight line regions described in points 1 and 3 can be represented by the use of a constant and the PPM value by a simple division of the voltage by the constant.

The curve from the second part could be:

approximated by a straight line (thus, once again, using a constant), for simplicity, or;
more accurately, using a lookup table.

Using a straight line approximation for the curve (shown in lurid green), the graph becomes:

To determine the constant for the three lines simply take two points on each line and use:

  (y2 - y1) / (x2 - x1)

So for region one, assuming (by approximation, 3 V corresponds to 100 ppm and 2.5 V corresponds to 85 ppm (my eye sight may be slightly off here), the slope is

(3 - 2.5)/(100-80) = 0.5/20 = 0.025

You can calculate the constants for regions two and three in a similar manner (if using a straight line approximation for region two).

Therefore the code would be alomg the lines of

const double kRegionOne = 0.025;   // region one constant
const double kRegionTwo = ???;     // region two constant
const double kRegionThree = ???;   // region three constant

int ppm;                           // ppm result

/*
 * your code here
 * ...
 */

if ((sensor_volt < 3.25) && (sensor_volt >= 2.25)) {
  ppm = sensor_volt/kRegionOne;    // we are in region 1
} else if ((sensor_volt < 3.8) && (sensor_volt >= 3.25)) {
  ppm = sensor_volt/kRegionTwo;    // we are in region 2
} else if (sensor_volt >= 3.8) {
  ppm = sensor_volt/kRegionThree;  // we are in region 3
}

If you wish to be more accurate then use a lookup table for region two, as jsotola states in their comment.


How to use a variable format in `sprintf` How should I make a variable format sequence for sprintf?.

int i=2,d=9;
String sf;
sprintf(sf,"%%0%d",i);
fprintf(sf,d);

While expecting the output.

09

The compilation fails, with several errors, according the failing change I apply.

Invalid cast from type 'String' to type 'char*'

sprintf cannot be used to write data into String objects. More precisely, it is possible to come up with a "hackish" way to write the result directly into a String object, but the latter is definitely not designed for such use.

The target buffer should be an array of char, not a String. Which is what the compiler is telling you.

char buffer[64];
sprintf(buffer, "%%0%d", i);

or better

char buffer[64];
snprintf(buffer, sizeof buffer, "%%0%d", i);

The format string you used in your sprintf will generate %02 result (since i contains 2 at that moment). Why you are expecting 09 is not clear. Why are you expecting the % character to disappear is not clear either, considering that the format string seems to be deliberately designed to include it.
A String object cannot be used as the first parameter of fprintf. It is not clear what that fprintf is doing in your code.

Apparently you are trying to use sprintf to generate another format string at run time (using i as field width), which is later used to output the d variable. In that case that would be something like

char format[16];
snprintf(format, sizeof format, "%%0%dd", i);
fprintf(file, format, d);

That fprintf will indeed output 09.


Digital selection for gain control not working instead showing 0 I am making a device which will have a button to measure the input and another button to reset and the inputs are variable analog values(0 to 5v) and output is a ratio of two analog input voltages. It also has a selection keys(two buttons) for four selections(like gain eg. if key1 == LOW key 2 == LOW then J = 1 and likewise)
but the problem is when i am multiplying j with it the output shows zero if I multiply numbers like 1,2,3etc without using j then the ratio value gets multiplied.

here is the code

    void setup() // put your setup code here, to run once:
    {
      Serial.begin(9600);
      pinMode( K1, INPUT );
      pinMode( K2, INPUT );
      pinMode( MeasureButton, INPUT );
      pinMode( ResetButton, INPUT );
      dsp.begin(20, 4);
      current = millis();
    }

    void loop()
    {

      while(current < wait)
      {
      Serial.println("INITIALIZING");
      delay(1000);
      current = millis();
      }
      Serial.println("                   ");
      delay(1000);
      Serial.println(" READY TO MEASURE ");
      delay(2000);
      while (digitalRead(MeasureButton) == LOW)
      {
        if(K1 == LOW && K2 == LOW)
        {J = 1; // SOMETHING VALUE
        showMessage1();
        i = 0;
        delay(1000);
        }if(K1 == LOW && K2 == HIGH)
        J= 2; // SOMETHING VALUE
        showMessage1();
        i = 0;
        delay(1000);
        if(K1 == HIGH && K2 == LOW )
        J= 3; // SOMETHING VALUE
        showMessage1();
        i = 0;
        delay(1000);
        if(K1 == HIGH && K2 == HIGH )
        J= 4; // SOMETHING VALUE
        showMessage1();
        i = 0;
        delay(1000);

      }
      while (digitalRead(ResetButton) == HIGH)
      {
      dsp.setCursor(1,0);
      dsp.print("                   ");
      Serial.println("                   ");
      delay(1000);
      dsp.setCursor(1,0);
      dsp.print("RESETED");
      Serial.println("RESETED");
      delay(1000);
      }
while (digitalRead(ResetButton) == LOW)
      {
      dsp.setCursor(1,0);
      dsp.print("                   ");
      Serial.println("                   ");
      delay(1000);
      dsp.setCursor(1,0);
      dsp.print("PRESS MEASURE");
      Serial.println("PRESS MEASURE");
      delay(1000);
      }
    }

    void showMessage1()
    {
       while(i<5)
        {
        A = analogRead(A0);
        B = analogRead(A1);
        C = analogRead(A2);
        D = analogRead(A3);
        N = analogRead(A4);
        W1 = (A/N)*J;        // J is another variable whose value is dependent on K selection values
        W2 = (B/N)*J;        // J is another variable whose value is dependent on K selection values
        W3 = (C/N)*J;        // J is another variable whose value is dependent on K selection values
        W4 = (D/A)*J;        // J is another variable whose value is dependent on K selection values

        sumW1 = sumW1 + W1;
        sumW2 = sumW2 + W2;
        sumW3 = sumW3 + W3;
        sumW4 = sumW4 + W4;
        i++;
      }
        Serial.print("W1-");
        Serial.print(sumW1);
        Serial.print("W2-");
        Serial.println(sumW2);
        Serial.print("W3-");
        Serial.print(sumW2);
        Serial.print("W4-");
        Serial.println(sumW4);
        sumW1 = 0;
        sumW2 = 0;
        sumW3 = 0;
        sumW4 = 0;
    }

pinMode( K1, INPUT );

with

    if(K1 == LOW && K2 == LOW)

makes no sense. K1 is a pin number. LOW is a macro for 0 (HIGH for 1). You are comparing a static pin number against a static number.

If K1 is not equal to 0, the inner part of that if statement can never be reached.

What you meant to do was "if the voltage at the pin K1 is low". For that you need to read out the current value of the pin and check it.

For that you must replace your if(K1 == LOW) type statements to if( digitalRead(K1) == LOW).

I'd also like to mention that you must have a pull-up on your buttons for this "LOW"/"HIGH" logic to work. Either externally, or use INPUT_PULLUP instead of INPUT in pinMode.


Read speed between two ultrasonic sensors I'm new to Arduino and in need of help for this small project.

I'm trying to build an Arduino code that reads the speed of an object passing through two ultrasonic sensors. The plan now is to ping the first ultrasonic sensor once an object passes. The second sensor will then activate and wait for the object to pass by. The time it takes to reach the second sensor will be given into the equation.

Speed will be calculated by the distance between the two ultrasonic sensors divided by the time for the object to reach the second sensor. I would like to display the speed if possible on my computer screen.

Here is my code so far. Any help will be appreciated:

int trig1 = 3; //Trig 1
int trig2 = 4; //Trig 2
int echo1 = 5; //echo1
int echo2 = 6; //echo2
int ECHO1;
int ECHO2;
double first_time;
double second_time;
double final_time;
double speed;

void setup()
{
   pinMode(trig1, OUTPUT);  //sets the digital pin 3 as output
   pinMode(trig2, OUTPUT);  //sets the digital pin 4 as output
   pinMode(echo1, INPUT);  //sets the digital pin 5 as input
   pinMode(echo2, INPUT);  //sets the digital pin 6 as input
}

void loop()
{
  ECHO1 = digitalRead(echo1);

  while (ECHO1 == 0)
  {
    digitalWrite(trig1,HIGH);
    delay(100);
    digitalWrite(trig1,LOW);
    ECHO1 = digitalRead(echo1);
  }

  first_time = time();

  ECHO2 = digitalRead(echo2);

  while (ECHO2 == 0)
  {
    digitalWrite(trig2,HIGH);
    delay(100);
    digitalWrite(trig2,LOW);
    ECHO2 = digitalRead(echo2);
  }

  second_time = time();

  final_time = second_time - first_time;

}

There are several issues with these ultrasonic modules and your code:

How fast are these objects moving? If you don't have any reflection, it'll take almost 20ms for one measure. So precision will be low.
What if the object is moving in oposite direction?
What if the object stucked between?

and so on.

Anyway Laser interrupter circuit (or similar) would be much more suitable for this job.

Or if you want to use ultrasonic, you can use Doppler effect. But it's not possible with those PING))) modules (or clones).


How to fix when i shorted 5v to gnd accidentally (Arduino Nano) I connected 5V to GND accidentally (connect directly, no LED, no motor). Now the LED on the board doesn't light up and power LED lights up but it is not bright. The 5V output pin is only around 1.98V. I'm using clone version from Alibaba. I ordered two, one is still working but the shorted one doesn't work. May I know how to fix them?

I would say that to repair an Arduino Nano clone yourself, if ICs/SMD parts are damaged, is not worth the effort, if you could do it at all (first having to find out which parts need to be replaced, carefully de-soldering the delicate SMD parts, then putting new parts in place, etc.).


Calculate time between 2 data of a sensor I'm working on a project in my university and I'm having a trouble in calculate time. I have a conveyor and an IR sensor which I use to calculate the maximum and minimum distances of a box when it is moving on the conveyor. Then I want to calculate the time between the max and min distances of box. I have used millis() for timing but it is not accurate.
Here is my code:

int IRpin = 0;
float volts, distance,firstdata;
int k = 0;
float min;
float mang[150];
int m;
void setup() {
Serial.begin(9600);
}

void loop() {
volts = analogRead(IRpin) * 0.0048828125;
distance = 13 * pow(volts, -1.10);
if (distance < 20)
{
Serial.println(distance);
mang[k] = distance;
k++;
}
else
{
if (k > 0)
{
  min = mang[0];
  for (int i = 1; i < k; i++)
  {

    if (min > mang[i])
    {
      min = mang[i];
      m = i;
    }
  }
  firstdata=mang[1];
  }

I store data the sensor send to me in an array. Now I want to calculate the time between firstdata [mang(1)] and [(min)]. I use 0A41SK Sharp IR sensor.
Thank you for your time and sorry for my bad english.

Ok, yea...Please format this a little better (properly tabbed line spacing and such), and comments would go a long way to understanding this, because chances are people don't want to invest the time to decipher what's going on here without them. I'm not entirely sure what is going on here, but I'll just suggest what I would do in my understanding of the question, which is how to detect what the minimum and maximum value of the distance is and record the time at which each of these moments occurred.

I would have a float value to store the maximum and minimum distance as well as their times, and simply on every iteration of the loop check if the position was greater than the previous maximum distance or shorter than the previous minimum distance. If either of those are true, set the maximum/minimum distance to the current position and set the maximum/minimum distance time to the current time, using millis(). There's no reason I can see, if I'm understanding this correctly for an array to store all the data, it's just taking up memory space from what I see.

Hope this helps a bit, and, if I'm totally off base, again I'll emphasize the utility of comments in readability. Hope this helps and good luck.


ESP8266 Supply Voltage dropping below 3.3V I am trying to power an ESP8266 with a 3.3V regulator (this one, can supply ~ 1A). I've been struggling for days to get the ESP to work – it will occasionally boot, occasionally connect, but then not work again for hours. What I mean by "not working" is that it will often have trouble communicating over UART; or, upload my code, but not run it; or, run my code and crash on an Exception 0.

Now I have noticed that my voltage rail is dipping severely, sometimes below 3V. If I press my reset button, the level returns to 3.3V, but then when the ESP "boots" (but often not running any code, or crashing), it dips back to 2.9V. It is also fine while programming.

Does this suggest my ESP is simply fried? It's possible I briefly misconnected a wire when I first got the unit.

The ESP8266 will do an analog calibration when it is running the user code. This will typically be the worst case power requirement. The peak current requirement can be as much as 1/2 an amp. While your regulator probably can supply that I would bet your interconnecting wiring, and maybe the power source, are causing too much voltage drop.

The fact that you can see the voltage go down to 2.9 volts makes me thin that you have serious problems.

Early on when I started with the ESP8266 I was getting flaky operation. I put it down to bad code. But eventually I ruled that out. I took my setup to work (where I design electronic products) and looked at the power connections with a digital scope at the module. Right at the last point before the traces run under the shield. (I use the ESP-12 modules) It dipped just under 3.0 volts for two microseconds, and that was enough to cause a reset.

These things are not tolerant to any power dips. And this is why I recommend anyone starting with the ESP8266 to buy a Nodemcu or a Wemos type module. Something that has the regulator right at the processor.


Arduino Uno ADCH register stuck at 255 when read from ISR I'm working on a project that will essentially become an oscilloscope in the long run. I am following this guide. My code is uploaded here for more reference.

In my .ino file I have called functions to set up register such that I have a timer ISR called at a frequency of 100 KHz, and an ADC clock rate of 2 MHz. The ADC is also set so that the result is left shifted so ADCH contains an 8-bit result. In a separate .h file I have an ADC ISR that looks like this:

ISR(ADC_vect)
{
  // Read 8-bit conversion result from ADCH.
  uint8_t byte0 = ADCL;
  uint8_t byte1 = ADCH;

  data_byte = byte1;
  flag = true;
}

The loop() function is the following:

void loop()
{
  if (flag == true)
  {
    //Serial.println("ISR HIT");
    Serial.println(data_byte);
    flag = false;
  }
}

So, when the ISR is called the flag is set to true, and in the loop() function I am notified with an "ISR HIT" printed on the serial monitor, this operation is successful.

However, I also have a volatile global variable in my .ino function called data_byte (also declared as an extern in the .h file) that I set byte1 to. When byte1 is printed to the serial monitor the result is:

255
255
255

Any ideas on why the value of ADCH is stuck at 255? My hardware is simply a light sensor connected to pin A0, 3.3 V, and GND.

It would seem the problem lies here:

// Set Register to all zeros since Vref
// will be set to internal voltge and
// analog pin A0 is used.
ADMUX = 0x00;

According to the datasheet, the bits REFS[1:0] of the ADMUX register
select the voltage reference as:

00: AREF, Internal V ref turned off
01: AVCC with external capacitor at AREF pin
10: Reserved
11: Internal 1.1V Voltage Reference with external capacitor at AREF pin

Settings those bits to zero means that you are now supposed to provide
your own reference through the AREF pin. If you want to use the 5 V
supply as a reference, you should set them to 01. This is confirmed by
the block schematic. Here is the part of that schematic relative to the
reference voltage:

When REFS0 is zero, the highlighted transistor does not conduct, hence
the only way to provide a voltage reference is through the AREF pin.


DHT 11 temp. And hum. Sensor always 0 values I am trying to get my DHT 11 from the official arduino store to work (https://store.arduino.cc/grove-temperature-humidity-sensor).

I am following this guide right here:
http://wiki.seeedstudio.com/Grove-TemperatureAndHumidity_Sensor/

But I'm only getting invalid output of 0 humidity and 0 degrees.

I hope the image helps in identifying my problem.

On a side note, my sensor looks like a part is missing which is very strange and makes me doubt the right product was sent to me.

Some more information:
- Black to GND
- Red to 5v
- White is wmpty
- Yellow to d2
- Using an arduino Uno
- Output does not change whether the sensor is actually connect or not.
- Total noob at this.

Help would be appreciated a lot!

You haven't bought a DHT11 module but the Grove - Temperature&Humidity Sensor (High-Accuracy & Mini) / TH02 module.

Thus you should use the example code here or follow the guide at seedstudio wiki.

Datasheet of the sensor: https://www.silabs.com/documents/public/data-sheets/Si7005.pdf


Using Arduino Micro with MPU6050 I have an Arduino Micro and an MPU6050 gyro/accelerometer board; I want to read DMP data from the MPU6050, but the sketch requires the use of the interrupt pin, of which I have none of the interrupt pins available and they cannot be switched around.

I'm wondering how to go about reading the DMP data when needed. I've tried but always just receive the value 180 for any reading.

Thank you!

I searched quite some time for everything regarding the MPU6050, but there is just rumors and jokes about the dmp funcionality. One project encorporates the hard reverse-engeneering some wise people did, which is: http://www.i2cdevlib.com/docs/html/class_m_p_u6050.html

This also uses the interrupt, which I suppose you can't really avoid. Why exaclty this would be necessary though, is not a thing I could tell you.. I assume, that the dmp works somehow with the fifo buffer and can only interact through it. The cited library has examples with and without dmp, which I can really recommend.

Using this thing for a quadcopter however I can just say, that the dmp is too slow to control such a fast system, so maybe first consider what you really need. From my experience it does some magic things, but acts strange is due to it's not documentary it is a pain to work with.

Hope this helps.


Didn't have MAC address on Wiznet based ethernet shield (cloned) My Ethernet shield dont have any MAC address, please tell me how to find the MAC address, I'm stucked! Here is the link from where I bought the Ethernet shield.
http://www.amazon.in/gp/product/B00AXVX5D0?ie=UTF8&at=&force-full-site=1&ref_=aw_bottom_links

Ethernet will work as long as two different machine in the LAN don't have the same MAC address, as @Nathan wrote in his answer.

The MAC address is built by two parts, a prefix which are given to manufacturers of network devices and is called OUI, and a suffix that is the node part that manufacturers can use as they wish.

If you want to build an MAC address yourself, use a Locally administered address.  Universally administered and locally administered addresses are distinguished by setting the second-least-significant bit of the most significant byte of the address.
That will make this address to not use any OUI prefix, as that bit is zero on OUI, which minimize the risk of two or more devices have the same MAC address in same LAN.

If you get the same MAC addresses you will get very strange results if they happen to be in the same LAN, I tell you.  Been there, done that, and it wasn't fun to debug.

Here are a site that looks up MAC addresses (and generate random ones).  But if you want to see which manufacturer have that MAC address, you read it from IEEE and their list.


New to Arduino: Should I learn C, C++ or both (C & C++)? From what i've researched here is my thoughts on both

C++
I heard that you can create libraries using C++ in arduino. And you can use the Arduino IDE to do that stuff.  Here is the proof

http://arduino.cc/en/Hacking/LibraryTutorial

Notice that it uses the C++ syntax.

I also see arduino projects on github written on C++
https://github.com/search?l=C%2B%2B&q=Arduino&type=Repositories&utf8=%E2%9C%93

C

I heard that you can use AVR GCC and code it without the arduino ide. And I heard it's much faster than the arduino language because it's more closer to the metal. But I think it's harder to set up because you need a programmer into the Atmel chip, which is much more costlier compared to directly plugging in the arduino using the USB to printer cable. And you also need to download a bunch of stuff to get coding in pure avr gcc (win-Avr GCC, atmel studio etc.).

Which one should i learn C or C++? I prefer the easy to debug route. Or is it beneficial if i learn both?

The basic syntax of C and C++ is very similar, to the point that C code can typically be compiled directly as C++. You'll also find C standard functions (such as printf and malloc) can be used from C++ programs.

The major difference in the core language is that C++ has a lot of extra stuff such as classes and templates. Conventionally, C++ also has a huge standard library which doesn't work on C. However, that's not usually available (nor really appropriate) for Arduino programming, so you don't need to worry too much about it unless you migrate to e.g. desktop programming.

Basically, it's probably sensible to learn C first, because the same knowledge works in C++. You can then move on to the C++-specific stuff, such as classes.

As a side note, the Gnu Compiler Collection (GCC) actually covers both C and C++. It's what the Arduino IDE at Atmel Studio use under-the-hood for all their compilation. It's even possible to work directly with GCC but still upload programs to Arduino via USB.

It's also worth noting that programs compiled within the Arduino IDE aren't necessarily going to run any slower than programs compiled some other way (whether C or C++). The main difference is whether or not you use the Arduino functions. Since they are general purpose, they're not necessarily doing things the most optimal way. You could get more efficiency in theory by manipulating the microcontroller's special registers directly, which is you can do from within the Arduino IDE as well. It's usually very tricky for a beginner though, so it's probably not something you want to attempt until you're more comfortable with C/C++.


Can an AT89S52 be programmed using an Arduino as ISP? Since the AT89S52 controller is ISP programmable is it possible to use an Arduino UNO as a programmer to upload the hex file to the 8952 ?

I've tried various programmer softwares such as progisp, 8051 loader and ISP Prog v1.4 but the Arduino doesnt show up as a programmer on any of these. I've uploaded the ArduinoISP sketch on the UNO and then tried to program the 8952 without any luck.

According to my understanding the ISP programmers use an ATMega8 ,so is what I'm trying to do possible or do I need to purchace an ISP programmer ?

You should be able to use the Arduino as an ISP since an ISP is basically just a serial to SPI interface. If you are trying to use the arduino software to upload your program, you will need to edit your boards.txt file to be able to talk to the chip. If you are just using avrdude you will need to update your avrdude.conf.  AVR Freaks has a post on someone trying something similar and may be of some help. Without knowing your environment it's difficult to give more specific advice


Mac shortcut for next window - IDE 1.8.7 problem How do I use the keyboard to cycle through Arduino windows on a mac?

In my System preferences, I have (default):

Keyboard -> Shortcuts -> Move focus to next window =  Cmd ⌘   `

It works perfectly in all other programs, but in the Arduino IDE, it only swaps between the last two windows. If I have three(or more) windows open, it is a real pain to find the one in the background.

I am using fully updated MacOS 10.14 and Arduino IDE 1.8.7

In MacOS 10.14 and Arduino IDE 1.6.12, cmd` cycles through 5+ IDE windows properly, for me.

Update:

  When you upgrade to Arduino 1.8.7,

I won't be. I've tried a couple of its point releases and have given up on it because its launch performance is so p...-poor. Maybe 1.9 will finally fix it.

Sloeber/Eclipse is my serious code-crunching IDE. I keep the A-IDE around for reference and for quick knock-off experiments because it's quick to launch.

Update 2:

The OP asked me to note that he

  found that  Cmd ⌘   Shift   `  cycles
  through all windows (maybe in reverse).

Update 3:

  In older IDE the reverse cycling with Shift doesn't work?

It works in both directions for me (shifted/unshifted).


Reducing noise and finding sampling rate I have Arduino Due R3 (84MHz) and I am trying to find the mean of value from AnalogRead. I have to set the sampling rate of 8000 samples/second with 4 channels. I tried using for loop for this purpose.

#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int i = 0;
int sensorPin = A0;
int sensorValue = 0;
int highest=0;
int lowest=0;
float mean=0;

void setup()
{
  Serial.begin(9600);
  analogWriteResolution(12);  // set the analog output resolution to 12 bit (4096 levels)
  analogReadResolution(12);   // set the analog input resolution to 12 bit
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);

  lcd.print("Hello");

}

void loop()
{

  for(;;)
  {
    mean=0;
    for(i=0;i<8000;i++)
    {
       sensorValue = analogRead(sensorPin);
     highest=max(highest,sensorValue);
     lowest=min(lowest,sensorValue);
     mean = mean + (highest-lowest);
    }
    mean = mean/8000;
    delay(10);
    lcd.setCursor(0, 1);
    lcd.print(mean);
  }

Will this set sampling rate to 8000 samples/sec ?

Also I was receiving  a lot of noise at A0 which often led to the lowest value to be 0. In the image : The  red wave is a constant dc voltage of 2.7 V from power supply.

How do I overcome this noise so that mean value is accurate and precise ?

Just to as a complement to Majenko's answer (which I second), there are
a couple of flaws in your program that may be related to your problem:

lowest is always zero, as it is initialized to 0 and cannot increase
your computation of the mean is incorrect: the mean is the sum of the
readings divided by their number
you fail to reset lowest and highest between consecutive runs of
8000 samples
there is no point in putting all of loop() inside an infinite loop.

Assuming you really intend to print summary statistics on runs of
8000 samples, as your code suggests, I would write it like this:

const int SENSOR_PIN = A0;
const int SAMPLE_COUNT = 8000;
const uint32_t SAMPLE_PERIOD = 125;  // 125 us

void loop()
{
    long sum = 0;
    int lowest = INT_MAX, highest = 0;

    uint32_t lastTime = micros();
    for (int i = 0; i < SAMPLE_COUNT; i++) {

        // Wait until it's time.
        while (micros() - lastTime < SAMPLE_PERIOD) ;
        lastTime += SAMPLE_PERIOD;

        // Take and process the sample.
        int sensorValue = analogRead(SENSOR_PIN);
        sum += sensorValue;
        highest = max(highest, sensorValue);
        lowest = min(lowest, sensorValue);
    }
    float mean = (float) sum / SAMPLE_COUNT;
    Serial.print("mean: "); Serial.print(mean);
    Serial.print(", minimum: "); Serial.print(lowest);
    Serial.print(", maximum: "); Serial.println(highest);
    Serial.flush();
}

Edit: I changed the code in order to keep a roughly constant
sampling rate of 8000 samp/s. The main change is that, before
taking a reading, we wait until it's time to do so (until
micros() - lastTime >= SAMPLE_PERIOD).

Note that lastTime could be updated with lastTime = micros(), in
which case it would have hold the time we last took a sample. By
updating it with lastTime += SAMPLE_PERIOD it instead holds the time
we shoud have taken the last sample. This is the right choice for
enforcing a given average sampling rate.

Running on an Uno: I have no experience with the Due, but here are
some remarks that would apply to an Uno, or any other AVR-based Arduino:

analogRead() takes about 110 µs, which means we cannot sample
more than one channel, and we only have about 15 µs to process
the sample. Here the processing is simple enough that the Arduino can
do it in this limited time.
There is some jitter in the sampling, because micros() has a limited
resolution of 4 µs, because of the timer interrupt kicking in
from time to time, and because the while loop takes a finite amount
of time.

If I were to do something similar on an Uno, I would forgo
analogRead(), configure the ADC to be triggered by a timer, and set
the timer to trigger the DC every 125 µs. Not only would this get
rid of the jitter, it would also allow the CPU to do its job in parallel
with the ADC, instead of just sitting idle and waiting until the ADC is
done. This would allow for more complex per-sample processing.

About the Due: As I said, I have no experience with this board. It
has a more capable processor, but this tells you nothing about the speed
of its ADC. I would expect to face the same issues as with the Uno,
though maybe to a lesser degree. I guess it should be possible to
trigger the ADC from a timer, but I have no idea how to do so.


Using Lua in Arduino project I want to write code for my Arduino in Lua. Where I can find the necessary (pins) I/O lib and examples for Arduino IDE?
UPD: I've got arduino mega with many memory.

Lua is an interpreted language. That is, the compile phase turns Lua source code into intermediate "pseudo-code" which the Lua interpreter then runs. It doesn't compile into machine code, and therefore there is nothing that could be uploaded to your Uno as a "hex" file.

In any case, with only 2 KB of RAM, it wouldn't be very practical to attempt to run Lua on a Uno. I like Lua personally, but running it on the (AVR) Arduinos just isn't practical.


Serial.println Sensor Value and text in one line How do I put the sensor value and text on the one line in the serial monitor.

I just want Pot Value 30 to show in the serial console. What am I doing wrong?

Serial.println("POT value ")(sensorValue);

You just do two Serial prints:

Serial.print("POT value ");
Serial.println(sensorValue);

The .print prints without moving to a new line, the .println moves to a new line.

If you want to be more fancy and don't mind the processing and memory overhead, you can use snprintf to format the string:

char temp[15];
snprintf(temp, 15, "POT value %4d", sensorValue);
Serial.println(temp);

You can read more about sprintf and formatting here:

http://www.cplusplus.com/reference/cstdio/snprintf/ (function parameters)
http://www.cplusplus.com/reference/cstdio/printf/ (formatting options)

Note that there is no floating point support in the standard library for the Arduino - so you can't use %f etc.


motor hard stop vs coasting I'm using this motor driver with 2 of these motors to control a skid steer robot. To get the robot to coast to a stop, I use this code:

  analogWrite(MotLPWM, 0);  //coast to stop
  analogWrite(MotRPWM, 0);
  digitalWrite(MotL1, HIGH);
  digitalWrite(MotL2, HIGH);
  digitalWrite(MotR1, HIGH);
  digitalWrite(MotR2, HIGH);

to get the robot to hard stop, I use this code:

analogWrite(M1PWM, 0);
analogWrite(M2PWM, 0);
digitalWrite(M1INA, LOW);
digitalWrite(M2INA, LOW);
digitalWrite(M1INB, LOW);
digitalWrite(M2INB, LOW);

I would like for the robot to stop and/or brake with something in between so it isn't so hard on the gears. The following snippet of the whole sketch is supposed to let the motors coast for 1/4 second then hard stop. Unfortunately, it doesn't coast and goes straight to the hard stop. Any ideas how to fix it?

    void allStop () {
//COAST
  analogWrite(MotLPWM, 0);  //coast for 1/4 second before fast stop
  analogWrite(MotRPWM, 0);
  digitalWrite(MotL1, HIGH);
  digitalWrite(MotL2, HIGH);
  digitalWrite(MotR1, HIGH);
  digitalWrite(MotR2, HIGH);
//HARD STOP
  if ((millis() - previousCoastMillis) > 250) {
  analogWrite(MotLPWM, 0);
  analogWrite(MotRPWM, 0);
  digitalWrite(MotL1, LOW);
  digitalWrite(MotL2, LOW);
  digitalWrite(MotR1, LOW);
  digitalWrite(MotR2, LOW);
    previousCoastMillis = millis();
  }
}

The full sketch is here:

int ledB = 5;

int MotL1 = 8;
int MotL2 = 7;
int MotLPWM = 9;

int MotR1 = 11;
int MotR2 = 12;
int MotRPWM = 10;

unsigned long previousCoastMillis = 0;
const int coastInterval = 500;

void setup() {
  pinMode(MotL1, OUTPUT);
  pinMode(MotL2, OUTPUT);
  pinMode(MotLPWM, OUTPUT);
  pinMode(MotR1, OUTPUT);
  pinMode(MotR2, OUTPUT);
  pinMode(MotRPWM, OUTPUT);
  pinMode(ledB, OUTPUT);
}

void loop() {
  go();
  allStop();
}

void allStop () {
//COAST
  analogWrite(MotLPWM, 0);  //coast for 1/4 second before fast stop
  analogWrite(MotRPWM, 0);
  digitalWrite(MotL1, HIGH);
  digitalWrite(MotL2, HIGH);
  digitalWrite(MotR1, HIGH);
  digitalWrite(MotR2, HIGH);
//HARD STOP
  if ((millis() - previousCoastMillis) > 250) {
  analogWrite(MotLPWM, 0);
  analogWrite(MotRPWM, 0);
  digitalWrite(MotL1, LOW);
  digitalWrite(MotL2, LOW);
  digitalWrite(MotR1, LOW);
  digitalWrite(MotR2, LOW);
    previousCoastMillis = millis();
  }
}

void go () {
  analogWrite(MotLPWM, 150);
  analogWrite(MotRPWM, 150);
  digitalWrite(MotL1, HIGH);
  digitalWrite(MotL2, LOW);
  digitalWrite(MotR1, HIGH);
  digitalWrite(MotR2, LOW);
  digitalWrite(ledB, HIGH);
  delay(1000);

}

You are trying to use a mix of delay and  millis

Instead you will want a proper state machine:

void loop(){

    switch (state){
    case GOING: go();
       state = WAIT_FOR_COAST;
       transition = millis();break;

    case WAIT_FOR_COAST: if(millis()-transition > 1000){
            allStop(false);
            state = WAIT_FOR_STOP; transition = millis();
        }
        break;
    case WAIT_FOR_STOP: if(millis()-transition > 250){
            allStop(true);
            state = WAIT_FOR_GO; transition = millis();
        }
        break;
    case WAIT_FOR_GO: if(millis()-transition > 1000){
            allStop(true);
            state = WAIT_FOR_GO; transition = millis();
        }
        break;

    }

}

Remove the delay in go and use a simple if-else in the allStop where parameter == true means hard stop and false means coast.

Another option is to use a extra mosfet to put a resistor across the motor instead of shorting it out (which is what the hard stop will do). That will reduce the breaking torque but defeats the isolation of the board.