MicroSD interfering with ISP programming I have a microSD connected to an Arduino and I can't program it over ISP without removing the SD card. Does anybody know how to prevent the SD card from interfering with the ISP programming?

Details:

This is the microSD breakout: https://www.adafruit.com/products/254

I'm using an ATMEGA328P at 3.3V 8MHz.

I'm not using a bootloader and, for several reasons, I can't use the serial port for programming.

Thanks!

Because the SD card is an SPI device it shares the same pins as the ISP interface. The only way to not have the SD card interfere with the ISP is to not have the SD card connected.

As you have seen, that can be achieved by removing the card.

It can also be achieved by adding a tri-state buffer between the MCU and the card so the MCU only connects the card to the SPI bus when it is ready to use it - under default operation the card is disconnected.


Set parameters after compilation I am extremely new to arduino and have searched for this on net but have not found it.
My project has 2 files, a ".ino" file with the sketch and another ".h" file with the secrets and configuration parameters, such as reading intervals, credentials to connect to Wi-Fi, etc.
Now I need in runtime to be able to connect to the arduino, either by serial or by any other way to be able to set these parameters.
Edit:
My question is: How can I change the parameters after compiling the sketch ?, for example, how can I specify the credentials for the arduino to connect to the client's wifi, since each client has different credentials.

It is likely 2 features are desired for this project:

A way to enter WIFI credentials after the program is running.
A way to store the WIFI credentials between power cycles.

The solution for the 2nd requirement is to use non volatile memory. Both problems have been solved before for certain types of Arduinos.  Here is a project on GitHub which has solutions for boards using the ESP8266 or ESP32 processors.


Arduino - Ultrasonic Sensor for use instead of analog potentiometer for proximity control I was hoping someone could assist me with a project. I have built a device which uses a potentiometer (analog) to control an audio filter (analog). I was looking to use the arduino dual ultrasonic sensor module (HC-SR04) to replace the potentiometer in this circuit to act almost like a proximity sensor; raising the filter cut off when a person gets close to the sensor. Do you know anyone who might be able to help in coding this? and also, what needs to be connected to what?? Thank you for any help you can provide. The potentiometer I would like to replace with the sensor is circled in red. I don't use the 'Fine Tune' potentiometer next to this, so please ignore.

The HCSR04 module is a digital proximity sensor, needing a microcontroller to read values from it. If you really want to use this then you will have to use a microcontroller as a digital to analog converter and map distance values from the HCSR04 to voltages.

However, a better solution would be to use some kind of analog distance sensor. I have used the Sharp IR distance sensors before (with Pololu carrier) and have had great success. This model also comes in a 3V flavor which might simplify your circuit design. You would now only need some analog circuitry to get the voltage values into the correct range.


Set variable value with serial? so I need to make a arduino program, generates 2 random numbers, makes a + calculation with them and asks user the right answer. If the answer is right AKA Calculation==User Answer, then led is set to LOW, and serialprint sent. If its wrong, Led lights up and serialprint sent again. It works if i set the variables manually etc. But the I think the problem is with my serialRead, somehow it doesnt set the value it got from the user as the value of the variable (Luku4)

Here is the code, I hope you can help me.

int Luku1 = 0;
int Luku2 = 0;
int Luku3 = 0;  //Summa
int Luku4 = 0; //Vastaus
const int ledPin = 13;
byte i = 0;

void setup() {

  for (i=0; i<4; i++){
pinMode(ledPin, OUTPUT);
}

randomSeed(analogRead(0));
Serial.begin(9600);
Serial.println("Arvotaan 2 satunnaislukua ja summataan ne yhteen. Kerro oikea vastaus");
}

void loop() {
  Serial.println("Arvotaan 2 satunnaislukua");
  Luku1 = random(1,5);
  Luku2 = random(1,5);
  Serial.println(Luku1);
  Serial.println("+");
  Serial.println(Luku2);
  Luku3 = Luku1 + Luku2;
  delay(100);
  Serial.println("Mika on vastaus?");
  Luku4 = Serial.read();
    while(Serial.available() == 0){}

  if (Luku4==Luku3) {
    digitalWrite(ledPin, LOW);
    Serial.println("Oikea vastaus");
    delay(2000);
  }

  else{
    digitalWrite(ledPin, HIGH);
    Serial.println("Vaarin");
    delay(2000);
    digitalWrite(ledPin, LOW);

  }
}

You are comparing a byte which was read through uart with a number. If you send number '5' through uart, you won't get number 5, but character '5'. To convert single character to number, you can do following:

Luku4 = Serial.read(); // '0' .. '9'
Luku4 = Luku4 - '0'; // 0..9

But this will work only for single digit numbers, for more robust solution please refer to readString function to see how you can read strings from UART and to function atoi which converts string to number.


Reading file from SPIFFS in nodemcu using ArduinoJson #include <ArduinoJson.h>
#include <FS.h>

/* Set these to desired credentials in runtime */
struct Config {
  String ssid = "";
  String pass = "";
  bool hFlag = false;
};

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("");
  delay(1000);

  //allows serving of files from SPIFFS
  Serial.println("Mounting FS...");
  if (!SPIFFS.begin()) {
    Serial.println("Failed to mount file system");
    return;
  }

  if (readConfigFile("/LaSt.json", false)) {
    Serial.println("Config read");
  } else {
    Serial.println("Failed to read config");
  }
}

bool readConfigFile(char* fileName, bool whichFile)
{
  File configFile = SPIFFS.open(fileName, "r");
  if (!configFile) {
    Serial.println("Failed to open config file");
    return false;
  }

  size_t size = configFile.size();
  if (size > 1024) {
    Serial.println("Config file size is too large");
    return false;
  }

  // Allocate the memory pool on the stack.
  // Use arduinojson.org/assistant to compute the capacity.
  StaticJsonBuffer<256> jsonBuffer;

  // Parse the root object
  JsonObject &root = jsonBuffer.parseObject(configFile);

  if (!root.success())
    Serial.println(F("Failed to read file, using default configuration"));

  // Copy values from the JsonObject to the Config
  Config.ssid = root["ssid"];
  Config.pass = root["pass"];
  if (whichFile)
  {
    Config.hFlag = root["hFlag"];
  }

  // We don't need the file anymore
  configFile.close();

  return true;
}

Compile gives error in Copy values from the JsonObject to the Config section. Error: expected unqualified-id before '.' token.

Want to read file from SPIFFS, and store in variable to use.

Your code at the top:

struct Config {
  String ssid = "";
  String pass = "";
  bool hFlag = false;
};

defines a variable "type". It's like making a new int or bool, but yours is called struct Config.

After making the type, you need to create declare an instance of it.

struct Config cfg;

Then, you refer to the one you created:

  // Copy values from the JsonObject to the Config struct named cfg
  cfg.ssid = root["ssid"];
  cfg.pass = root["pass"];
  if (whichFile)
  {
    cfg.hFlag = root["hFlag"];
  }

Note that a particular issue with ArduinoJSON and Strings is that you may get an error like:

error: ambiguous overload for 'operator=' (operand types are 'String' and 'ArduinoJson::JsonObjectSubscript<const char*>')

There is an ArduinoJSON FAQ entry that states

  Most of the time you can rely on implicit casts.

  But there is one notable exception: when you convert a JsonVariant to
  a String.

  For example:

String ssid = network["ssid"];
ssid = network["ssid"];

  The first line will compile but the second will fail with the
  following error:

error: ambiguous overload for 'operator=' (operand types are 'String' and 'ArduinoJson::JsonObjectSubscript<const char*>')

  The solution is to remove the ambiguity with any of the following replacement:

ssid = (const char*)network["ssid"];
ssid = network["ssid"].as<const char*>();
ssid = network["ssid"].as<String>();


How to connect the 3.3v pin of arduino mega to multiple sensors I am connecting 3 accelerometers to an arduino mega. I have everything except how to connect them to the 3.3v pin. I know that I can just connect the 3 of them to the same ground pin but I have been told I can't do the same with 3.3v pin. Can anyone tell me what is the best way to power them from the arduino mega?

You can connect all of them as long as the total current draw is not over 50mA as described here. If you need more than 50mA, you need to create your own 3.3v supply or use something like a breadboard power supply for instance (keep in mind to make a shared ground line).


16Hertz Uno R3 Board vs Arduino Uno R3 Board I bought a 16Hertz Uno R3 Board. When I installed the driver and the Arduino IDE,  in the IDE`s menu I saw:

  Tools -> Board -> Arduino Uno

was selected by default which is great, but...

  Tools -> Port -> COM3(Arduino Mega or Mega 2560)

was selected by default which I think might be some kind of misunderstanding...

When I chose:

  Tools -> Board -> Arduino Mega or Mega 2560

On that tools menu appeared new menu "Processor" with two options:

  Tools -> Processor -> ATmega2560 (Mega 2560)

which was selected by default and there was another option

  Tools -> Processor -> ATmega1280

When I restore Tools -> Board settings back to "Arduino Uno" the "Processor" menu with the two options disappeared and Tools -> Port setting did not changed!

If you take my board and look at the Microcontroller there is written:

  ATMEGA328P-PU

Also on that board is written:

  16HzUNO

I need to know:

What does 16Hz mean? Does it mean the clock or frequency of this
Microcontroller? I think it does not, if I try to find out details of my Microcontroller on the rs-online site, there is written:

  ATMEGA328P-PU, 8 bit AVR Microcontroller 20MHz 1 kB, 32 kB Flash, 2
  kB RAM, I2C 28-Pin PDIP

Why was there "COM3(Arduino Mega or Mega 2560)" written on the
Port's menu?
Is my 16Hz Uno R3 and the Arduino Uno R3 board the same? Which one
is better? When one of those is better?
Does the standard Arduino Uno R3 board have the same ATMEGA328P-PU
Microcontroller?

You need to have a look at the Arduino comparison table. This shows that all Arduino Uno boards run at 16 MHz. It seems that you have fallen for the marketing on the page for the Uno kit that you provided.

Also, which version of the IDE are you running? You should upgrade to the latest version, which is currently, at the time of writing, version 1.6.1.

To answer your questions in turn:

"16Hz" is the brand name and has nothing whatsoever to do
with the speed, which is actually 16 Mega Hertz. "Clock" and
"Frequency" refer to the same thing. 16 MHz is the clock frequency
of the board, and is the speed at which the ATmega328 runs at.
The RS Online link does indeed state 20 MHz, but that is merely the
maximum speed at which the ATmega328 can run at. The Uno under clocks it at 16 MHz.
The Ports menu will show you a number of possible devices, Arduino Uno should be one of them (which is the one you should select) and three items below that will be Arduino Mega or Mega 2560 (which you should ignore, you do not have a Mega board1). Unfortunately the Arduino site only shows the Mac menu, even on the Windows guide

which is no help to you, assuming that you are running the Arduino IDE on Windows. You should actually see this in the Board menu:

and this in the Port menu:

As you can see, there should be no mention of the microcontroller in the Port menu.
The 16Hz branded Uno and the Arduino Uno are to all intents and purposes the same and as I state in the first line, the 16 MHz Uno is exactly the same as a regular Uno, it is just marketing.
Both the 16Hz and the Arduino Uno have a ATmega328 and the Mega board has a ATmega2560. Again, check the Arduino comparison table to see the variety of the boards and their respective microcontrollers.

I hope that answers your questions.

1 If you do chose the Arduino Mega or Mega 2560 option, in the Board menu, then indeed there will be an additional Processor menu. However, this is irrelevant in your case, as you do not have a Mega board, and so you need to chose the Uno in the Board menu. If you do so, then the Processor menu will disappear, as it is not needed for the Uno.


Arduino UNO/Nano communication with SP1ML-868 module Good evening, I'm trying to establish serial communication between an Arduino UNO/Nano (ATMega328P) and a SP1ML-868 RF radio module (http://www.st.com/en/wireless-connectivity/sp1ml.html). I can talk to the radio with an FTDI breakout board, connected directly to my PC, but I can't do it with the Arduino.

As the radio is 3.3V and the Arduino is 5V, I tried to use the logic level converter from Sparkfun in the RX/TX lines, but that didn't work as well.

Any idea as to what I might be doing wrong? Thanks!

EDIT
I was able to talk to the radio by uploading a blank sketch to my Arduino and using only the RX/TX pins and the FTDI chip on the board. When I configure the Serial port (i.e. Serial.begin), this no longer works, which leads me to believe the problem is in the ATmega USART configuration. For some weird reason, this only works when the Arduino RX is connected to the module RX, and TX with TX.

As requested, below is the simple serial echo code I'm using, and an image with the wiring. This assumes the normal RX->TX and vice-versa connection. The module is powered through wires underneath its breakout board (3.3v).

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

void loop(){
  while(Serial.available() > 0){
    Serial.print((char)Serial.read());
  }
}

For some weird reason, this only works when the Arduino RX is connected to the module RX, and TX with TX.

This works because in that configuration you are actually using your Arduino as a USB-serial adapter. When you make the RX-RX, TX-TX connection you cannot communicate between the ATmega328P on your Uno but you are also making a RX-TX, TX-RX connection with the ATmega16U2 chip on your Uno that is used as the USB-serial adapter on the board.

I feel that it's problematic to try to use Serial (pins 0 and 1) for communication both with the computer and the module. Instead I would recommend using the SoftwareSerial library for communication between the Uno and the module.

SoftwareSerial doesn't work reliably at 115200 so you should first use the current working wiring to configure the module to communicate at a lower baud rate. 9600 is quite safe but if communications speed is a bottleneck for your application you can probably use a higher baud rate.

Next, wire the module to any unused pins on your Uno other than 0 and 1.

Finally, upload the following code to the Uno:

#include <SoftwareSerial.h>

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

void setup() {
  Serial.begin(115200);  // set this to the baud rate of the Serial Monitor
  SP1MLserial.begin(9600);  // set this to the baud rate of the module
}

void loop() {
  if (SP1MLserial.available()) {
    Serial.write(SP1MLserial.read());
  }
  if (Serial.available()) {
    SP1MLserial.write(Serial.read());
  }
}

This is the equivalent of the simple echo code you posted above and can be used to verify that everything is working before moving on to more complex code. I have arbitrarily chosen pin 10 for the Uno software serial RX pin 11 for the TX pin but you can modify the code to any pins that are convenient for you. You should make the connections with the module as RX-TX, TX-RX.


ATtiny85 - report error "Device reports version as: 2.2" I've bought ATtiny, from see link.
Trying to upload a basic Blink sketch I get this error: Device reports version as: 2.2.

1) Board manager was updated using http://digistump.com/package_digistump_index.json

2) Board selected as Digispark (Default -16.5MHz )

3) Programmer set to Micronocleus

Tried using some guides on-line, but some were old, some were for windows, while I'm using Ubuntu machine.

Appreciate any help,
Guy

It sounds like you have a newer board than the version of Micronucleus in the Arduino package.

As I discovered here you basically need to upgrade micronucleus in your Ardino installation, which you can download from here

Download the zip file from Github and extract it.  Then in a terminal (if you're not already in one) go to the directory you extracted.
Build the executable by typing "make"
Copy the compiled executable to ~/.arduino15/packages/digistump/tools/micronucleus/<version>/

where <version> is the currently installed version number (e.g., 2.0a4).  There should already be a micronucleus executable in there that you would replace with your newly compiled one.


Correlated signal from two sensors in one circuit I have water level/humidity sensor and a LDR diode hooked to arduino like this (the resistor is 10k)

On A0 I can read signal from water sensor (blue)
On A1 I can read signal from light sensor (yellow)

The problem is that both signals seem to be correlated. When I dip the water sensor to water and keep the light levels the same, the signal from light goes up as well (dramatically).

I suspect that this is due to Ohm's law. The voltage in a circuit depends on the total resistance of the circuit. Both sensors act as a sort of resistors so when one's resistance changes the voltage in the circuit changes as well.

How can I wire the sensors such that the change in resistance of either sensor doesn't affect the second? Or do I need a separate power supply for each sensor?

If I've found the same humidity sensor, it has pretty big output impedance and the maximum input impedance for the ADC input is 10kOhms. According the the datasheet the recommended minimum load for the sensor is about 80kOhms (?). That means readings of humidity sensor will be highly affected by sampling capacitor initial charge (= the value of previous reading).

Basically reading GND between sensor readings helps to separate the results from each other, but the humidity sensor won't be able to charge sampling capacitor to its output voltage without amplifying the current (you'll get values much lower than it should be).

Or you can repeat the readings on humidity sensor channel several times until the value is more "stable".


Making two points on a tm1637 display blink [ Solved ] Hello! In my project, using a display controlled by a TM1637, I want to make the two points on the middle of the screen blink (as every clock does).
The following example, provided by the library I'm using, makes the two points blink as I want (tm1637.point(POINT_ON/POINT_OFF); is what enables/disbales the point):
#include <TimerOne.h>
#include "TM1637.h"
#define ON 1
#define OFF 0

int8_t TimeDisp[] = {0x00,0x00,0x00,0x00};
unsigned char ClockPoint = 1;
unsigned char Update;
unsigned char halfsecond = 0;
unsigned char second;
unsigned char minute = 0;
unsigned char hour = 12;

#define CLK 2//pins definitions for TM1637 and can be changed to other ports
#define DIO 3
TM1637 tm1637(CLK,DIO);

void setup()
{
  tm1637.set();
  tm1637.init();
  Timer1.initialize(500000);//timing for 500ms
  Timer1.attachInterrupt(TimingISR);//declare the interrupt serve routine:TimingISR
}
void loop()
{
  if(Update == ON)
  {
    TimeUpdate();
    tm1637.display(TimeDisp);
  }

}
void TimingISR()
{
  halfsecond ++;
  Update = ON;
  if(halfsecond == 2){
    second ++;
    if(second == 60)
    {
      minute ++;
      if(minute == 60)
      {
        hour ++;
        if(hour == 24)hour = 0;
        minute = 0;
      }
      second = 0;
    }
    halfsecond = 0;
  }
 // Serial.println(second);
  ClockPoint = (~ClockPoint) & 0x01;
}
void TimeUpdate(void)
{
  if(ClockPoint)tm1637.point(POINT_ON);
  else tm1637.point(POINT_OFF);
  TimeDisp[0] = hour / 10;
  TimeDisp[1] = hour % 10;
  TimeDisp[2] = minute / 10;
  TimeDisp[3] = minute % 10;
  Update = OFF;
}

I tried to do it as it was the famous "blink", but nothing works.
Here's what I have done:
#include "TM1637.h" // Library for the 4-Digit Display
#include "RTClib.h" // Library for the RTC
#include <SoftwareSerial.h>

#define CLK 6
#define DIO 7

TM1637 tm1637(CLK,DIO);
RTC_DS1307 RTC;

const int fotoRes = 2;

SoftwareSerial mySerial(10, 11);

void setup()
{
  pinMode(fotoRes, INPUT);

  RTC.begin();
  RTC.adjust(DateTime(__DATE__, __TIME__));

  tm1637.init();
}
void loop()
{
  DateTime now = RTC.now();

  tm1637.display(0,now.hour()/10);
  tm1637.display(1,now.hour()%10);
  tm1637.display(2,now.minute()/10);
  tm1637.display(3,now.minute()%10);

  tm1637.point(POINT_ON); //Like blink example.
  delay(500);
  tm1637.point(POINT_OFF);
  delay(500);
}

EDIT: tm1637.set(0-7) ONLY set the brightnes of the screen. What makes the two pints appear is tm1637.point(POINT_OFF/POINT_ON). I'm asking how can I do to make these two points blink. Thanks.
Arduino UNO R3, DigitalTube library by Grove

Calling the point() method only updates a flag; you see the effect the next time you try to display a number. You can use something like this:

void show_time(DateTime &t){
  tm1637.display(0,t.hour()/10);
  tm1637.display(1,t.hour()%10);
  tm1637.display(2,t.minute()/10);
  tm1637.display(3,t.minute()%10);
}

void loop() {
  DateTime now = RTC.now();

  tm1637.point(POINT_ON);
  show_time(now);  // changes take effect here
  delay(500);
  tm1637.point(POINT_OFF);
  show_time(now);
  delay(500);
}


MacOS 10.15.1 Catalina CU port always busy, and TTY port not selectable I am trying to use an FTDI breakout board to connect to my custom made Arduino compatible board. I am using a new 16 inch macbook pro with USB-c ports, so I am using a dongle, in case that could be the problem.

Every time I try and upload a sketch I get the error: "can't open device "/dev/cu.usbserial-D306P6WW": Resource busy". When I check the /dev/ folder, both "/dev/cu.usbserial-D306P6WW" and "/dev/tty.usbserial-D306P6WW" show up, however in Arduino IDE I can only choose the "/dev/cu.usbserial-D306P6WW" option. I have installed FTDI VCP drivers, CH340 drivers and all kinds of other drivers to try and fix this issue. I have restarted countless times, and I have used a multitude of commands to check for programs hogging the usb port, but there is never a program. Plugging a harddrive into the same port causes no problems, so the port can't really be the problem. I am using a "FTDI FT231XS" board from Sparkfun.

Nevermind, updating my MacOS version to 10.15.3 magically fixed the problem...


Serial parsing strange data I have a project where I use a software serial connection to read serial data from a barcode scanner.

All is good. However from time to time I have some problems with the data that I'm receiving.

  You said : 123456789��?�: @���?���?���?���?���?

  You said : 123456789

  You said : 123456789123456

  You said : 987654321789456123

My code is something similar to the one below

int count = 0;
void parseSerial() {
  char ser[20];
  while (Serial.available() > 0) {
    char c = Serial.read();
    if ( c != '\r' && count <= sizeof(ser)) {
      ser[count] = c;
      count++;
    } else {
      Serial.print("You said : ");
      Serial.println(ser);
      for(int i=0; i < sizeof(ser); i++) {
        ser[i] = '\0';
      }
      count = 0;
    }
  }
}

Any idea on how I can get rid of "��?�: @���?���?���?���?���?"?

Thanks.

The problem is that the buffer is not initialized to start with. When
you call parseSerial(), it contains garbage, which is what you see on
the serial monitor. In order to avoid printing out that garbage, you
have to properly terminate the string, i.e. add a \0 after the last
valid character.

You did that after printing the string (you filled the whole buffer
with \0, which is overkill), but that's too late. The subsequent
printouts are OK though.

The recommended way to handle incoming serial data is to look for a
terminating character (\r seems to be what you expect), and buffer
all the incoming bytes until you see it. Don't forget to save 1 byte of
buffer space for the terminating \0:

void parseSerial() {
    static char buffer[20];
    static int count = 0;

    while (Serial.available()) {
        int c = Serial.read();
        if (c == '\r') {           // received complete line
            buffer[count] = '\0';  // terminate the string
            Serial.print(F("You said: "));
            Serial.println(buffer);
            count = 0;
        }
        else if (count < sizeof buffer - 1) {
            buffer[count++] = c;
        }
    }
}

Notice that the buffer here being static, you can accumulate partial
messages through successive calls to parseSerial(). Only when the
message is complete will it print it back.


Resetting I2c Address - MLX90614 I was using my MLX90614 IRTherm sensor flawless and bought two more. I have connected two sensors serial with pull-ups to SDA --> A4 and SCL --> A5. After digging the internet I found out that I should change their default slave addresses to different addresses so that Arduino can recognize their 7-bit slave addresses.
After changing their address, now I can't read either two new serial MLX'es or my old MLX.

I might have messed up with their addresses and don't know how to
reset their addresses.
How can i connect multiple sensors/ how can i change their adress properly?

  reading sensor data

#include <Wire.h> // I2C library, required for MLX90614
#include <SparkFunMLX90614.h> // SparkFunMLX90614 Arduino library

IRTherm therm; // Create an IRTherm object to interact with throughout

const byte LED_PIN = 8; // Optional LED attached to pin 8 (active low)

void setup()
{
  Serial.begin(9600); // Initialize Serial to log output
  therm.begin(0x5A); // Initialize thermal IR sensor
  therm.setUnit(TEMP_F); // Set the library's units to Farenheit
  // Alternatively, TEMP_F can be replaced with TEMP_C for Celsius or
  // TEMP_K for Kelvin.

  pinMode(LED_PIN, OUTPUT); // LED pin as output
  setLED(LOW); // LED OFF
}

void loop()
{
  setLED(HIGH); //LED on

  // Call therm.read() to read object and ambient temperatures from the sensor.
  if (therm.read()) // On success, read() will return 1, on fail 0.
  {
    // Use the object() and ambient() functions to grab the object and ambient
    // temperatures.
    // They'll be floats, calculated out to the unit you set with setUnit().
    Serial.print("Object: " + String(therm.object(), 2));
    Serial.write('°'); // Degree Symbol
    Serial.println("F");
    Serial.print("Ambient: " + String(therm.ambient(), 2));
    Serial.write('°'); // Degree Symbol
    Serial.println("F");
    Serial.println();
  }
  setLED(LOW);
  delay(500);
}

void setLED(bool on)
{
  if (on)
    digitalWrite(LED_PIN, LOW);
  else
    digitalWrite(LED_PIN, HIGH);
}

  Setting address

#include <Wire.h> // I2C library, required for MLX90614
#include <SparkFunMLX90614.h> // SparkFunMLX90614 Arduino library

IRTherm therm; // Create an IRTherm object to interact with throughout

const byte oldAddress = 0x5A;
const byte newAddress = 0x5B;

void setup()
{
  Serial.begin(9600); // Initialize Serial to log output
  Serial.println("Press a key to begin");
  while (!Serial.available()) ;

  therm.begin(oldAddress); // Try using the old address first

  byte address;
  if (!therm.readID()) // Try reading the ID registers
  {
    // If the read fails, try re-initializing with the
    // new address. Maybe we've already set it.
    therm.begin(newAddress);

    if (therm.readID()) // Read from the ID registers
    { // If the read succeeded, print the ID:
      Serial.println("Communicated with new address.");
      Serial.println("ID: 0x" +
                     String(therm.getIDH(), HEX) +
                     String(therm.getIDL(), HEX));
    }
    else
    {
      Serial.println("Failed to communicate with either address.");
    }
  }
  else
  {
    // If the read suceeds, change the address to something
    // new.
    if (!therm.setAddress(newAddress))
    {
      Serial.println("Failed to set new address.");
    }
    else
    {
      Serial.println("Set the address to 0x" + String(newAddress, HEX));
      Serial.println("Cycle power to try it out.");
    }
  }
}

void loop()
{

}

Edit 1:
Datasheet

Page 13 of 35 in the datasheet states:

  In order to provide access to any device or to assign an address to a
  SD before it is connected to the bus system, the communication must
  start with zero SA followed by low RWB bit. When this command is sent
  from the MD, the MLX90614 will always respond and will ignore the
  internal chip code information.

Supposedly, all you have to do is to connect only one device and use the address zero to read/write the registers.


Accelerometer Interrupt Meaning - Wakeup Function I am working with an LSM9DS1 IMU, and now specifically trying to program a wakeup feature into the system. My idea is to set the accelerometer at the lowest possible read rate, then when the accelerometer value exceeds a predefined level, to have the system wake up.

When programming the sensor, there is a register called INT_GEN_CFG_XL that has a "6-Direction detection for interrupt." I was wondering what this means. Does this perhaps calculate the magnitude of acceleration, and see if that goes above a predefined value? I can see the other interrupt generators are for 1-direction of each of the three axes, but I can't interrupt this one.

Here is a link to the device datasheet

The INT_GEN_CFG_XL 6-Direction detection interrupt apparently is aimed at detecting change of direction of travel, rather than an axis-combined acceleration level.

See the LSM303 discussion at Polulu.com.  That page includes a link to App Note CD00290365.pdf for the LIS3DH.  Here is what that app note says, on page 27:

  There are two possible configurations for the 6D direction function:

    • 6D movement recognition: In this configuration the interrupt is generated when the device moves from a direction (known or unknown) to a different known direction. ...
    •  6D position recognition: In this configuration the interrupt is generated when the device is stable in a known direction. ...

With the LSM9DS1 that you are using, you can leave OR enabled, set separate X,Y,Z threshholds in INT_GEN_THS_X_XL, INT_GEN_THS_Y_XL, INT_GEN_THS_Z_XL, and set the “Enable interrupt generation on accelerometer's X axis high event” (sim. for Y and Z) bits in the INT_GEN_CFG_XL register.


Interfacing Arduino with Python Serial I am implementing an FIR filter using Arduino. I am using an input signal as an audio signal. The audio signal has a duration of 3 seconds with total samples, 66150. What I am doing is reading this file in python and storing the data in an array. Using Serial, I want to send this sampled data to Arduino serial and process it, then send it back to serial and receive in  Python.

Python Code

import matplotlib.pyplot as plt
from scipy.fftpack import fft
from scipy.io import wavfile # get the api
import serial, time

samplerate, data = wavfile.read("sample.wav")
samples = len(data)
plt.plot(data[:20000])
arduino = serial.Serial('COM4', 9600, timeout=.1)
time.sleep(1) #give the connection a second to settle

for i in range(0,samples):

    arduino.write(data[i])
    time.sleep(1)
    print(arduino.readline())

Arduino Code

  void setup() {

  Serial.begin(9600);
  }
  int i = 0;
  int newdata[10];
  void loop() {
     if(Serial.available() > 0) {
          int data = Serial.read();
          newdata[i] = data;
          Serial.print(newdata[i]);
          i = i+1;
        }
   }

The problem I am facing is that I am stuck at very first step. As a check, I sent 10 samples values at start from Python to arduino using a loop and tried to recover them back to read on Python console. These values were not correct. When I entered a string inside the arduino.write(), it was receiving but when I input a variable inside the arduino.write(), it doesn't print that value after transferring back to python.
I just tried many things like changing to string but I didn't get the desired result. The output for this code is attached. Tomorrow is my submission and I am stuck in this thing. Help will be highly appreciated.

I have found a way to tackle this.
Here is my arduino code:

char buf[100];
const double coefficients[28] = {
-0.006416610121367, -0.01179616274682, -0.01212859343535,-0.001491136183145,
 0.0175211951058,  0.03193599126761,   0.0259553014052,-0.004580133449276,
-0.04206485416456, -0.05260424218688,-0.007566809377484,  0.09242896920118,
 0.2100842841173,   0.2894365184419,   0.2894365184419,   0.2100842841173,
 0.09242896920118,-0.007566809377484, -0.05260424218688, -0.04206485416456,
-0.004580133449276,   0.0259553014052,  0.03193599126761,   0.0175211951058,
-0.001491136183145, -0.01212859343535, -0.01179616274682,-0.006416610121367
};

int order_of_filter = 27;
int sample_array[28] = {};
double output_sample = 0;
void setup()
{
  Serial.begin(9600);
  Serial.setTimeout(50000);
}
void loop()
{
  int  sample_in;
  int num_read = Serial.readBytesUntil('\n', buf, 100);
  buf[num_read] = '\0';
  sscanf(buf, "%d", &sample_in);
  for (int i = order_of_filter; i > 0; i--)
  {
    sample_array[i] = sample_array[i-1];
  }

  sample_array[0] = sample_in;

  for(int i = 0; i<=order_of_filter; i++)
  {
    output_sample = output_sample + sample_array[i]*coefficients[i];
  }
  Serial.println(output_sample);
  output_sample = 0;
}

And here is my Python Code:

    import matplotlib.pyplot as plt
  from scipy.fftpack import fft
  from scipy.io import wavfile # get the api
  import serial, time
  import numpy as np
  import sounddevice as sd

  arduino = serial.Serial('COM4', 9600, timeout=1) #COM port depends on the USB port
 time.sleep(3) #time to get connection ready
 # %%

 fs, data = wavfile.read('hfsound.wav')
 samples = len(data)
 #Plot the signal
 plt.plot(data[:samples])
 plt.ylabel("Amplitude")
 plt.xlabel("Time")
 plt.title("Time Domain Response of the Input Signal")
 plt.grid()
 plt.show()
 #Plotting fft
 fft_input = fft(data)
 half_length = int(len(fft_input)/2)
 omega_axis = np.linspace(0, fs/2, half_length)
 fft_n = fft_input[:half_length]
 plt.plot(omega_axis,abs(fft_n))
 plt.xlabel('frequency')
 plt.ylabel('Amplitude')
 plt.title("Frequency Domain Response of the Input Signal")
 plt.grid()
 plt.show()
 # %%

 #Declare an Array of zeros
 outputArray = np.zeros(64000)
 #Sending data to aurdino
 for i in range(samples):
     number = data[i]
     string = str(number).encode(encoding='utf-8') + b'\n'
     arduino.write(string)
     byt = arduino.read_until();
     print(byt.strip())
     outputArray[i] = byt.strip()

 arduino.close()
 # %%

 #Plotting Output waveform
 #Plot the time-domain output signal
 plt.plot(outputArray[:len(outputArray)])
 plt.ylabel("Amplitude")
 plt.xlabel("Time")
 plt.title("Time Domain Response of the Output Signal")
 plt.grid()
 plt.show()

 #Plotting fft of output
 fft_out = fft(outputArray)
 half_length = int(len(fft_out)/2)
 omega_axis = np.linspace(0, fs/2, half_length)
 fft_n = fft_out[:half_length]
 plt.plot(omega_axis,abs(fft_n))
 plt.xlabel('frequency')
 plt.ylabel('Amplitude')
 plt.title("Frequency Domain Response of the Output Signal")
 plt.grid()
 plt.show()
 # %%

 #Playback code
 sd.play(outputArray, fs)
 # %%


Why does the following code not cause the led's to flash but rather stay on continuously int timer = 1000;
int thispin = 5;

void setup() {
  for (int thispin = 5; thispin < 8; thispin++)
    pinMode(thispin, OUTPUT);
}

void loop() {
  for (int thispin = 5; thispin < 8; thispin++)
    digitalWrite(thispin, HIGH);

  delay(timer);
  digitalWrite(thispin, LOW);

  for (int thispin = 7; thispin = 5; thispin--)
    digitalWrite(thispin, HIGH);

  delay(timer);
  digitalWrite(thispin, LOW);
}

I have the above code. I thought that how it was written would cause the led's to flash but they all stay on continuously. Could anybody help to explain what it is i have done wrong?
I am very new to this and I'm just fiddling basically trying to learn.
Thank you!

The objective of the code is not clear. It seems the idea is to repeatedly blink 3 LEDs, connected on pins 5,6 and 7. To do so, the code needs slight modification-
int timer = 1000;
int thispin = 5;

void setup() {

  for (int thispin = 5; thispin < 8; thispin++)
    pinMode(thispin, OUTPUT);
}

void loop() {

  for (int thispin = 5; thispin < 8; thispin++)
    digitalWrite(thispin, HIGH);

    delay(timer);

  for (int thispin = 5; thispin < 8; thispin++)
    digitalWrite(thispin, LOW);

    delay(timer);

}

Also, since you wanted to know why the LEDs stay ON continuously with your code-
This is because there is no delay statement after any of the digitalWrite-LOW statements. If there's no delay, the LEDs may turn off for a fraction of a millisecond, which won't be noticeable.


How do I measure watts without a CT clamp? I'm trying to build an "IoT" project for home that will in effect create a smartplug. I'd like to add the capability to measure the watt usage of the plug (and whatever's connected to it). I'd like to not use a CT clamp for this purpose, and I was hoping someone here can help.

I have a 220 V mains connection and I'd like to measure the watts used by a connected appliance to the smart plug is a small as possible form. CT sensors are too big for this purpose.

Thanks.

You can't use a CT sensor to measure power.  CT sensors measure current.  Measuring Watts is the correct unit if you want to know the rate of energy consumption (power) from an outlet.

Response to a Comment: There are consumer devices that cost only $12.95 that might be ideal, if the only usage scenario is to compare various devices for steady state power draw and you are fine with 3% (1.5 digit) accuracy.  For the 220 VAC (whether split phase or single phase) you would need to gang two of them together appropriately.  These plug-outlet designs are nicely miniature, but will not support checking past values, providing feedback to a control system, or Wattage plotting against date, time of day, or tay of week.

Measuring of Wattage accurately (to two or three significant digits) is not trivial if the 220 Volt source is an AC power grid, thus the length of this answer.

The basic EE formula for power is P=IV for DC, meaning power is the product of current and voltage.  But you can't just go with Watts = 220 X current and expect any more than one significant digit of accuracy.  Grid Voltage may not be a clean sine wave and may vary five or ten Volts under normal conditions.

If you want more than one digit of accuracy, you'll need to calculate RMS (root mean square) power in Watts by sampling both Voltage and current and using the AC principles that extend the simple P=IV relation.   I don't know if you have knowledge of what electrical engineers call RMS.  In case you don't, the articles in the result set of This Search [1] may be helpful.

Let's hypothetically say you are considering doing the work necessary to get the two or three significant digits of accuracy in determining power consumption.  To get a sense of what that would entail, here's some information on doing that properly.  You will want to consider line voltage fluctuation, reduce your noise levels, protect your Arduino board from over-voltage, and follow electrical code reasonably well.

The below measurement fixture design is not small, but it could be miniaturized.  Unfortunately the design of a miniaturized version is large project FAR outside of the scope of an answer in this forum.  You may be one of those that likes the challenge, so I'll share a design for a larger version and leave it to you or other answering parties to think of a miniaturization that meets all these other reasonable goals.

Off the shelf parts to fabricate a full sized power measurement fixture to interface with an embedded board like the Arduino Due, for example:

Two electrical boxes
A length of electrical conduit at least 50 cm long
Electrical hardware to connect the two boxes and secure the AC cord leading to the plog and to the devices being powered.
Two lengths of 2-conductor 18 AWG shielded twisted pair cable with at least 500V rating
Code compliant AC cabling
Wire nuts
Box for the buffering circuit
A good quality digital Voltmeter with RMS AC as one of the options

Fabricate this way, but using proper code-compliant electrical practices in addition to these basic instructions for the main circuits:

Connect the plug to one of the boxes with properly rated AC cord.
Connect the two boxes with the conduit and properly rated power and return wires (white and black).
Connect the second box to the device
In each box, connect the 2 conductors of the shielded twisted pair in parallel to the AC circuit passing through the box with the wire nuts.  You must leave the shields of the two twisted pair lengths isolated (not connected to the box or the ground wire in the AC circuit.
Bring both twisted shielded pairs into the buffering circuit box.

The buffering circuit would condition each of the two AC voltage in three stages.

Surge protector
Resistor divider (see other Arduino articles for this)
Zener diode to further protect the A-to-D converter on the board

The Zener diode and the resistor divider would drop the voltage from 400 V down to below the max voltage of the Arduino board, which any of the voltages might be relative to the ground potential on the Arduino board under certain conditions.  The Arduino Due might be a good choice, because of multiple built in true A-to-D channels and the higher accuracy (digits resolution) than most other Arduino options.

The output of the box for each of the FOUR voltages would be connected to FOUR analog inputs.

Vph = the hot (black) coming from the plug
Vpr = the return (white) coming from the plug
Vlh = the hot (black) going to the load (devices to be powered)
Vlr = the return (white) going to the load

In the software you would probably want to measure the above four voltages in immediate succession (no delay between the four analogRead calls) every millisecond for a second, which will capture 60 cycles of data in 1,000 samples, enough to get three significant digits of accuracy in your power measurement.  The 60 samples of 4 channels can be thought of as 1,000 vectors of 5-dimensional data.  The fifth dimension is the time offset in milliseconds.

The software goal would be to calibrate the conversion of the 4 by 1,000 element array of analogRead integers to a 2 by 1,000 element array of doubles that represent instantaneous Voltage and current. Then power in Watts can be calculated from the Voltage-current data set.

When dealing with the 1,000 sample vectors, your loops will start with "for (int index = 0; index < 1000; ++ index) { ...".

You will need to convert your digital values representing the Voltages coming from your resistor divider to physical units.  These are the operations you would do on each sample.

V = Cv * (Vph - Vpr)
I = (Cih * (Vph - Vlh) - Cir * (Vlr - Vpr)) / R

V and I are the doubles that represent instantaneous Voltage and current respectively.

Cv, Cih, Cir, and R are also doubles. They are the calibration constants to convert the analogRead values to line voltages and currents.  A typical way to calibrate their values is to measure the RMS voltages across the three node pairs represented by each subtracted voltage pair in the inner parentheses above and the current, using some constant load.  A good load option would be some non-digital device that is fully warmed up and in some steady state.

From the voltages and currents and the digital values acquired from the four analog channels in the Arduino, with some algebra skill, one can determine the scaling factor C for each of the three cases, by dividing: (V1 - V2) / V, where V1 and V2 are the RMS values measured with the digital Voltmeter and V is the calculated RMS voltage from the samples.

R can be calculated by dividing the Voltage and current values V/I in accordance with the principles discussed in the articles referenced above.

Once you have calibrated your measurements for V and I in your block of 60 samples, the articles above give you some direction as to how to calculate your power in Watts RMS in a loop.

[1]: Search for "calculating rms watts from samples of voltage and current" via Google.


Help understanding how avrdude works with ArduinoISP and why its not working for me I am trying to use avrdude with a Mega2560 running ArduinoISP

Note: I have the 10uF cap on the Mega2560 RESET line as described by Ardunio.

Also, I am using avrdude/6.3 on Windows 10.  The Mega2560(ArduinoISP) is connected to the PC using an a USB cable - connection is COM8.

I have a couple of tasks I want to do

Update the firmware on my USBASP
Load Arduino boot on ATTINY85 dev board.

I started with Arduino IDE but moved to avrdude to better understand the problem

For #1:
Wired it per https://www.arduino.cc/en/Tutorial/ArduinoISP

AVR-ISP pin     MEGA-ISP pin
6/10 (name)

1/9 (MISO)      50
2/2 (VCC)       VCC
3/7 (SCK)       52
4/1 (MOSI)      51
5/5 (RESET)     53
6/10 (GND)      GND

I tried using the command:

avrdude -c arduino -p m8 -P COM8

I get the error

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xed
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xe0

avrdude done.  Thank you.

--UPDATE-- The error above was caused by not setting the BAUD rate. Now I get:

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.

What I really want to know is more of how this process works so I can better understand it and be able to debug the issues.

Is this an error communicating with the ISP (Arduino) or is it an issue with the ISP talking to the target (ATMega8B on USBAVR)?
What does "stk500" mean?  Is that the programming protocol, the ISP protocol, or something all together different?
Is this all documented somewhere?

The target board was not reset.

The "Arduino as ISP" sketch uses pin 10 to reset the target, not the SS pin. So even on Mega, wire reset of target to pin 10, not to pin 53.

  Is this an error communicating with the ISP (Arduino) or is it an issue with the ISP talking to the target (ATMega8B on USBAVR)?

the first error "not in sync" is a problem with communication with the programmer. it was caused by wrong baud rate. the "invalid signature" is a response from the programmer about target. if the signature could be read avrdude would print the target MCU type. all zeros signature is when the target doesn't answer. so check the wiring.

  What does "stk500" mean? Is that the programming protocol, the ISP protocol, or something all together different?

yes it is a ISP programming protocol. the "Arduino as ISP" implements only this protocol

  Is this all documented somewhere?

this is AVR MCU world, not Arduino. you can google avrdude reference, stk500 reference etc


Does the Arduino pro-micro 3.3v use an 8MHz crystal or a 16MHz crystal with a clock divisor of 2? I am trying to convert some 5v Leonardo-compatible boards to run at a lower 3-3.7v voltage, so that I can power my project using LiPo batteries.

As far as I can tell, the default Leonardo settings (and pro-micro settings) will not run at this voltage. When I power the boards (which expect 5v) from a lithium battery, typically the system does not start at all. My two theories are that either the 16 Mhz xtal oscillator does not start resonating, or that the brown-out detection of the boards precludes booting at the lower voltage.

I would like to modify the boards to run on lower power. Since the pro-micro exists in a 3.3v variant, I presume there is some way to get the Atmega32u4 chip working at lower voltages. I have reviewed the Atmega32u4 datasheet and schematics from sparkfun, as well as examined the fuse bit differences between the 3.3v and 5v versions of the pro micro. As far as I can tell, the only difference in configuration is the brown-out detection. The clock source settings are configured for a crystal between 8Mhz and 16Mhz, so this could be the same for both boards.

I wasn't quite able to understand the build system for the Catarina bootloader, which might give hints as to how the clock is handled. It seems like both the 3.3v and 5v boards bootloaders are built from the same source, but with a different "CPU frequency" variable. However, there are quite substantial differences in the .hex file outputs and I wondering if there is something fancier going on.

As far as I can tell, it's possible to get an 8MHz clock on the Atmega32u4 either by using a 16MHz xtal with a clock divisor of 2, or using an 8MHz xtal with a clock divisor of 1.

Since the pro-micro 3.3v is the "mainstream" supported board using the Atmega32u4 at a lower voltage, I would like to configure my project to be compatible. Which means I need to build in a compatible clock source, if possible.

Does anyone know more details of the pro-micro 3.3v/8Mhz configuration that might help clarify how to set this up?

On the schematic of the Sparkfun Pro Micro 3.3V/8 Mhz (here) a resonator of 16 MHz is drawn. But also is stated there: "Board is marked with combination of resonator frequency and regulator voltage". From this you can deduct that the 3.3V/8MHz and the 5V/16MHz versions don't have the same resonator and that the 3.3V/8MHz version most probably has a 8MHz resonator.


How to turn a LED if ultranonic HC-SR04 reading is on defined range for some interval My objective is if ultrasonic readings ranging between 1 to 10 cm and no distance change for 10 seconds or more, a LED will turn on. Here is my current code.

#define trigPin 7
#define echoPin 8
#define led 13
#define led2 12

long duration, distance, interval = 4000;
int detection = 0;

void setup() {
   Serial.begin (9600);
   pinMode(trigPin, OUTPUT);
   pinMode(echoPin, INPUT);
   pinMode(led, OUTPUT);
   pinMode(led2, OUTPUT);
   detection = millis();
}

void loop() {

   ultraSonic();

   if (distance > 0 && distance < 10 && (millis() - detection >= interval)) {
   digitalWrite(led, HIGH);
   digitalWrite(led2, LOW);
   } else {
   digitalWrite(led, LOW);
   digitalWrite(led2, HIGH);
   }

   Serial.print(millis());
   Serial.print(" - ");
   Serial.println(distance);

   delay(250);
}

void ultraSonic() {
   digitalWrite(trigPin, LOW);
   delayMicroseconds(60);
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(60);
   digitalWrite(trigPin, LOW);
   duration = pulseIn(echoPin, HIGH);
   distance = (duration / 2) / 29.1;
}

Sorry for my bad english.
Cheers.

void loop() {

   ultraSonic();

   if ((distance > 0) && (distance =< 10)) {
   digitalWrite(led, HIGH);
   digitalWrite(led2, LOW); // turning LED on
   } else {
   digitalWrite(led, LOW);
   digitalWrite(led2, HIGH); // turning LED off
   }

   Serial.print(millis());
   Serial.print(" - ");
   Serial.println(distance);

   delay(250);
}


Strange issue with FHT library for sound-reactive LED project I have been playing with the FHT library and have run into an interesting issue with fht_mag_octave() disrupting the output of my ADC actions.  Running on a MEGA ADK.

The idea is that I'm using FHT to read in the microphone input into A0, but also occasionally checking A2 pot to adjust the volume/brightness of the of the overall FastLED strip.

Here is the code in question...  it's barebones.  Just the standard FHT loop and then, every 100 loops, it checks A2 for the brightness setting.

#include <FastLED.h>

#define LED_PIN     6
#define BRIGHTNESS  200
#define LED_TYPE    WS2811
#define COLOR_ORDER GRB
#define NUM_LEDS 16
CRGB* const leds(NUM_LEDS);

#define LOG_OUT 1 // use the log output function
#define OCTAVE 1 //   // Group buckets into octaves  (use the log output function LOG_OUT 1)
#define OCT_NORM 0 // Don't normalise octave intensities by number of bins
#define FHT_N 128 // set to 128 point fht
#include <FHT.h> //

void setup() {
  Serial.begin(9600);
  delay(1000);
  FastLED.addLeds<NEOPIXEL, LED_PIN>(leds, NUM_LEDS);
  FastLED.setBrightness (BRIGHTNESS);

  // TIMSK0 = 0; // turn off timer0 for lower jitter (commented this out b/c I think this interferes with FastLED)
  ADCSRA = 0xe5; // set the adc to free running mode (0b11100101), prescalar=32 for higher ADC clock freq
  ADMUX = 0x40 | (0 & 0x07); // use adc0 (0b1000000)
  DIDR0 = 0x01; // turn off the digital input for adc0

}

int counter = 0;

void loop() {

  while (1) { // reduces jitter

    cli();  // UDRE interrupt slows this way down on arduino1.0

    for (int i = 0 ; i < FHT_N ; i++) { // save 128 samples
      while (!(ADCSRA & 0x10)); // wait for adc to be ready  in binary 0010000 (look for ADC Interrupt flag to be set to 1)
      ADCSRA = 0xf5; // restart adc (in binary 11110101...http://www.robotplatform.com/knowledge/ADC/adc_tutorial_2.html)
      byte m = ADCL; // fetch adc data
      byte j = ADCH;
      int k = (j << 8) | m; // form into an int
      k -= 0x0200; // form into a signed int
      k <<= 6; // form into a 16b signed int
      fht_input[i] = k; // put real data into bins

    }

    fht_window(); // window the data for better frequency response
    fht_reorder(); // reorder the data before doing the fht
    fht_run(); // process the data in the fht
    fht_mag_octave();
 //   fht_mag_log();

    // every 100th loop, adjust the volume accourding to the value on A2 (Pot)
    if (counter > 10) {

      ADMUX = 0x40 | (2 & 0x07); // set admux to look at Analogpin A2

      while (!(ADCSRA & 0x10)); // wait for adc to be ready
      ADCSRA = 0xf5; // restart adc
      byte m = ADCL; // fetch adc data
      byte j = ADCH;
      int brightness = (j << 8) | m; // form into an int

//      brightness = map(brightness, 0, 1023, 0, 255);
      Serial.print("b: ");
      Serial.println(brightness);

      FastLED.setBrightness (brightness);

      ADMUX = 0x40 | (0 & 0x07); // set admux back to look at A0 analog pin (to read the microphone input
      counter = 0;
    }

    counter++;
    sei();

  }
}

Here's the output as shown (basically, it's outputting nonsense, non-int values):

b: ⸮
b: ⸮
b:
b:
b: ⸮
b: ⸮
b:
b: ⸮
b: ⸮
b:
b: ⸮
b: ⸮
b: ⸮
b:
b: ⸮
b: ⸮
b:

b: ⸮
b: ⸮
b:

If I comment OUT the fht_mag_octave line and uncomment fht_mag_log(), here is the output (which looks right as I turn the Pot pin):

b: 0
b: 0
b: 0
b: 0
b: 0
b: 9
b: 35
b: 38
b: 48
b: 85
b: 143
b: 171
b: 188
b: 204
b: 224
b: 245
b: 280
b: 332

The issue is that the A2 value "brightness" does not read properly if I use fht_mag_octave().  If I comment out only the fht_mag_octave() line, it works perfectly.  I can also use fht_mag_log instead, and it works fine.

This makes me think that there is something that fht_mag_octave() does something that interferes with the ADC registers.

Any ideas?

Thanks to @TonyStewart for suggesting that I just do a successive A2 read.

I modified the code by just repeating the A2 read.  b1 is the first read, and b2 is the 2nd read.

  while (!(ADCSRA & 0x10)); // wait for adc to be ready
  ADCSRA = 0xf5; // restart adc
  byte m = ADCL; // fetch adc data
  byte j = ADCH;
  int brightness = (j << 8) | m; // form into an int

  Serial.print("b1: ");
  Serial.print(brightness);

  while (!(ADCSRA & 0x10)); // wait for adc to be ready
  ADCSRA = 0xf5; // restart adc
   m = ADCL; // fetch adc data
   j = ADCH;
   brightness = (j << 8) | m; // form into an int

  Serial.print("   b2: ");
  Serial.println(brightness);

And the readout looks good.  B1 is now legible, but incorrect/low.  B2 looks accurate and scales all the way to 1024 as I wanted.

b1: 0   b2: 688
b1: 0   b2: 739
b1: 0   b2: 816
b1: 20   b2: 915
b1: 118   b2: 1016
b1: 152   b2: 1023
b1: 172   b2: 1023
b1: 165   b2: 1023
b1: 180   b2: 1023
b1: 188   b2: 1022
b1: 184   b2: 931
b1: 127   b2: 713
b1: 0   b2: 615
b1: 0   b2: 532
b1: 0   b2: 436
b1: 0   b2: 327
b1: 0   b2: 304
b1: 0   b2: 452

I'm still curious about the reasoning behind this...but I'm glad that there is a solution, and not one that is too painful.


Wiring Multiple MPU 6050 to Micro/Lenardo disclaimer I am new at hardware/circuits
I am currently trying to connect two MPU-6050 to a single Micro board.
In addition, there are 5 additional buttons to be connected.
I am under the impression to connect multiple devices to the I2C bus, there must be unique addresses. I read there was a way to make unique addresses (https://playground.arduino.cc/Main/MPU-6050/#multiple).
However I am not sure of the wiring or if the voltage/resistors/anything is supposed to be located.
I have a sketch of what it may look like.

Can anyone help me verify that this is the proper configuration? Or what a proper configuration would look like?

Buttons are just buttons. You can have them "active high" with pulldown resistors as you have there (10K is fine. The actual value doesn't really matter, just don't have it too low or excess current will be drawn), or "active low" without resistors and connecting to ground when pushed instead of VCC and use INPUT_PULLUP. The choice is yours. There's no real benefit in this situation to either way of doing it.
The critical part is your AD0 connection. Whether you connect one to ground and leave the other unconnected, or connect one to VCC and leave the other unconnected, depends entirely on the design of the breakout board. It should have a resistor on the AD0 pin internally that either connects it to GND or to VCC. If it connects to GND then you need to link that pin to VCC to override it. If it connects it to VCC (or more likely 3.3V) internally then you need to connect it to GND to override it.
To find out which you will have to either consult the documentation or schematic for the board or measure the voltage at the AD0 pin. If it measures 0V (within a few mV) then it connects to ground and you will have to connect it to VCC to override it. If it measures more (probably nearer 3.3V) then connect it to ground to override it.
Because those chips are 3.3V and the board contains a 3.3V regulator (if your boards are the same as you picture in your wiring diagram) the chances are that the AD0 is pulled up to 3.3V so you just need to connect one to ground.
So it looks to me like your wiring diagram is most likely suitable and correct, pending confirmation of the pullup/pulldown in the AD0 pin.


Arduino graphic interface I succeeded in programming a system of thermoregulation using Arduino.  This system holds the temperature of a plate at 37°C. I used a PID corrector to realize this.

What I want to do now is make a graphic interface that can communicate with the Arduino, allowing me to see a graph of the temperature.

I would like an explanation of how to send temperature data to a graphic interface using Arduino Uno.

There are two main possibilities.

The first one is to make a GUI on the Arduino itself. Add a TFT screen, touchscreen if you want the user to interact, or a non-touchscreen (cheaper) if you just want to display. Then, within your Arduino code, you can display the temperature data, and if you go the touchscreen route, interact with the user.

I own a couple of Arduino Esplora devices, and they would be near perfect for this, as they have a non-touch TFT screen, a joystick, buttons and a pot. All the equipment you need to display the temperature. Oh, and it has temperature and light sensors onboard.

The second way would be to make a GUI on your desktop/laptop machine. In your Arduino code, you could send your temperature data through USB (Serial), Bluetooth (SoftwareSerial), WiFi, Ethernet, nRF, etc etc etc. If you don't mind having the Arduino tethered to your computer by a cable, USB<-->Serial is the easiest solution. The software on the computer listens on a serial socket and when it receives temperature data, it displays it within its GUI.

HTH


Super-fast USB communication; how is it possible? On Arduino forums, there's a post where someone improved the USB communication and made it super-fast. I don't understand how he did this, and I'm trying to recreate this, but failing.
My test code
I made a simple program on Python for testing; here it's:
import serial
import sys
import datetime

ser = serial.Serial(
   port = 'COM9',
   baudrate = 26*115200, #biggest number acceptable by python
   parity = serial.PARITY_NONE,
   stopbits = serial.STOPBITS_ONE,
   bytesize = serial.EIGHTBITS
)

if ser.isOpen() == False :
   ser.open()
   if ser.isOpen() == False :
      print("Can't open serial port")
      sys.exit(1)

start = datetime.datetime.now()
s = b'abc'*10000
ser.write(s)
total_len = len(s)
end = datetime.datetime.now()
speed = total_len/(end - start).total_seconds()/1e6
print("Speed: " + str(speed) + " MB/s")

And I made a simple Arduino program to read:
char buf[500];

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

void loop() {
  if (Serial.available() > 0) {
     Serial.readBytes(buf, 500);
  }
}

With this, my best result was 0.2 MB/s with my Arduino mega. However, on that post, they reached 12 Mbit/s = 1.5 MB/s!!!!! This is insane!
Atemmpting to achieve their result:
Apparently Arduino libraries are different than before, so just taking their code and putting it in my arduino\avr\cores\arduino directory doesn't work. So I started trying to edit the code myself. I'm a C++ dev, so supposedly this should be doable... but...
The problem I faced
So eventually, the problem I faced was that there are two Serial communication modes (apparently) UART and CDC. The code from the forum uses CDC, while my Arduino IDE uses UART. I tried enabling CDC using:
#define USBCON

but this lead to the error:
error: #error "Targets with both UART0 and CDC serial not supported"

At this point I don't know how to continue, as I'm not a hardware expert. But I'd like your opinion on this whole thing:

Is it possible to get these speeds? How?
If it's, why is it not in the default Arduino library?
In case there's no easy answer for the other questions, is switching from UART to CDC easy, so that I could continue my testing?

Is it possible to get these speeds? How?

Not without a 32-bit Arduino with a USB interface.

  If it's, why is it not in the default Arduino library?

Because you can't use it on an 8-bit Arduino without a USB interface.

  In case there's no easy answer for the other questions, is switching from UART to CDC easy, so that I could continue my testing?

Yes, get a 32-bit Arduino with a USB interface such as the Arduino Due that the poster of that thread used.


Arduino Uno lag in simple loop I have a simple Arduino sketch which I have been playing with on my Uno.

The idea is simple, the user turns a potentiate (pin A2), when they pass a certain threshold a LED is turned on (pin 7).

Here is the code:

// Digital pins
const byte ledPin = 7;

// Analog pins
const byte userInputPotPin = A2;

// Potentiometer constants
const int userInputPotMinimumValue = 0;
const int userInputPotMaximumValue = 1023;
const int userInputMinimumValue = 1;
const int userInputMaximumValue = 100;

// Variables
const int threshold = 90;

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

    // Digital pins
    pinMode(ledPin, OUTPUT);

    // Analog pins
    pinMode(userInputPotPin, INPUT);
}

void loop()
{
    int rawValue = analogRead(userInputPotPin);
    int mappedValue = map(rawValue, userInputPotMinimumValue, userInputPotMaximumValue, userInputMinimumValue, userInputMaximumValue);

    String messageText;
    messageText += "Raw:   " + String(rawValue) + "\t";
    messageText += "Mapped:" + String(mappedValue);

    if(mappedValue > threshold)
    {
        messageText += "\tThreshold exceeded!";
        digitalWrite(ledPin, HIGH);
    }
    else
    {
        digitalWrite(ledPin, LOW);
    }

    Serial.println(messageText);

    delay(100);
}

The problem is that when it is run the hardware is very unresponsive - I can turn the pot, but I don't see the light change for several minutes. The log messages in the serial monitor also seem to be lagging behind.

I have tried:
* Removing the Serial statements (so there is no serial communication when the sketch is running), and just observing the LED. This makes no difference.
* Increasing the value in the delay up to 1000. This makes no difference in the responsiveness.

However, when I run the sketch on my Mega2560 the problem goes away and the circuit is as responsive as I expect.

Is there something wrong with my Uno board?

It turns out the problem was the A2 pin on the board.

When I used the A0 pin (or a different board) the problem goes away.

I realised something was wrong when I noticed the values from the pot were strange (I expected values in the range 0 - 1023, but was receiving values from 170-250 ish).


Limit to number of sensors attached to Arduino Is there any limitation on how many sensors can be attached to one Arduino board? I am making elderly smart ban and I want to use GPS, GSM, gyroscope, pulse sensor, temperature sensor and I2C OLED. Right now I have only gyroscope, pulse sensor and GPS connected to Arduino Uno but I would like to add more stuff and also I am considering using Arduino Nano or only ATmega328P chip for finished product. My main concern is power.

There is no answer that can be given to you that is "correct". However, there are things for you to consider in your design process:

Can you fit all the code in flash, and the required variables in RAM?
Does the chip have all the IO you need, and can you use the required internal / interfacing peripherals in the right combinations to satisfy your requirements
Do the devices fit within your power budget (battery capacity, required run-time, power regulation efficiency).

The Arduino is just a component. It belongs in a circuit, and that circuit is what determines everything else. The ATMega328P has certain power requirements, as do all the other components in your circuit. It is up to you to design the right power system to provide that power with the right efficiency and power saving options (switching off circuit segments when not needed to save power), etc.

For prototyping and experimenting the Arduino provides a rudimentary power supply which is wildly inefficient. Not recommended for any battery powered scenario or any high current usage.


Gesture sensing TV coffee table - what sensors would you use? A 32 inch flat screen was embedded in a coffee table and covered by a protective layer of glass. Sensors around the edge of the glass surface need to be able to detect the precise location of an object on the glass so that a mouse cursor can be controlled with a stylus.

What sensors would you use to ensure accuracy of stylus location above the screen?

Perhaps if you drop the monitor an inch or 2 away from the glass you can use a Frustrated Total Internal Reflection (FTIR) IR scheme.  But at that shallow angle it will be tricky and may require several cameras around the edges.

added later...

Should mention the parallax problem given there is a gap of an inch or more between the monitor and the touch screen.  FTIR is better when you project the image onto the touch screen.

If you don't mind lower resolution, I believe the micro dose dispenser soda machines use a capacitive touch wire mess embedded in the transparent plastic front panel.  Although micro dose dispensers appear to only need to emulate about 100 to 200 buttons.  Not enough to control a mouse with any accuracy.  But enough to control a GUI designed with such constraints.

Loose high resolution capacitive touch screens can be bought with out a monitor.  However they tend to be much smaller then 32 inches.


Transient buttons control non-transient behaviour of LEDs Imagine a system where you have two transient non-exclusive buttons and two LEDs.

When you press button 1, the LED 1 is HIGH and LED 2 is LOW (and stays that way).

When you press button 2, the LED 1 is LOW and LED 2 is HIGH (also stays that way).

Which C++ code allow me, to keep the LED 1 turned on indefinitely (until button 2 is pressed)?

Basically, my problem is, that the buttons are transient and the behaviour of LEDs shouldn't be.

Here is code, that would work for pernament exclusive buttons, but doenst work for transient non-exclusive buttons.

if (digitalRead(button1) == HIGH)
{
    led1 = HIGH;
}
else
{
    led2 = LOW;
}
if (digitalRead(button2) == HIGH)
{
    led2 = HIGH;
}
else
{
    led2 = LOW;
}

Don't react to the button by changing the LED; change a state-variable in memory, instead. That saves the information of which button was most recently pressed. Then, each time through your loop, set your LED's according to the contents of that persistent variable. Remember that it will have to be a static variable (global or static local), as an automatic one will disappear and reappear after each exit and re-entry to loop(), and you cannot count on its contents when that happens.

Update:

  How do I prevent overwriting the state variable with different input ?

You don't prevent it - you must over-write it. The purpose of the state variable is to remember which button was last pressed. I had in mind something like the following, where lastButton saves the number of the most recent button:

void setup(){
   pinmode(LED1PIN, OUTPUT);
   pinmode(LED2PIN, OUTPUT);
   pinmode(BUTN1PIN, INPUT_PULLUP);  // you might not want the pullup
   pinmode(BUTN2PIN, INPUT_PULLUP);  //  depending on your wiring.
}

void loop(){
   static uint8_t lastButton = 0;

   // Save the number of the last button pressed.
   if (digitalRead(button1) == HIGH)
      lastButton = 1;
   else if (digitalRead(button2) == HIGH)
      lastButton = 2;

   // Set the LEDs according to most recent button
   // Note that at program-start, when no button has
   // been pressed yet, this code leaves both LED's off.
   if (lastButton == 1)
   {
      digitalWrite(LED1PIN, HIGH);
      digitalWrite(LED2PIN, LOW);
   }
   else if(lastButton == 2)
      digitalWrite(LED1PIN, LOW);
      digitalWrite(LED2PIN, HIGH);
   }
}


Difference between 3.3v & 5v Im quite new to arduino in general and i'm sorry for the beginner question.
could someone explain what the 3.3v and 5v on boards do? I know their voltages. but can you run one on the other? whenever i try to search about it i see people saying that most newer modules are running on 3.3v so they convert their 5v arduino to 3.3v. something about if you run one on the other it could break it.

the arduino I bought looks like it has both! is that even possible?
 I also purchased this LED matrix as I wanted to make a wifi enabled scrolling text display. the matrix says it requires 5v. since this arduino says vin is 5-12v the two should connect and work properly, right?

The difference for different voltage boards lies in the parts, that are soldered on it. Often microcontrollers support more than one supply voltage, but impose different performance limits on the system. Take for example the Arduino Uno: It uses the Atmega328p, which can run both on 3.3V and 5V. But on the UNO there is a 16MHz quartz, which generates the controllers clock signal. The Atmega328p cannot run 16MHz with only 3.3 volts. To run a board on a voltage, for which it wasn't directly build, mostly requires you to resolder it with the correct parts.

  whenever i try to search about it i see people saying that most newer modules are running on 3.3v so they convert their 5v arduino to 3.3v

There are special chips, called voltage regulators/converters. They come with various working principles, but basically they are converting one voltage to another. The Arduino Uno has one connected to Vin, so that you can apply between 7V and 12V to Vin and the Arduino itself will only see the 5V it get's from the regulator. Some modules also have a voltage regulator, but not all. Be careful not to provide more than the specified voltage to any board or you may destroy it.

  the arduino I bought looks like it has both! is that even possible?

First, as Juraj wrote, this is not an Arduino. It is an ESP8266, a totally different chip and board. But you can also program it through the Arduino IDE, without it being an Arduino. Second: When they write, that you can provide it with either 3.3V or 5V, they mean, that you can provide 5V through the USB jack and a voltage regulator will convert it to 3.3V for the ESP, which runs completely on 3.3V. You should not connect 5V to any other pin.

  since this arduino says vin is 5-12v the two should connect and work properly, right?

As stated above the 12V is only, what you can at maximum provide at Vin. The ESP8266 runs on 3.3V, so you will have to provide 3.3V (or more over the Vin pin). The LED matrix runs at 5V, as you stated. So you need a 5V source and a level shifter for the 2 lines between the ESP8266 and the matrix. If you connect them directly, you would damage the ESP8266. So: No, you cannot use it directly. It is up to you, if you want to use a level shifter or buy another matrix display, which can be controlled by a 3.3V signal.


Cannot get esp8266 - 12 wifi module to always read analogRead incoming voltage accurately So I have and arduino uno that is firing an output on pin 8. This code is not in this file just to be clear. From there Im taking that output and using it to fire pin 0 on the wifi module. Im using pin 0 because from what I understand all other pins have a pullup or pulldown resistor. When pin 0 is hot I want to print that value. Sometimes it works when I do it other times the analog values reads very low. I am using the 3.3v from the arduino uno and I plan to get a voltage regulator for the wifi module but would this cause this kind of issue? I am very very new to arduino so if anyone has any ideas I would appreciate a very dumbed down explanation. Thanks a lot. Also the reason why I have the delay turned down so low is because it seemed to make the analog signal pick up more often. Im not sure why this would matter but at a delay of 3000 it would almost never change analog value but when I turned the delay down to one the value came through much more consistently. Currently the code just outputs low analog numbers and occasionally pops up 1023 when voltage is applied but not consistently. And sometimes it just stops altogether until I keep trying for a while. I am getting voltage to the pin however so I know I have a complete circuit and power.

include

#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

const char* ssid = "ENDOWED Underwear";
const char* password = "endowwear";

HTTPClient http;

static const uint8_t D0   = 16;
static const uint8_t D1   = 5;
static const uint8_t D2   = 4;
static const uint8_t D3   = 0;
static const uint8_t D4   = 2;
static const uint8_t D5   = 14;
static const uint8_t D6   = 12;
static const uint8_t D7   = 13;
static const uint8_t D8   = 15;
static const uint8_t D9   = 3;
static const uint8_t D10  = 1;

int featherPin = D3;

void setup() {
  Serial.begin(115200);
  pinMode(featherPin, INPUT);

  WiFi.begin(ssid, password);

  while(WiFi.status() != WL_CONNECTED) {
    delay(10);
    Serial.println("Waiting for connection");
  }
}

void loop() {
  int sensorValue = analogRead(featherPin);

  if (WiFi.status() == WL_CONNECTED) {
        Serial.println("yay connect");

        http.begin("http://10.150.40.121:3000/");
        http.addHeader("Content-Type", "text/plain");

        int httpCode = http.POST("Message from ESP8266");
        String payload = http.getString();
//        Serial.println(payload);
        http.end();

    } else {
        Serial.println("Error in Wifi connection");
    }

    if (sensorValue > 850) {

      http.begin("http://10.150.40.121:3000/home");
      http.addHeader("Content-Type", "text/plain");

      int httpCode = http.POST("Message from ESP8266");
      String payload = http.getString();
      Serial.println(payload);
      Serial.print("hi");
      http.end();
      } else if (sensorValue < 850) {
        Serial.print(sensorValue);
//        Serial.println("I am not hot");
      }

//  digitalWrite(trigPin, LOW);
//  delayMicroseconds(1);
//  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(2);
//  digitalWrite(trigPin, LOW);
//
//  pinMode(echoPin, INPUT);
//  duration = pulseIn(echoPin, HIGH);
//
//  inches = (duration / 2) / 74;
//  Serial.println(inches);
//
//  spaceIntruded = inches;
//
//  if (spaceIntruded <= 50 || spaceIntruded >= 900){
//      digitalWrite(ledPin, HIGH);
//      digitalWrite(hornPin, HIGH);
//      Serial.println("Intruder Detected!");
//      Serial.println("Sending text Notification...");
//      delay(500);
//      Serial.println("Armed...");
//  }
//
//  else{
//    digitalWrite(hornPin, LOW);
//    digitalWrite(ledPin, LOW);
//  }
    delay(1);

}

Analog to Digital conversion is one aspect1 where the ESP8266 is very poor. It has a single ADC pin which can read a maximum of 1V.

That pin is the only pin you can use with analogRead(). Any attempts to use any other pin just use that pin instead. The parameter (pin number) to analogRead(pin) is ignored and no matter what you do that one single ADC pin is what is being read. Also the pin cannot be used for anything else. None of the digital functions can be used with it since the pin doesn't have a GPIO number associated with it.

Some boards include a simple voltage divider on the ADC pin to allow higher voltages to be read, such as the NodeMCU:

If your board doesn't have such a divider you will have to implement it (or something similar) to be able to read the 3.3V incoming voltage.

1 The ESP8266 is great for WiFi but pretty poor for everything else. It is seriously starved of internal peripherals (it doesn't even have I²C). For a more feature-rich solution you might consider upgrading to the ESP32.


Is it right to connect Serial module directly? I find a strange thing that the led is on when power is off. And it's the problem of my serial module. Arduino may get power from my serial module. My serial module use max2322. I don't if it will harm my arduino or has influence to my program.
Is it needed to add a resistance?

Maybe the serial module has a serial cable attached to it which gives a voltage.

I think it can hurt, since you have two voltage sources, one from the Arduino and one from the Serial cable. Not using the power wire from the serial cable should fix the problem.

A resistor will not help because you still have two power sources in case you have both voltage from the Arduino (adapter/USB) and serial.


Arduino should check the same way like a USB keyboard or a USB mouse, if turned on notebook is connected I have a USB HUB and have connected to it a USB keyboard and a USB mouse. As long I have not connected a Notebook to it those devices don't turn on. 5V is always turned on! So I could charge my phone. How do they know there is no notebook connected? My Arduino is always on. I want to emulate this with an Arduino. Without the need of extra software on a notebook, the Arduino should be able to tell if a notebook is connected to the USB Hub or not. Please help.

With Arduino Nano, you don't have control over the USB, because it is handled by the USB-to-TTL-Serial chip on the board. The MCU is to this adapter connected only with RX and TX of the Serial interface.

With Arduino Micro you could retrieve the state of the USB connection, because he MCU ATmega32u4 has a build in USB support an handles the USB connection from application (sketch).


Ultrasonic Sensor - JSN-SR04T 2.0 I would like to use the JSN-SR04T 2.0 in order to find the depth of a body of water. Once I test the sensor in a body of water, the distance measurements are then constant at about 20 cm. I then changed my distance formula to account for the speed of sound in water, but the measurements are still constant despite change in the body of water. Does anyone have any recommendations on how to obtain better measurements underwater?

#define trigPin 2
#define echoPin 3

// Define variables:
long duration;
int distance;

void setup() {
  // Define inputs and outputs
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  // Begin Serial communication at a baudrate of 9600:
  Serial.begin(9600);
}
void loop() {
  // Clear the trigPin by setting it LOW:
  digitalWrite(trigPin, LOW);

  delayMicroseconds(5);
 // Trigger the sensor by setting the trigPin high for 10 microseconds:
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  // Read the echoPin. pulseIn() returns the duration (length of the pulse) in microseconds:
  duration = pulseIn(echoPin, HIGH);

  // Calculate the distance:
  distance = duration*0.034/2;

  // Print the distance on the Serial Monitor (Ctrl+Shift+M):
  Serial.print("Distance = ");
  Serial.print(distance);
  Serial.println(" cm");

  delay(100);
}

According to the data sheet the minimum target distance is 20cm in the open air at a 343 m/s
The speed of sound in water is 1481 m/s so the minimum distance would be 20cm x 1481 / 343 = 86cm.

You cannot measure distances under 83cm in water.


Cannot create a PWM with 20% duty cycle using micro() timer I have been working with Arduino for almost a year, because I found it easy for beginners in electronics. But now, I have a major problem, I'm trying to get rid of my delay() function because I want my Arduino Nano to handle to tasks at once:

1-Read MIDI data and transfert it into a pwm signal, as well as monitoring the on and off of the signal (which are bytes). This part works correctly, but i'm not using the mirco(), i'm using a library called Timer1.

2-Generate a PWM signal of 20% dutycycle with a frequency ranging from 1 to 103 Hz using a potentiometer to adjust the frequency.

So, what happens is that the signal I measure on my oscilloscope is a PWM at 50% duty cycle and with frequencies that don't match my calculations at all. Also, It doesn't change smoothly, the frequency goes from 159Hz to let's say 180Hz only at one particular point on the potentiometer, just like if all the rest of it was useless. I decided to monitor all my values with Serial and everything was good, the values were OK and nothing was wrong. Then I decided to change all my variables to floats so I could maybe get more precision... Didn't work as well. So now I'm kind of desesperate.

//MANUAL MODE TEST WITH MICROS()
//VARIABLES ASSIGNEMENT
unsigned long current=0.0;
unsigned long previous=0.0;

float TimeOn = 0.0;
float TimeOff = 0.0;
float manuelF = 0.0;
float sensor = 0.0;

int pin = 11;

byte state = LOW;

//SETUP AND PIN ASSIGNEMENT
void setup() {
  pinMode(9, OUTPUT);//MUSIC SIGNAL OUTPUT
  pinMode(11, OUTPUT);//MANUAL SIGNAL OUTPUT
  pinMode(A5, INPUT);//POTENTIOMETER MANUAL
  pinMode(A6, INPUT);//POTENTIOMETER MUSIC
  Serial.begin(9600);
}

void loop() {

  sensor = analogRead(A5);
  manuelF=((sensor+10.0)/10.0); //Capture la fréquence sur A5
  TimeOn=1000000.0*(0.2*(1.0/manuelF));
  TimeOff=1000000.0*(0.8*(1.0/manuelF));
  current = micros();

  Serial.println(TimeOn);

  //Serial.print("A5 read:");
  //Serial.println(analogRead(A5),8);
  //Serial.println("-----------");
  //Serial.print("Fréquence: ");
  //Serial.println(manuelF,8);
  //Serial.print("timeon:");
  //Serial.println(TimeOn,8);
  //Serial.print("timeoff:");
  //Serial.println(TimeOff,8);

  if ((state == LOW)&&(current - previous >= TimeOff)){
      state = HIGH;
      digitalWrite(pin,state);
      previous = current;
    }
  else{
    if (current - previous >= TimeOn){
      state = LOW;
      digitalWrite(pin,state);
      previous =current;
    }

  }
 }

As you can see I'm still monitoring the TimeOn variable. Well, It shows exactly (to 4 micro seconds precise) the time that it is supposed to be ON.

My output at that moment is a 50% duty cycle with a frequency of 53Hz when I pass the 7k on the potentiometer (it is a 10k). Before that, it doesn't even outputs a signal.

What is going on?

EDIT#1:
I have done the modifications that @Edgar Bonet suggested me. It partially worked. What i'm left with now is a PWM that can go from 1Hz to 5Hz almost smoothly with the duty cycle at 20% for 1Hz and going up to 22% at 5Hz. After that I only get very discrete frequencies: 7.99Hz, 9.55Hz, 10.66Hz, 11.99Hz, 13.70Hz, 19.18Hz, 21.32Hz, 26.65Hz, 35.54Hz and then it takes almost half a turn before it changes to 53.3Hz until the end. The duty cycle at 35Hz is 33.3% and it reaches 50% at 53.3Hz... What logic is that....

You wrote:

if ((state == LOW)&&(current - previous >= TimeOff)){
    state = HIGH;
    digitalWrite(pin,state);
    previous = current;
  }
else{
  if (current - previous >= TimeOn){
    state = LOW;
    digitalWrite(pin,state);
    previous =current;
  }

While you probably mean:

if (state == LOW && current - previous >= TimeOff) {
    state = HIGH;
    digitalWrite(pin, state);
    previous = current;
}
else if (state == HIGH && current - previous >= TimeOn) {
    state = LOW;
    digitalWrite(pin, state);
    previous =current;
}


Sending serial bits in arduino I am a newbie in Arduino and serial communication. I am working on a project that use Arduino to send data bits to an actuator using RS232 communication protocol. In order to control the actuator, an instruction consists of 6 bytes must be sent with 9600 baud, no hand shaking, 8N1 format.

Here are the instructions:
Byte 1 - Device, Byte 2 - Command, Byte 3 - Data(LSB), Byte 4 - Data, Byte 5 - Data, Byte 6 - Data(MSB)

For example to send 1, 20, 1, 1, 0, 0 (Move the actuator to absolute position of 257 microsteps)

This is my draft code. How can I send start and stop bit? I am confused on sending start and stop bit. The Serial.write() is sending binary data as a byte. Does it mean that I write Serial.write(20), the compiler will send the data in 00010100 binary format? I am quite frustrated with serial communication.

The start and stop bit are already included as part of the UART protocol. When you send a byte it first sends the start bit, then the byte, then the stop bit. You don't need to do anything to make those bits send.

20 is actually sent as 0001010001

So your code will just be a series of Serial.write() calls for each byte you want to send.

Serial.write(1);
Serial.write(20);
Serial.write(1);
Serial.write(1);
Serial.write(0);
Serial.write(0);

Or as an array:

uint8_t data[6] = {1, 20, 1, 1, 0, 0};
Serial.write(data, 6);


Is TM4C123 similar to Arduino? I'm currently studying embedded systems on eDx.
https://courses.edx.org/courses/UTAustinX/UT.6.01x/1T2014/info (must login to see)
http://users.ece.utexas.edu/~valvano/edX/index.html (don't need to login)
and I found out that TM4C123 is quite similar to Arduino.
but I haven't worked TM4C123 yet.(I ordered it and I'm waiting for it)
 I don't know much about it.
and it's not that popular as Arduino I guess.
so If anyone has used Tm4C123, please give me some information compared to Arduino.

The Tiva C LaunchPad is comparable to the Arduino Due in power and capabilities, but is incompatible with the stock Arduino ecosystem. It uses "BoosterPacks" rather than Shields, and Code Composer Studio (or other [some non-gratis] tools) instead of the Arduino IDE and libraries.

The Energia IDE is a port of the Arduino IDE and significantly simplifies configuration and programming Tiva C launchpads.

Beware of odd quirks with the Tiva C Launchpad board, such as the 0-ohm shunts that must be removed if you want all pins to be completely independent.


Do I need the Ground and 5 V pin connect to Led? I am building an ambilight. So I bought a 3 pin LED Strip which I power with the USB hub from my TV. Next step is to connect it to the Arduino Nano. Is it OK when I only use the dataport from the Aduino and the power only from the television?

I think it is not a good idea to power the LED strip via USB.

Normally USB delivers a maximum of mA  (see below). Assuming you have 30 LEDs (minimum for a normal LED strip), and each LED gives 40 mA (maximum), this is already more than what most USB ports can deliver. This can ruin your USB port.

For the Arduino Nano you can use the 5 V, and you should connect all GNDs together.

But you will need a decent adapter anyway for the LED strip, so than you can power your Arduino Nano from the adapter you use for the LED strip.

Update

According to Wikipedia USB power

  Low-power devices (such as a typical USB keyboard) may draw at most 1
  unit load (1 unit load is 100 mA for USB devices up to USB 2.0, while
  USB 3.0 defines a unit load as 150 mA), and all devices must act as
  Low-power devices when starting out as unconfigured.

  High-power devices (such as a typical 2.5-inch USB Hard Drive) draw at least 1 unit load and at most 5 unit loads (500 mA) for
  devices up to USB 2.0 or 6 unit loads (900 mA) for SuperSpeed devices.


Sending data from Arduino to laptop via bluetooth using java I intend to establish communication between my laptop and Arduino via Bluetooth. I'm using BlueCove Java API. I'm unable to understand how to send data to Arduino using this. There are no clear examples available on the internet regarding how to establish the communication between these two. Could somebody provide any information on this?
I just want to send some string to Arduino, based on which it must send back something to the laptop. Any help on this would be greatly appreciated. Thank you.

I was able to establish bluetooth communication between Arduino and my laptop successfully. I made some observations, which I'd like to share. BlueCove library which I've been using, ultimately communicates to the Arduino by constructing a bluetooth URL. This bluetooth URL is of the form btspp://bluetooth_address_without_colon:1;authenticate=false;encrypt=false;master=false.
To find the bluetooth address of a device, enter the following command in the terminal

hcitool scan

This will display a list of devices along with their addresses.
For instance, if my HC-05 has an address  20:16:10:09:47:93 then the bluetooth URL can be formulated as
btspp://201610094793:1;authenticate=false;encrypt=false;master=false.
Note that the '1' here represents the rfcomm channel. By observation, I've found that HC-05 modules use rfcomm channel 1.
In your project, ensure that you import the two jars of BlueCove libraries viz bluecove-2.1.0.jar and bluecove-gpl-2.1.0.jar (latest version). You can download them from here.
This is the Java code for communicating with the Arduino to turn an LED ON/OFF:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
public class HC05 {
boolean scanFinished = false;
String hc05Url =
"btspp://201610094738:1;authenticate=false;encrypt=false;master=false"; //Replace this with your bluetooth URL
public static void main(String[] args) {
try {
new HC05().go();
} catch (Exception ex) {
Logger.getLogger(HC05.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void go() throws Exception {
StreamConnection streamConnection = (StreamConnection)
Connector.open(hc05Url);
OutputStream os = streamConnection.openOutputStream();
InputStream is = streamConnection.openInputStream();
os.write("1".getBytes()); //'1' means ON and '0' means OFF
os.close();
byte[] b = new byte[200];
Thread.sleep(200);
is.read(b);
is.close();
streamConnection.close();
System.out.println("received " + new String(b));
}
}

This the Arduino code for controlling the LED:

int ledPin = 13;
int flag = 0;
int receivedData;
void setup() {
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
Serial.begin(9600);
}
void loop() {
if(Serial.available()>0){
receivedData = Serial.read();
flag = 1;
}
if(flag == 1){
switch(receivedData){
case '0':
digitalWrite(ledPin, LOW);
Serial.println("LED Turned OFF");
break;
case '1':
digitalWrite(ledPin, HIGH);
Serial.println("LED Turned ON");
break;
default:
Serial.println("Nothing here");
break;
}
flag = 0;
receivedData = 12;
}
Serial.flush();
}

Thanks to @Sigma for sharing some valuable information

Reference:

https://stackoverflow.com/questions/33473926/best-practice-java-serial-bluetooth-connection-hc-05


Wiring a potentiometer to control a 9V battery powering 2 LEDs in series I am trying to build an array of LEDs where their brightness is controlled by a potentiometer.  The LCD will display the percentage of brightness based on the potentiometer.  I am able to successfully control the brightness of a circuit with only one LED.  However, I am having trouble with 2 two LEDs in series (which are in parallel with other sets of 2 LEDs in series).  And I believe the problem is that the Arduino is only supplying enough voltage to power one LED (maybe < 5V).  How can I properly wire a 9V battery to this circuit in which the potentiometer can control the amount voltage coming from this battery?  Are Arduinos only capable of controlling <5V with a potentiometer?

Here is my code:

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int potPin = A0;
int ledPin = 6;
int potValue = 0;

void setup() {
  pinMode(potPin, INPUT);
  pinMode(ledPin, OUTPUT);
  lcd.begin(16, 2);
  lcd.print("Potentiometer");
}

void loop() {
  potValue = (analogRead(potPin)/10.02);
  analogWrite(ledPin, potValue);
  lcd.setCursor(0,1);
  lcd.print(potValue);
  lcd.print("%");
  delay(100);
  lcd.print(" ");
  delay(1);
}

And here is a picture of my circuit setup:

Yes, Arduino is a 5V microcontroller, meaning it can directly control 5V circuits only. You might incur in problems also trying to deal with 3.3V circuits, even if Arduino is pretty friendly to 3.3V counterparts.

That does not mean though you cannot control higher voltage circuits, just not directly. Actually if anything above 6V is connected to an Arduino PIN you will blow that pin and potentially others which are logically connected within the MCU, so be aware.

To control higher voltage circuits you have multiple options, in your case you are probably interested into using a BJT transistor, an 2N2222 might do.

simulate this circuit – Schematic created using CircuitLab

Please note the values of R1 and R2 must be adjusted to the LEDs you are using depending on their Vf (forward voltage drop) and the maximum current you want to provide.


Does not name a type error when using makeTime I am getting a "does not name a type" error when trying to use makeTime() from the Time.h library, code snippet as follows:

#include<Time.h>

tmElements_t tmet;
tmet.Year = 2013-1970;
tmet.Month = 8;
tmet.Day = 28;
tmet.Hour = 18;
tmet.Minute = 30;
tmet.Second = 0;

time_t dateMet = makeTime(tmet);

Alternatively I've also tried time_t dateMet = maketime(&tmet); with the same result. I am no expert so go easy on me but am I missing something small here?

Thanks

You're trying to access the 'properties' (i.e. the members) of the tmet variable in a scope where they aren't accessible (outside of a code block). In this global scope of the program the compiler expects a type name on the left side of a statement (i.e. a variable or type declaration), but tmet's members like tmet.Year aren't types in and of themselves.

There are two solutions. You can move the access to the members of tmet into a code block like the setup function:

#include <Time.h>

tmElements_t tmet;
time_t dateMet;

void setup() {
  // put your setup code here, to run once:
    tmet.Year = 2013-1970;
    tmet.Month = 8;
    tmet.Day = 28;
    tmet.Hour = 18;
    tmet.Minute = 30;
    tmet.Second = 0;

    dateMet = makeTime(tmet);
}

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

}

Or you could declare and define tmet in one statement, which has a different syntax (since you have to provide the content of a tmElements_t in a single line:

#include <Time.h>

tmElements_t tmet2 = { 2013-1970, 8, 28, 18, 30, 0 };

time_t dateMet2 = makeTime(tmet2);

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

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

}

Both versions work right away from within the Arduino IDE (i.e. I tested them).


attachInterrupt for mega 2560 not triggering I recently bought a mega 2560 to toy around with as a hobby. It's pretty fun so far, but I've recently gotten stuck while trying to use attachInterrupt with a button. I'm using the CHANGE mode, and have read the documentation pretty thoroughly ( I think ).

I've looked up multiple questions and tried to fix my setup and I still can't seem to make it work.

Here's my code:

int buttonPin = 18;
int ledPin1 = 11;
int ledPin2 = 9;
int ledPin3 = 5;

int value = 0;

void setup() {
  //declare inputs and outputs
  pinMode(buttonPin,INPUT_PULLUP);
  pinMode(ledPin1,OUTPUT);
  pinMode(ledPin2,OUTPUT);
  pinMode(ledPin3,OUTPUT);

  //create interrupt for button
  attachInterrupt(digitalPinToInterrupt(5),count,CHANGE);

  Serial.begin(9600);
}

void loop(){
  if(value == 0){ digitalWrite(ledPin1,HIGH);}
  else{ digitalWrite(ledPin1,LOW); }

  if(value == 1){ digitalWrite(ledPin2,HIGH);}
  else{ digitalWrite(ledPin2,LOW); }

  if(value == 2){ digitalWrite(ledPin3,HIGH);}
  else{ digitalWrite(ledPin3,LOW); }

  delay(500);
  Serial.print(digitalRead(buttonPin));

}

//count occurs when button is pressed
void count(){
  //incremement a counter
  value++;
  //reset counter from 3 to 0
  if(value >= 2){ value = 0; }
}

It's a pretty simple sketch. I'd attach a picture of my current setup but I don't really think It's needed. The button is indeed working as I'm debugging using serial.print().

If not clear, the objective of the sketch is to change the LED lit when the button is pressed. Currently, the variable value is stuck at 0.

//create interrupt for button
attachInterrupt(digitalPinToInterrupt(5),count,CHANGE);

The code does not match the comment.

attachInterrupt(digitalPinToInterrupt(buttonPin),count,CHANGE);