text:
WS2811 strip not working on NodeMCU, works fine on Nano
Sorry if this is something simple, but im scratching my head over this for a while and there are a few things that have me super confused.
I have two WS2811 strips lighting up my outdoor stairs
Both are powered from a central point, using Cat5 Cabling to get power and data from the controller to the start of each strip
Iv been running it from a Nano perfectly fine for a while, but wanted to add networking so upgraded to a NodeMCU
I first started on just one strip to confirm it worked as expected, and after setting about 50 of the 80 leds it started to glitch, so I added a 3.3 to 5v converter and the issues went away.
I then went to work on the second strip, and was getting nothing from it,
no commands sent to the strip were working, the first strip kept working fine however.
I swapped around the pin outputs and converters in case it was a faulty part or bad pin, but no matter the combination, it worked 100% when using the first strip, and never worked on the second.
So i put my Nano back in, running the same color swap test code I had, and both strips worked fine, put the Node back in and only the one strip worked.
I then got a small test strip and connected it directly to the output of the converters and when it was on the one for the first strip, it worked fine (With both the test and first strip displaying the same test)
But when I put it on the output for the second strip, the test strip would turn off as if it was getting a "Set all to 0" command.
I disconnected the cat5 that connected the converter to the second strip, and the test strip started working.
So I thought there must be a short or something on the cat5
So I disconnected the LED strip from the other end and did a continuity test, and none of the leads were shorting (Pos, Neg and Data)
So I put the cable back onto the converter, with nothing on the other end, and the test strip stopped working again,
I dont know if the length of the cat5 is causing a capacitance issue or something, even though its only connected on one end (Converter end)
And it works fine with the nano, only when its the Node and only with the second strip do I have problems
Hopefully my description makes sense, and someone has some idea of whats going on
Link to diagram of my setup https://imgur.com/a/pTefyR5
And happy to try make a short clip if a visual guide would help explain my problem
Thanks in advance

Can the library you use drive two strips at once on the ESP8266?

Yes, works fine when I have it on my testbench,
it only breaks when I add the CAT5 cabling, even without the second strip connected at the other end

cat5 is likely the problem. you don't want a long run between the MCU and the LEDs. are your LED's really 12v WS2811 ? where did you get them?

for reference here is alink to a video showing the problem https://www.youtube.com/watch?v=NnYTCVuATZM

Hi. i have the exact same pronblem. I tested a variety of solutoions, and i can say that cat5 distance is not the problem.. The more leds the strip, more glitches.. Also has a 12v ws2811 strip and changed from arduino mega to ESP8266. didn't find a solution yet.


text:
Arduino LCD Brightness
I've made this small device that uses a ultrasonic sensor to tell how far away an object is and display it on a 16x2 display.
Here's the code:
#include <LiquidCrystal.h>

int Contrast=100;
 LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

const int trigPin = 7;
const int echoPin = 8;
// defining variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
  analogWrite(6, Contrast);

  lcd.begin(16, 2);
  lcd.clear();
}
void loop() {

// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration / 29 / 2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
  lcd.setCursor(0, 0);
  lcd.print("Distance: ");

 lcd.setCursor(0, 1);
  lcd.print(distance);
  delay(100);
  lcd.clear();
}

Every thing works fine apart from the fact that the lcd backlight is too dim(barely visible). I tried looking online but is there any way i can get max brightness without a potentiometer? I do have resistors , can i use them somehow?

Please share your wiring diagram so we can help you. Contract control is usually done using a potentiometer, but can vary depending on the LCD model.

The back light of the LCD is just an LED connected through a resistors on the A (15) and K (16) pins on the display. The LED doesn't require an external resistor since according to the datasheet there is a build in resistor on the board itself. If you aren't using any external resistors and applying a constant voltage of 5V and the screen is still dim than this means that the led is most likely dead and you would need to replace the back light panel.
If you are talking about the contrasts of the display. Than I would recommend you to hook up the contrast pin to a PWM pin on the Arduino and by using analogWite to tune the display in order to get the desired value of contrast.

Most character LCDs have a series resistor but not all. It is a manufacturing option, Typically LCDs available for the hobby market do, but this should be confirmed prior to use.

source: Stack Exchange

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

sort: votes


text:
Arduino Leonardo RX TX mystery
I'm at the tail end of a project using a Leonardo, a HC-06 bluetooth module and a few cell phone vibration motors.  Everything is working fine except the serial communication between the Leonardo and the HC-06.  I've done some tests to rule out common mistakes

TX is connected to RX, and vice versa.
Using a multimeter I checked for continuity with the RX TX, no problem there
I can upload the script
I uploaded the exact same script to an Uno, using the same HC-06.  I was able to connect to the HC-06 with my phone and execute the script.  So I know it's not the script and I know it's not the HC-06.
The Leonardo is working properly because I can upload the script and execute it using the Arduino Serial Monitor.

The only clue I have is that I can upload the script with the RX/TX connected and that's not supposed to work.  However, I checked the connections and there is continuity.  So I'm stumped.  The only thing I can think of is that I damaged the RX/TX while I was soldering, but I'm hoping it's not that.  Is there a way to test for that.  Any suggestions?
/*
 * created by Rui Santos, http://randomnerdtutorials.com
 * Bluetooth App - Turn On and Off LED
*/

#include <SoftwareSerial.h>
SoftwareSerial mySerial(1, 0); // RX, TX

int led = 3;
int state;

void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

void loop() {
  if(Serial.available() > 0){
      state = Serial.read();}

  if (state == '1') {
      digitalWrite(led, HIGH);}   // turn the LED on (HIGH is the voltage level)

  else if (state == '2') {
      digitalWrite(led, LOW);}    // turn the LED off by making the voltage LOW

  delay(100);               // wait for 100ms

  //For debugging purpose
  //Serial.println(state);
}

You should read the Leonardo manual. All will be explained. It's very different from an Uno.

Why are you using software serial on pins 0 and 1?

On the Leo the RX and TX are labeled RX1 and TX0, so I assumed they were pins 0 and 1.  But I also deleted that line of code and tested it and still it didn't work

An Arduino Leonardo has native USB support. Which means that it has separate serial interfaces to the PC and to the hardware pins.
Serial is only used for the communication with the PC and is unrelated to the hardware serial pins 0 and 1. Those are exposed trough Serial1.
So, if you are using the exact same Uno sketch, that uses the hardware serial pins, it can't work on a Leonardo, because data is just sent-to/read-from the PC and not to the connected Bluetooth module connected on pins 0 an 1.

Thanks.  Any suggestions on how to change the script to reflect that difference?

You need to replace Serial with Serial1.

You're a genius gre_gor, it worked!!  Thanks for the help, I needlessly banged my head against the wall for 3 days.  Have a good one!

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


text:
HC-SR04 pulse at multiple angles
I have a HC-SR04 sensor mounted on a stepper motor, mounted on a car.
The idea is this:

The car moves forward with the ultrasonic sensor facing the front
If the sensor reads a small distance the car do the following:

Stop
Turn the sensor to the left and get a new distance
Turn the sensor to the Right and get a new distance
Drive slightly backward
The car turns the to direction the distance was the highest
Drive forward again

I think I must have wrongly understood how the echo/ultrasonic sensor works. Because when I read values to the left and right, it will always return zero, but reading values when driving forward works very well.
Below is the relevant code
//Trigger
void triggerEcho(){
  digitalWrite(echoTrigPin,LOW);
  delayMicroseconds(5);
  digitalWrite(echoTrigPin,HIGH);
  delayMicroseconds(10);
  digitalWrite(echoTrigPin,LOW);
}

//Trigger, receive and calculate distance (cm)
long getEchoDistance(){
  triggerEcho();
  pinMode(echoRecPin, INPUT);
  long echoDuration = pulseIn(echoRecPin, HIGH);

  return echoDuration / 58;
}

void loop(){

  long distance = getEchoDistance();

  //If front obstacle is encountered
  if((distance < 5) && (distance != 0)){
      carStop();
      servo.write(180);                     //turn echo sensor left
      delay(250);
      long distanceL = getEchoDistance();   //trigger and read sensor value
      servo.write(0);                       //turn echo sensor right
      delay(250);
      long distanceR = getEchoDistance();   //trigger and read sensor value

      //this will always show distance as 0
      Serial.print("  LEFT :"); Serial.print(distanceL); Serial.print("\n");
      Serial.print("  RIGHT:"); Serial.print(distanceR); Serial.print("\n");

      carDriveBackward(135, 1.185, 1.0);     //drive backwards
      delay(250);
      if(distanceR>distanceL)                //turn in the direction that was furthest
        carTurnRight(100,1250);
      else
        carTurnLeft(100,1250);
      carStop();
      servo.write(90);                        //face sensor forward
      delay(250);
    }
    else
      carDriveForward(135, 1.185, 1.0); //R - L
}

I bet something is wrong with how I'm implementing the triggerEcho() and getEchoDistance(). I excluded anything on the wiring and pins, as the reading of the distance is very correct when reading the facing the front.

I doubt you have misunderstood the way ultra sound works.  You send a pulse and then go quiet waiting for a reply.  The time it takes to send the pulse is the minimum distance you can detect things at.
If you are not getting returns left and right then it could be there is nothing there or turning the head is breaking a connection.
Firstly jack the vehicle up off the floor so it doesn't go anywhere.
Place a solid object (book) in front of the vehicle and make sure it detects it.
Now place the same object to the right of the vehicle, do it detect it?
Stop the US sensor when it is looking right (by killing the power) and check that it is looking horizontally.  Check the connections, are they being pulled loose?
Your code looks fine, you US works forwards so I think it is a mechanical issue with your car.

So I found out that it had to do with my pins. I was using pin 1 and 2 for trigger and echo. For some reason, I really don't understand why, but using Serial.print() function had an effect on using pin 1 and 2 properly (is that even possible? Do these pins have a relation to that?). Anyway, I switched to other pins, and it works in all direction. Except that I get some messed up results sometimes, but I think my sensor is too near the floor.
I mark your answer as correct, as you were right, its a mechanical issue. Thank you:)

Ok. Googling a little bit tells me that pin 1 and 2 are somewhat special:)

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


text:
Arduino Uno: Receive MIDI data from DAW
I basically want to have my Arduino accept MIDI data from my digital audio workstation, my choice is Ableton Live. I would then like it to check the received data and change the state of a digital pin accordingly. I made a pretty basic schematic to show you.

(Just a very quick diagram, I intend to use RGB LEDs and transistors of some sort in the final product)
I would be happy using a Serial>Midi of some sort if it's the only way, but true USB MIDI would be nice.

What kind of MIDI interface hardware does your PC have? And what exactly is your question?

Which Arduino are you using?

The R3's ATmega16U2 supports USB, so all you need to create a USB MIDI device is software.
On AVRs, you typically use the Lightweight USB Framework for AVRs (LUFA), which has support code for both the basic USB protocol and for USB MIDI.

LUFA has lots of examples.

For USB Midi you could use: Arduino UNO + USB Host Shield + USBH_MIDI Library
The library is specifically for the USB Host Shield. I've used this to take MIDI over USB from a digital piano and used it to control some LEDs. It's pretty strait forward to get it all working.


text:
Arduino/Genuino 101 5 volts pin
Still trying to understand the nomenclature of the pins, I am confused of what's the function of the +5V pin, as I read that the 101 should not operate at that tension.
What's it for?

That is just a regulated 5V and it is 5 tolerant.

What does a regulated input means? And why can I use it without damaging the pins?

Regulated input refers to regulated power input. And The board operating voltage and I/O is 3.3V but all pins are protected against 5V overvoltage So, that doesn't means you will want to power the board with 5V.

In Genuino 5V pin is a DC regulated pin. That means when you supply Power (9 to 12 V) to Vin or through the DC Jack, a 5V voltage regulator regulates to give constant output at 5 V. The purpose of that pin is to provide 5V output for other use- as a power supply to some sensor you are interfacing or anything.
However, you can power up the Genuino 101 via the 5V pin. But that is not advisable because in that case it will bypass the regulator present in the board and can damage the circuit if improperly regulated.

fwiw, i've never seen an unregulated 5v psu output...

yes, otherwise how could you get a constant voltage.

Oh, my misconception was that because of the sign of the voltage (positive) I was assuming it to be an input pin, in the sense voltage would go to, and not from, there. Thanks for the help


text:
Is it possible to connect NRF24L01 to localhost in laptop without wifi router?
I want to send data from arduino to my localhost port:8080(with ipython notebook) via modul NRF24L01 without WiFi router. Is it possible? If it possible, how to do that?
Thank  you...

It is possible to have 2 NRF24L01 radios to talk to each other without a WIFI router.
However, is it possible to get your notebook to talk to a NRF24L01?  Probably not unless you can write a device driver for it.
You could use two Arduinos each with a NRF24L01, and get one to receive the data and then send it via Serial to you laptop, but you would be better looking at an ESP8266, set that up as an access point, connect your laptop to that network and job done.
(By the way you won't be able to call you laptop localhost)


text:
Accessing 2 dimensional array in PROGMEM inside loop
I am unable to access elements of a 2D PROGMEM array from inside a loop. Please see the following example:
const byte a1[] PROGMEM = {'a', 'b', 'c', 'd'};
const byte a2[] PROGMEM = {'e', 'f', 'g', 'h', 'i'};
const byte a3[] PROGMEM = {'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'};
const byte a4[] PROGMEM = {'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

const byte * const arr[] PROGMEM = {a1, a2, a3, a4};

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

  Serial.println(pgm_read_byte(&(arr[0][0])));
  Serial.println(pgm_read_byte(&(arr[1][0])));
  Serial.println(pgm_read_byte(&(arr[2][0])));
  Serial.println(pgm_read_byte(&(arr[3][0])));
  for (int i = 0; i < 4; i++) {
    Serial.print(i);
    Serial.print(":");
    Serial.println(pgm_read_byte(&(arr[i][0])));
  }
  int j = 0;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 1;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 2;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 3;
  Serial.println(pgm_read_byte(&(arr[j][0])));
}

void loop() {

}

The output is:
97
101
106
114
0:12
1:174
2:12
3:148
97
101
106
114

I verified and re-verified the syntax so many times. could not find anyone facing similar issue. I am at my wits end why it would not print correct values inside the loop. Any ideas?
EDIT: expected output is:
97
101
106
114
0:97
1:101
2:106
3:114
97
101
106
114

the constant uses like arr[1][0] are replaced at compile time with the items value. they are not read from the array in runtime. even with j with constant value the compiler evaluates it at compile time and replaces with the value

I think you are right.. is there any way I can achieve accessing the elements from inside the loop?

https://www.arduino.cc/reference/en/language/variables/utilities/progmem/

I had already gone through it.. after you put it here, i took some ideas and made it work.. giving below as answer.. thanks..

@Juraj sorry, i guess i don't have option to upvote you since i am new here..

You can make it easier. For example when each array is a zero terminated string, or when all the arrays have the same fixed size, or one long string with markers. A two-dimensional array with a different number of elements without knowing how many elements are valid, that seems so very weird.

const byte a1[] PROGMEM = {'a', 'b', 'c', 'd'};
const byte a2[] PROGMEM = {'e', 'f', 'g', 'h', 'i'};
const byte a3[] PROGMEM = {'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'};
const byte a4[] PROGMEM = {'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

const byte * const arr[] PROGMEM = {a1, a2, a3, a4};

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

  for (int i = 0; i < 4; i++) {
    Serial.print(i);
    Serial.print(':');
    for (int j = 0; j < 4; j++) {
      Serial.print((char) pgm_read_byte_near(pgm_read_word(arr + i) + j));
      Serial.print(',');
    }
    Serial.println();
  }
}

void loop() {

}

output
0:a,b,c,d,
1:e,f,g,h,
2:j,k,l,m,
3:r,s,t,u,

at runtime the size of the arrays is unknown, so I print the first 4 items

After going through link given by Juraj above again, I could make it work as follows:
const byte a1[] PROGMEM = {'a', 'b', 'c', 'd'};
const byte a2[] PROGMEM = {'e', 'f', 'g', 'h', 'i'};
const byte a3[] PROGMEM = {'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q'};
const byte a4[] PROGMEM = {'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

const byte * const arr[] PROGMEM = {a1, a2, a3, a4};

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

  Serial.println(pgm_read_byte(&(arr[0][0])));
  Serial.println(pgm_read_byte(&(arr[1][0])));
  Serial.println(pgm_read_byte(&(arr[2][0])));
  Serial.println(pgm_read_byte(&(arr[3][0])));
  for (int i = 0; i < 4; i++) {
    Serial.print(i);
    Serial.print(":");
    Serial.println(pgm_read_byte_near(pgm_read_word(&(arr[i])) + 0));
  }
  int j = 0;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 1;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 2;
  Serial.println(pgm_read_byte(&(arr[j][0])));
  j = 3;
  Serial.println(pgm_read_byte(&(arr[j][0])));
}

void loop() {

}

Now it shows the expected output and access from inside loop using variable index is possible. Thanks.

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


text:
MPU6050 Acc and Gyro readings swapped
I have been trying to figure out this MPU6050 for a bit but the RAW readings are confusing me. It seems to me that the accelerometer readings and the gyro readings are getting swapped... and I don't really see how.
Here is the code reading the raw data in:
#include "Wire.h"

const int MPU_ADDR = 0x68; // I2C address of the MPU-6050.
const int ACCEL_XOUT_H = 0x3B; // starting register: high byte to accelerometer X High

int16_t accelerometer_x, accelerometer_y, accelerometer_z; // variables for accelerometer raw data
int16_t gyro_x, gyro_y, gyro_z; // variables for gyro raw data
int16_t temperature; // variables for temperature data

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Wire.beginTransmission(MPU_ADDR); // Begins a transmission to the I2C slave (GY-521 board)
  Wire.write(0x6B); // PWR_MGMT_1 register
  Wire.write(0); // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
}

void loop() {
  Wire.beginTransmission(MPU_ADDR);
  Wire.write(ACCEL_XOUT_H); // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false); // connection is kept active.
  Wire.requestFrom(MPU_ADDR, 7*2, true); // request a total of 7*2=14 registers

  // Read high byte, shift up one byte then OR with low byte
  accelerometer_x = Wire.read()<<8 | Wire.read(); // reading registers: 0x3B (ACCEL_XOUT_H) and 0x3C (ACCEL_XOUT_L)
  accelerometer_y = Wire.read()<<8 | Wire.read(); // reading registers: 0x3D (ACCEL_YOUT_H) and 0x3E (ACCEL_YOUT_L)
  accelerometer_z = Wire.read()<<8 | Wire.read(); // reading registers: 0x3F (ACCEL_ZOUT_H) and 0x40 (ACCEL_ZOUT_L)
  temperature = Wire.read()<<8 | Wire.read(); // reading registers: 0x41 (TEMP_OUT_H) and 0x42 (TEMP_OUT_L)
  gyro_x = Wire.read()<<8 | Wire.read(); // reading registers: 0x43 (GYRO_XOUT_H) and 0x44 (GYRO_XOUT_L)
  gyro_y = Wire.read()<<8 | Wire.read(); // reading registers: 0x45 (GYRO_YOUT_H) and 0x46 (GYRO_YOUT_L)
  gyro_z = Wire.read()<<8 | Wire.read(); // reading registers: 0x47 (GYRO_ZOUT_H) and 0x48 (GYRO_ZOUT_L)

  // print out data
  Serial.print(""); Serial.print(accelerometer_x, DEC);
  Serial.print("|"); Serial.print(accelerometer_y, DEC);
  Serial.print("|"); Serial.print(accelerometer_z, DEC);
  Serial.print("|"); Serial.print(temperature/340.00+36.53, DEC);
  Serial.print("|"); Serial.print(gyro_x, DEC);
  Serial.print("|"); Serial.print(gyro_y, DEC);
  Serial.print("|"); Serial.print(gyro_z, DEC);
  // the following equation was taken from the documentation [MPU-6000/MPU-6050 Register Map and Description, p.30]

  Serial.println();

  // delay
  delay(100);
}

I am expecting some pipe-delimited data in the format:
'aX|aY|aZ|T|gX|gY|gZ'
and indeed looking at the serial data that is what I thought I had:
%matplotlib notebook
import serial
from collections import deque
import pandas as pd
import matplotlib.pyplot as plt
ser= serial.Serial('COM6', 115200, timeout=2.5)
ser.readline()

gives me a good line of data: b'4008|-1792|18376|26.3182334899|-1084|274|-380\r\n'
This certainly looks plausible -- but I was confused by why the accelerometer values were so high at rest... maybe that is just how it is. But when I moved things around I was more and more confused - I have to see this. So I plotted all the values in Jupyter/matplotlib and it made sense -- the first three numbers are not accelerometer data but gyro data:
fig = plt.figure()
ax = fig.add_subplot(111)
plt.ion()

fig.show()
fig.canvas.draw()

ser.reset_input_buffer()
ser.readline()
data = deque(maxlen = 100)
try:
    while True:
        line_of_data = [float(x.strip()) for x in (ser.readline().decode("utf-8")).split("|")]
        data.append(line_of_data)
        ax.clear()
        for n in range(7):
            ax.plot([x[n] for x in data], label='x['+str(n)+']')
        ax.legend(loc='upper left')
        fig.canvas.draw()
except KeyboardInter

I slowly turned the robot chassis and the x[0] and x[2] (should have labeled those better) values changed and then held their values as I held the rotation. This is what I expected to see from the gyroX and gyroZ (the MPU6050 is at the top of the chassis so as I rotate the body about the wheels the X axis changes the most but the Z does as well).
I don't see how the code could be swapping to two sets of data. I have looked at a number of other examples of reading the raw values and their numbers look similar to mine (i.e. they show the first three values as rather large, and the last three as rather small).
When the MPU is not moving I would expect the accelerometer values to be small.
Do I just not understand how the MPU6050 is working or am I somehow swapping the values in my code?

The accelerometer measures the earth gravity and the gyro measures a change in rotation. Can you try to tilt the object in all 6 directions and check if you can see the accel_x,y,z values from a large negative to a large positive value for each axis. To get gyro values, you have to rotate the object fast, and only during a change of the rotation, the gyro values get larger.

So... if I think of the three accelerometer values as a vector with Z pointing towards the center of the earth (which is why it initially the highest value when the chip is laying flat) then as I flip the chip over I will see the Z value flip... this is making much more sense to me. So the values are not swapped I just didn't know what I was looking at! (i.e. all is right in the world again).


text:
Having trouble with motor shield running off external power source
I apologize if I don't immediately give important info, I'm very new to arduino's/circuity of any kind.  I'll try to include as much info as possible.
Some preface:
I'm currently working on a project that generates electricity using TEG's (Thermoelectric generator). The setup I currently have is able to output upwards of 9V. The motor I'm using is able to run when directly connected to the TEG wires, sp they produce enough electricity to work. Due to the nature of the project, a stopping mechanism is being used via a photoresistor and an LED. Essentially when the light signal picked up by the photoresistor is low  enough,  power is cut to the motor.
So up until recently, the motor and the Arduino board/motor shield (Arduino UNO, Arduino Motor Shield Rev3) were being run using a 9V battery. Everything worked correctly, the motor would start when needed and stop when needed. Once I switched to the TEG's the set up stopped working (motor stopped running). What is weird is that if I connect a voltmeter to channel 1 of the motor shield, I read 6V-7V (some voltage drop but not drastic) when the LED was on and 0 when the led was off. So everything seemed to still be working, but the motor itself just won't actually run. In fact, when the LED is on, it makes a very faint noise for a second but doesn't run.
The only thing I can think of is that the current being produced by the TEG's is only enough to power the motor when directly connected, but when wired indirectly through the board thus powering the board, it no longer has enough amperage.
I included the code I wrote for it, which worked fine with a 9V battery powering the motor/board.
const int sensorPin = A5;
const int ledPin = 5;
int lightLevel;

void setup(){
  Serial.begin(9600);
  pinMode(12,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(ledPin, OUTPUT);
}

void loop(){
  lightLevel = analogRead(sensorPin);
  lightLevel = constrain(lightLevel, 0, 800);
  Serial.println(lightLevel);

  if(lightLevel < 200){
    digitalWrite(9,LOW);
    digitalWrite(12,HIGH);
    analogWrite(3,255);
  }
  if(lightLevel > 200){
    digitalWrite(9,HIGH);
    analogWrite(3,0);}
}

maybe the polarity of the TEG is reversed  ...... are you able to run a simple LED blink sketch?

Why don't you ever write pin 12 LOW?  Should it always be HIGH?  What is it connected to?

Try a decoupling capacitor acorss your TEG : 100µF/35v (+ at the +).
This will avoid micro power drops...
Verify that y hardware driving motor works below 9V.


text:
Detect a camera flash? Light sensor, photoresistor?
I'm looking to build an Arduino-based "camera flash logger" to detect when a camera flash goes off, and maintain a log of those events. My thinking is to use a photoresistor to measure light level, and watch for sudden changes using a loop. Something like:
const int ldrPin = A0;

// no idea what this number would end up being
// just putting something here to start with
const int threshold = 10;
int currentLevel, lastLevel = 0;

void setup() {
    Serial.begin(9600);
    pinMode(ldrPin, INPUT);
}

void loop() {
    lastLevel = currentLevel;
    currentLevel = analogRead( ldrPin );

    // look for a sudden change
    if( abs( lastLevel - currentLevel ) > threshold ) {

        // serial out here to simplify the example.
        // I'll be logging outputs (with timestamps) to an SD card.
        Serial.println( currentLevel );
    }
}

A couple of things I'm not sure of though:

will the response time of a photoresistor be fast enough to respond to the very short (sometimes less than 1ms) burst from a camera flash?
is a loop measuring level changes the best way to go about this, or would something like a state change interrupt be better? The ambient light level will vary depending on time of day, so it's an edge detection problem, as opposed to just reading a light level.

Apologies if this comes across as a "you haven't done your homework yet" question. I haven't started the project yet, so all I'm hoping for is a little direction on which way to proceed.

I would propose to use a phototransistor, reacts faster. And if you search for "Flash slave trigger schematics" you will find a lot of circuits (ex. http://www.learningelectronics.net/circuits/slave-flash-trigger.html) that could inspire you.

This ATtiny-based camera trigger uses a photodiode and an op-amp to detect lightings.

Thanks @MatsK. That circuit is more involved than, for example, the one shown in circuit 5 here. Is there a reason for that, or would the simpler circuit work for this purpose?

Thanks @EdgarBonet. Is there a reason to go that way (photodiode + op-amp) over a phototransistor or photoresistor?

Circuit 5 doesn't have a pulse filter, the circuit I refer to have C1 that will improve the detection of a pulse/fast changes of light and the darlington transistors for higher amplification. But you may need to modify the circuit to adopt it to your needs.

AFAIK, a phototransistor is kind of like a photodiode with built-in amplification. Not sure how it compares with with photodiode + an op-amp, you will have to read the datasheets of the individual parts to really know.

Interesting question. Do we really need to poll that quickly? For example every millisecond if the even lasts a millisecond.  Is there any way to use some electronic setup, such that a capacitor for example is loaded when the flash comes, so that a lower poll rate would be enough? (thus integrating over a period of time). Thanks.

A photo-resistor would not be recommended to detect a camera flash accurately.  For example, the Jameco Part #202403 (Part PDF) has a response time of 50 to 75 milliseconds.  Photo-resistors are more suitable for general light levels, for instance, like how bright it is in a room.  On the other hand, photo-transistors are suitable for very fast reaction times.  The Jameco Part #2129385 (Part PDF) has a response time of 15 microseconds, which is more than 1000 times faster.  A photo-resistor will be able to respond to the light change, but it will be nowhere as sensitive.As with any product, however, search for the product PDF before buying it.

I have used a photo-resistor to measure the light level of the surroundings during the solar eclipse of 2017, but that is better for general light levels.  You would use a photo-transistor for laser applications, or optoisolators

Thanks for the response. Would a phototransistor circuit (I've found an example in circuit 5 here work the same as a photoresistor? In other words, would the method I'm using (the script) work the same?

I believe that it should work, because it is adjusting the resistance, and that is the only thing the Arduino analog input cares about.  If it doesn't appear to work, add some delay timing to the loop.  You might want to record a test run with the code similar to below.

Here is a sketch that should work.  https://drive.google.com/open?id=1XTAKTFROCUzBeI-EQkweJ2aMK_MSvMJX


text:
Can I use this power supply with my Arduino?
I am new to Arduino and electronics in general.
I am working on a project where I would ultimately like to power the project from 220V AC (Wall light switch) (I want to replace the light switch with one of my own design).
I will want to feed power to the arduino directly from the 220V connecting wires in the light switch cavity.
This power source is 5V (I know the Arduino needs 9-12V), but I will use a USB connector, wired onto my AC/DC power source, to power the Arduino.
Power Source
Ratings:
AC85 - 264V or  DC110 - 370V wide voltage input
DC 5V(+/ -0.2V) 600mA isolated output
Input Current: 0.0273A/115VAC  0.014A/230VAC
Input surge current: 20A (230VAC)
Frequency range: 50/60 Hz
Operating Temperature: -30 - 70 ℃
Relative humidity: 20%- 90%
Rated power: 3W
Output efficiency: 80%

I don't really know why yet (this is part of figuring that out), but I have the feeling that the arduino would want a linear power source, rather than a switching power source. (Because linear is cleaner power?)
Regardless, I am asking the question as if this power source will do the job, and if not, why not? (Why not a switching PSU) ?

Yes, that power supply is ideal for powering an Arduino (an Arduino doesn't care if it's linear or switching, and a linear regulator that goes from 220V to 5V is called a furnace, and you don't want one of those...)
HOWEVER unless you have a very strange wiring setup in your house, under normal circumstances there is no 220V supply in the switch.  You normally have live in, switched live out and NO neutral connection.
That means you don't have the connections you need to wire your power supply up to.
By the way: if you didn't already know that then you are not qualified to mess around with home wiring and you should leave it to the professionals.

Well well well... I DID indeed forget about that. I am no electrician, and to be honest I have never opened a light socket, but I do know (forgot obviously) that they are not powered by a neutral and positive. I got whisked away so fast on the cool project idea, that I did not consider that. I just wrongly assumed "there must be power there" because it turns the light on.
Thanks for getting me back on track! ;-P

actually new code recommends/requires putting a neutral at each switch location exactly to enable smart switches.

@ratchetfreak ... depending on where you live...  codes aren't universal.

Being in South Africa in a rather "long ago built house", I probably do not have a neutral wire in the cavity. I will inspect.

in the USA, we've been running neutrals in practice since the 90s and in code since 2011.


text:
problem using #define to substitute functions
This might be more a general programming question, but I am using the Arduino compiler, and I've created my own ISR driven version of millis(), which I simply call myMillis(). So let's say I'd like to use this addition to a working project. Rather than do a global search and replace, I got the idea to simply put this define near the top of the program...
#define millis myMillis

uint32_t myMillis()
  { // my code ...
  }

So when I compile, every instance of millis() does indeed compile as if I did a global search and replace. I like that, because it means I don't have to make the change permanent, and can easily comment out my defines to compare program operation.
My question is, if I do as I just explained, what if, for whatever reason, there is some place within the project where I actually WANT to call the original version. A simple example might be if I wanted to occasionally output a message via serial.println(), comparing the returned value of millis() and myMillis(). I think there is a way to specify such an exception to my #define MACRO, but I'm not sure how.

google c++ fully qualified function name or c++ name visibility or c++ name scope .... i think that may be what you are looking for ...... i think that your question relates to namespace

Why did you create your own ISR function? What was wrong with the normal millis function?

@Jot: 2 reasons... 1) I created an ISR that counts time based on the pulsating DC from a transformer powered by AC, which over a course of days will be more accurate than the board clock, and 2) it makes it very easy to quickly detect detect when AC power is lost, so I can save some key date to EEPROM before the board power is completely lost. I'm leaving out some circuit details obviously.

The Arduino millis is very accurate, it uses the accuracy of the 16 MHz crystal or resonator of the Arduino board (when a Arduino Uno is used). The mains AC is in Europe 6 minutes behind at the moment. The resolution of your myMillis will be very course with 50 Hz or 60 Hz, some libraries might no longer work. To detect a power lost, about anything is better than using millis. I suggest to make your own functions and own interrupt, but keep millis as it is.

@jsotola No luck. For a moment I though specifying ::millis() would force a reference to the original, but it doesn't help. To prove it, I added an argument to myMillis with a default values (myMillis(uint8_t reset = 0); So now, if a subsequent call to ::millis(1) should fail to compile if I were referencing the system's millis(), because it would be one argument too many. But it compiles, so that won't do it. I couldn't see any other way.

@Jot ... I don't want to discuss the merits of the crystal vs AC driven time here. But making my own functions and ISR is exactly what I did. That's also the reason I'm putting the #define millis myMillis at the beginning of a working project. Here I'm just asking a specific question about whether its possible to make the define ineffective, just in one or two specific instances.

Randy, that never stopped me from telling what other posibilities there are or telling what is probably the wrong solution to the wrong problem ;) I refer to the XY-problem a lot: http://xyproblem.info/

@Jot: the mains in Europe got 6 minutes late in the course of months, that's way more accurate that the ceramic resonators that clock most Arduinos.

@EdgarBonet, my clone Uno with a crystal is 2 minutes behind in a year. It is only running on millis(). That is still not good, I will add a DS3231. If I would use the mains AC, I would have a interrupt routine with a counter and synchronize the TimeLib with that perhaps once per hour.

I can't post a schematic here in a comment, though I suspect most of you would know how to do it, I'll offer my diagram plus code on a PM of anyone is interested. I can't speak for the rest of the world, but having worked for and with major electric utilities in the US, I can tell you that while a clock driven by line frequency might get a few seconds off by days end, the whole US grid is locked together, and will work to ensure it comes back to satellite traceable NBS time by the next day. Unless there's a blackout, this is the better way to run an app that operates unattended for months.

There is no way to suppress define substitution. You could use #undef and then #define again in required section.
Name the define MILLIS and use this name in code, except where you want the original millis() function.

Thanks, but a global search/replace is just what I'm trying to avoid. And if I did, I wouldn't want to use the same name in caps, because it would make finding them with the search box impossible. Plus,  putting my defines BEFORE includes of some of my own library routines lets me swap out the millis() calls in them too, but only in projects that need the replacement.
Still, if you are correct that there is no reasonable way to suppress a #define sub, at least I know to move on. :-)

I guess I will do the opposite though, I'll create a separate _millis() that calls millis(), and put it before before my new define. Then I can substitute the very few places that need it with the underscore version, and still be able to replace all other uses without editing. Thanks again!

Not related to your problem, but it is worth noting that your define only exists in your sketch (known as a translation unit). Other translation units (the core, libraries, etc) never get to see it.
To make everything see  it youould have to place the define in a location that everything sees, such as Arduino.h in the core, for it to affect anything other than your sketch.
Once you have replaced millis there is no way to unreplace it. You could, though, make use of the scope limiting I talk about above to make a separate translation unit (maybe a small library) with a single function in it that calls millis. As long as that never sees the define it will still see the original function name.

It seems that if I make the define BEFORE including any of my own saved library processes that use millis(), they do indeed re-compile with just my version. Thats good enough for me, and again a very convenient way of substituting a LOT without permanent editing. So perhaps I should just create a separate _millis() call that calls millis(), before my new definition, and just substitute the few places that need it with the underscore version.


text:
slower clock frequency than expected on attiny202
I am programming an attiny202 which as per datasheet can run up to 20Mhz, but after compiling/uploading this simple code to the attiny202 and watch the PA2 pin on the oscilloscope, I see that the pin oscilates at ~2.5MHz which is around 10x slower than I would expect, this is even I disable prescaling, am I missing something? (I am new into programming microcontrollers)

note:
VCC is 5V (from lab bench PSU)

main.c
#include <avr/io.h>

int main(void)
{
  // no prescaling (if lesss than 4.5V, this is overclocking)
  _PROTECTED_WRITE(CLKCTRL_MCLKCTRLB, 0);

  PORTA_DIR = _BV(2);

  while(1)
  {
    PORTA_OUTTGL = _BV(2);
  }
}

Makefile
PRG = main

CC = avr-gcc
MCU_TARGET = attiny202
OPTIMIZE = -Os

OBJCOPY = avr-objcopy
UART = /dev/ttyUSB0

all: $(PRG).elf $(PRG).hex

$(PRG).elf: $(PRG).c                                                                                »       $(CC) -g -Wall $(OPTIMIZE) -mmcu=$(MCU_TARGET) $(PRG).c -o $(PRG).elf

%.hex: %.elf
»       $(OBJCOPY) -j .text -j .data -O ihex $< $@

clean:
»       rm *.elf *.hex

burn: $(PRG).hex
»       pymcuprog -t uart -d $(MCU_TARGET) -u $(UART) write -f $(PRG).hex --erase --verify

bitmaps from oscilloscope:
-
same picture with more measurement information:

So you are toggling a pin in code and expect it to change at the same frequency as the clock? That won't work, since even such a simple action takes more clock pulses than one. I'm not that much into this to tell you how many cycles are needed, but I'm very sure it is significantly more than 1

of course it wont run at same freq as the main clock!, toggling a value into a reg takes more than 1 cycle, I feel dumb, I am sorry, I have not slept much in the last 48 hours out of excitement seeing this working, is my first SOP8!, please, post your answer so I can accept it, going to sleep now before I ask more questions before thinking...

Just as a complement to chrisl's answer, if you disassemble the compiled
program, you should see that your infinite loop looks like this:
1:  sts  0x0407, r24  ; write to PORTA_OUTTGL
    rjmp 1b           ; jump back to previous instruction

These instructions take two cycles each, for a total of four cycles per
loop iteration. The loop is thus expected to run at F_CPU÷4 = 5 MHz.
Since a cycle of the output waveform takes two toggles, you expect to see
2.5 MHz on the oscilloscope.
You should be able to speed this up by writing to the virtual port
register VPORTA_IN instead of PORTA_OUTTGL. Virtual port registers
are equivalent to regular port registers, but they are mapped into the
I/O space of the microcontroller. This allows the compiler to replace
the sts instruction by the shorter and faster out instruction. The
loop should then complete in only 3 CPU cycles and output a waveform at
3.33 MHz.

oh thanks for this explanation!, why is the advantage then of using just non virtual port if vports are "better"? (of course there is a reason, but I am noob), care to explain?, thank you so much for your time

@JoeCabezas: The regular ports have extra functionality: set, clear and toggle register addresses for each underlying register. Also, the address space available for virtual ports is tiny, so most peripherals only have regular ports.

thank you, I will study more about vports then, very helpful!

You are constantly toggling a pin in software. This involves copying the register data to the working register, toggling the bit and writing the result back.
This takes way more than only 1 clock cycle. So the resulting frequency is way lower. With only software you just cannot get near the clock frequency of the microcontroller.

The code writes to an “output toggle” register, which is more efficient than doing the read-modify-write sequence entirely in software.

@EdgarBonet thank you, but still it seems like it takes a lot of cycles enought to reduce from 20MHz to 2.5Mhz, 10 cycles?, I really think I am missing something :/

@JoeCabezas: 20 MHz / 2.5 MHz = 8 cycles, not 10. That is two loop iterations (because the output signal is toggled twice) at 4 CPU cycles per iteration. See my answer for the detailed cycle count.


text:
Trouble with i2c on ESP8266
I have used with partial success I2C with the ESP8266.  When it works, it works well, with many devices on the bus.  I've examined the signals on a 'scope to assure Vlo, Vhi, Tr, and Tf.
However, often it works not at all.  No I2C devices (even if there is only one connected) are detected.  This condition is determined by some unknown factor, and it stays in this condition for some time (days?) before it starts working again.  Power cycle, reset-by-button, and reset-by-reflashing do not restore operation until it works again.
This has occurred with at least three ESP8266 modules from two different manufacturers with different pinouts.  It affects all connected I2C devices.  They are all slaves to the ESP8266.
What should I try next?

next time it fails, load and run a minimal sketch that uses I2C

The signals had looked good, but I did not examine them closely enough.  When I removed extra pullup resistors I had added on SCL and SDA, I2C worked.

It's OK to accept your own answer as the solution to the problem.


text:
How can I power up my Arduino Nano for project of Rocket Data logging?
I am building a Model Rocket for which I need arduino nano to log data.But,I dont know how to power it up once it goes off the ground.Can anyone explain?

How about a lithium battery?  They are very light and have enough voltage (~4 V)

Yup,I heard of them but real problem is I really don't know anything.I am absolute beginner.Can you help me ?Can you help me how to connect battery and arduino either nano or micro or esp8266?I need to consider weight factor also to lift the rocket.So,with minimum weight and maximum efficiency which is better?


text:
Arduino Mega PWM - 100ms Period - SSR and Heater
I'm not very advanced in Arduino "core" functions, so I need your help.
I'm using a Solid State Relay in order to control a heating element, with a PID Library (PID_v1.h) to obtain the OUTPUT of the PWM.
The code itself is not a problem, so that I'll not post it here.
Summarizing, this is the code where I send the PWM to the Relay:
    analogWrite(RELAY_OUT, outputValue);
I've found in this article that:
"The analogWrite function is used to set the duty cycle of a PWM pulse train that operates at approximately 500 Hz. Thus, with a frequency = 500 Hz, the period is = 2 ms."
My concern is that the response time of the relay (FOTEK SSR-60 DA) is 10ms (to turn on or to turn off), but I DO NOT KNOW how to configure Arduino PWM to work accordingly to this Relay, in a period greater than 10ms.
I've found in some pages some people changing the clock frequency in order to have a "fast pwm", but I need to know what values I have to use to get a "slow pwm", for a period greater then 10ms.
Can you help me with that? I've been searching a lot for this answer, but I could not find any "definitive"answer.
Thank you in advance!
Everton

I don't think you can PWM those FOTEK SSRs at 100Hz! They only turn on at the zero crossing and stay on the while half wave. So depending on how in sync your timer is with the 50Hz of the mains, the relay will be ON all the time, or OFF all the time.

You need a different kind of PID. Most PID code have the option to use a on/off output instead of a analog value for PWM. For a heater the minimal time between a chance can be 5 seconds to 1 minute, depending on the fysical system. Have you read this page about the relay: https://playground.arduino.cc/Code/PIDLibrary If you want to use that Solid State Relay, then you have to ignore its response time (it is not how fast it can be turned on and off all the time) and you have to ignore everyone else who is still talking about PWM.

Do you know how fast the physical system is?  Heaters are often controlled very slowly as compared to the ~10ms zero crossing response of a SSR.  House-sized furnaces often have a duty cycle more than a minute, and electric ranges have duty cycles on the order of seconds.  If the heater is on at full power, how fast can the temperature change? Sampling and adjusting should be 5-20 times faster than the process time constant, and you could use the PID_v1 output with your SSR to control a heater at, for example, a 5min by 10ms = 30000 step resolution.

Thanks a lot guys! I've tried to implement the solution using the MEGA registers as you suggested, but I think I'll not use PWM with this SSR anymore. I liked the suggestion from @Jot and will implement a on/off control. As I'm going to heat 60 liters (15 gallons) of liquid in my beer machine, I believe the period from 1 to 5 min will suit to my needs. Thank you very much for all your fast and useful replies!

I'd suggest using the TimerOne library.
Call Timer1.initialize(10000) in setup.
Then call Timer1.pwm(pin, duty); in your loop. Where pin is 11, 12, or 13 for the MEGA, and duty is between 0 and 1023.

As a physical interpretation, this sets a 10 second duty cycle, with 10/1024=9.78ms resolution, which matches the speed specs of the SSR.

Use ATmega PWM registers directly, in order to achieve about 100Hz PWM (10ms period).
This is an example of 10ms PWM period with 50% duty cycle on Arduino Mega (Pin D11):
/* Setup PWM pin D11 as Output */
   pinMode(11, OUTPUT); //D11/PB5/OC1A

   /* Timer/Counter Control Registers: TCCRxx */
   TCCR1A = 0;            //Clear register
   TCCR1B = 0;            //Timer/Counter stopped (CS12=0,CS11=0,CS10=0)

   TCCR1A = (1<<WGM11)  | //Fast PWM mode 16-bit (WGM13=1,WGM12=1,WGM11=1,WGM10=0)
            (1<<COM1A1);  //Set output HIGH during Duty Cycle peiod of OC1A

   TCCR1B = 2                     |   //Prescaler: divide by 8
            (1<<WGM12)            |
            (1<<WGM13);

   /* Set PWM frequency */
   ICR1   = 20000; // Period expressed in tick (10ms)

   /* Clear PWM counter */
   TCNT1  = 0;

   /* Set duty cycle to 50% */
   OCR1A  = 10000;

I didn't test it, but I think that it's correct.
Read this and this for details.


text:
Is there any way to group variables like group.variable as you can in Java/Delphi
I'm writing a sketch which does some calculations on measured variables, and it's based on a similar program written in Java like
c = A.Ux + B.Uz;
Where A&B have various parameters Ux,Uy,Uz etc
In Delphi this notation can be used either for parameters of classes or variables in a group. Looks like there's something similar in Java. It's a tidy way to organise and manipulate variables when there are lots of them and move them between methods without having huge numbers of arguments.
Is there any way to do this in the Arduino Wiring language? I don't seem to find anything online, but I'm probably phrasing the question wrong.
Thanks in advance, Brian

Wiring is the development platform, not the language. We write our sketches in C/C++. Do you mean struct or class members in C++? (https://www.tutorialspoint.com/cplusplus/cpp_classes_objects.htm)

What you are looking for is a struct:
struct foo {
    uint8_t Ux;
    uint8_t Uy;
    uint8_t Yz;
};

Then:
struct foo A;
struct foo B;

And:
A.Ux = 3;
B.Uz = 48;

int c = A.Ux + B.Uz;

When calling a function you should really use either pass-as-pointer or pass-as-reference to avoid unnecessary copying:
// By Reference
int normal(struct foo &arg) {
    return (arg.Ux + arg.Uy + arg.Uz) / 3;
}

int avg = normal(A);

Or:
// By pointer
int normal(struct foo *arg) {
    return (arg->Ux + arg->Uy + arg->Uz) / 3;
}

int avg = normal(&A);

You can read more about structs here.

Note that pass-as-const-reference is often the best alternative to pass-as-value.

@EdgarBonet Unless you want to modify but discard the values. Maybe do some calculations on them and return the result, but want to (for some reason) modify the actual values as part of the calculation process (maybe you're working iteratively on the values and want to accumulate changes, I dunno...).

Of course there are many specific situations! But that's not my point. My point is that, if you want to optimize a code that mindlessly passes a big struct by value, you know that the caller's copy of the struct should not be modified by the callee. Thus your best bet is to attempt to pass by const reference. If it compiles, you are all good. If it doesn't, that's because the callee is modifying its own copy, and you then know that at least some copying is necessary.

@EdgarBonet Indeed. But if it's getting that complex maybe it's time to consider upgrading to using classes... ;)

ah struct! perfect thanks! I was searching for 'record' as that's what it's called in Delphi....


text:
adafruit LSM9DS0 Library - ok with Uno but compile error with LinkitOne?
I'm calling an adafruit Flora LSM9DS0 magnetometer using the Adafruit library with the following sketch:
        #include <Wire.h>
        #include <SPI.h>
        #include <Adafruit_LSM9DS0.h>
        #include <Adafruit_Sensor.h>  // not used in this demo but required!

        unsigned long timeNow = 0;
        unsigned long mSecInHour = 3600000;
        unsigned long TimeNow =0;
        int millisecs =0;
        int seconds = 0;
        byte minutes = 0;
        byte hours = 0;

        int mag_raw_x;
        int mag_raw_y;
        int mag_raw_z;

        // i2c
        Adafruit_LSM9DS0 lsm = Adafruit_LSM9DS0();

        // You can also use software SPI
        //Adafruit_LSM9DS0 lsm = Adafruit_LSM9DS0(13, 12, 11, 10, 9);
        // Or hardware SPI! In this case, only CS pins are passed in
        //Adafruit_LSM9DS0 lsm = Adafruit_LSM9DS0(10, 9);

        void setupSensor()
        {
          // 2.) Set the magnetometer sensitivity
          lsm.setupMag(lsm.LSM9DS0_MAGGAIN_2GAUSS);
        }

        void setup()
        {
        #ifndef ESP8266
          while (!Serial);     // will pause Zero, Leonardo, etc
        #endif
          Serial.begin(9600);

          // Try to initialise and warn if we couldn't detect the chip
          if (!lsm.begin())
          {

            while (1);
          }
          Serial.println(F("Found LSM9DS0 9DOF, measurements in Gauss"));
         }
         void loop()
        {
          lsm.read();
          TimeNow = millis();
          mag_raw_x = lsm.magData.x;
          mag_raw_y = lsm.magData.y;
          mag_raw_z = lsm.magData.z;

Which compiles and runs fine on the Arduino Uno, but I don't understand why the same sketch causes this compile error in the LSM9DS0 library when I compile for the LinkitOne?
    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp: In member function 'bool Adafruit_LSM9DS0::begin()':

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp:77:16: error: 'SPCR' was not declared in this scope

         SPCRback = SPCR;

                    ^

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp: In member function 'void Adafruit_LSM9DS0::write8(boolean, byte, byte)':

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp:365:18: error: 'SPCR' was not declared in this scope

           SPCRback = SPCR;

                      ^

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp:374:7: error: 'SPCR' was not declared in this scope

           SPCR = SPCRback;

           ^

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp: In member function 'byte Adafruit_LSM9DS0::readBuffer(boolean, byte, byte, uint8_t*)':

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp:415:18: error: 'SPCR' was not declared in this scope

           SPCRback = SPCR;

                      ^

    C:\Users\elbg\Arduino\libraries\arduino_373648\Adafruit_LSM9DS0.cpp:426:7: error: 'SPCR' was not declared in this scope

           SPCR = SPCRback;

           ^

Any suggestions welcome !

The SPCR register is low level programming for SPI on a Arduino Uno.

The Adafruit library for the LSM9DS0 is written to run on an 8-bit Arduino. The LinkitOne isn't - it's an ARM board.
Either get a different library that is written to work on ARM, write your own library to work on ARM, or don't use that combination of components.


text:
Is it possible to convert RCA(video only) to Arduino Uno then to a computer?
I have an old wireless RCA output camera. I was wondering if I can convert its analog input to a digital one and have it saved on a file in my laptop?

yes, get a USB video digitizer with an RCA input ... plug into your laptop

Not possible with the Arduino Uno. The composite video signal has an analog bandwidth of ~5MHz, and a 16MHz Arduino with its 12-bit ADC has a max sample freq of circa 77kHz. You cannot sample the signal fast enough and you also can't send it to the computer fast enough due to the incredibly slow serial interface. You'll a need a faster chip (high-speed ADC and DMA..). See https://www.sciencedirect.com/topics/engineering/composite-video-signal, http://zone.ni.com/reference/en-XX/help/373389B-01/nivms/signals_cvbs/ https://forum.arduino.cc/index.php?topic=6549.0

Is it possible? Technically, yes - after all the ZX Spectrum had the Videoface. Only good for still images though (sampled the image in sections across many many frames - 0.26 seconds per image, so about 6 frames needed to get an image depending on region), and 4-bit graphics (fed though a few comparators). Would it be worth doing it? No. Unless you only wanted the experience of doing it. Would the results be usable? No. Absolutely not. Would I do it? No. I'd get a USB video capture dongle.

Thank you! Still got lots of things to learn.


text:
How are "unique IDs" generated for 1wire devices?
If I wanted to make my own 1wire device, I would need to give it a "globally unique" 48-bit identifier.
How are these identifiers generated? How can we guarantee no identifier conflicts with another brand's devices?

If you're going to downvote my question, at least have the balls to tell me why.

probably because the question is not about Arduino

I didn't downvote, but my guess is your question got downvoted because it's not about Arduino.

Oh, I'm sorry, I must've forgotten to write "make my own 1wire device FOR USE WITH AN ARDUINO" to the sodding question!

Where would you suggest I post it?

forgotten to write "make my own 1wire device FOR USE WITH AN ARDUINO" ... that would not make the question about the Arduino ... read what you are actually asking

There isn't a "making 1wire devices" SE. Where else was I supposed to ask!?

Well, NOT electronics.se, apparently! Am I supposed to keep guessing?

I think electronics se is the correct site for your question. Don't worry too much about downvotes.

Since there would be 2^48 unique IDS (281,474,976,710,656) then even a randomly-generated one would probably be safe. And since you say it is for the Arduino, just check there aren't other devices on the one-wire with a clashing ID. Are you going to have your devices and someone else's on the same wire?

Interesting question. After searching for a while I have not found a definite answer, but some good hints.
The 1-wire protocol was created by Dallas, which as later bought by Maxim Integrated. Thus the company Maxim has now control over it. They market the protocol with the explicit feature, that each device, that they manufacture, has a unique ID/serial number. They are the ones controlling it. I'm not sure how it works with other manufacturers, though this uniqueness probably only covers Maxims devices and the ones, where the respective manufacturer has a corresponding agreement with Maxim.
So you cannot be sure, that any ID you generate is unique in the group of all other devices. You can try to use a different family code in the device address (the 48bit is only a part of the actual address, together with 8 bit family code and 8 bit checksum), specifically one, that is currently not in use by Maxim. I've found this technical article with a list of 1-wire device families. It states, that it may not include all device families, but it is the only list, that I found.
As you wrote "we": Creating IDs unique to a whole industry can only be guaranteed by going into an agreement with major industry players (provided they want to do such agreements). Otherwise your guarantees are always limited. You can stay away from the most common devices (with an unused family code) and make sure, that your organization gives out each device ID only ones.


text:
Structure Array Initialization
I'm trying to initialize a char array which is part of a structure as follows:
#define TRUE 1
#define FALSE 0

struct s_field_def { // structure for managing display field
  char f_txt[16]; // option text
  bool f_inhibit; // set this to inhibit updating of the field on the display
};

enum field_name {F_STATE, F_PULSE};

void setup() {

  // initialize display fields structure
  struct s_field_def fields[2]; // initialize the display fields
  fields[F_STATE] =  {"HALTED", FALSE}; // displays the current run state
  fields[F_PULSE] =  {"@", TRUE}; // displays indicator of system running
}

void loop() {

}

The initialization of the structure is producing an error at these lines:
  fields[F_STATE] =  {"HALTED", FALSE}; // displays the current run state
  fields[F_PULSE] =  {"@", TRUE}; // displays indicator of system running

no match for 'operator=' (operand types are 's_field_def' and '<brace-enclosed initializer list>')

What am I doing wrong here?

As explained in Michel Keijzers' answer, you cannot use the = operator
to assign something to a string (a character array). However, you can
initialize a string using =. There is an important distinction
between assignment, which you can do anywhere in a program, an
initialization, which can only be done at the time you define a
variable.
For example:
int i = 2;  // initialization

void setup() {
    i = 4;  // assignment
}

In your specific case, you can initialize fields as follows:
struct s_field_def fields[2] = {
    {"HALTED", FALSE},  // displays the current run state
    {"@", TRUE}         // displays indicator of system running
};

Thanks for the quick feedback about the distinction between assignment and initialization.  That makes it clear.  Problem solved!

I worked too long in an environment where this was not used. Upvoted for learning something.

You can use this (but look at the accepted answer, it shows a much neater way).
  strcpy(fields[F_STATE].f_txt, "HALTED");
  fields[F_STATE].f_inhibit = FALSE;

  strcpy(fields[F_PULSE].f_txt, "@");
  fields[F_PULSE].f_inhibit = TRUE;

I don't have a compiler so I hope it's correct.
When using C++ you can use a constructor or assignment operator, but C does not have these object oriented features.

I was hoping to avoid strcpy for the initialization.


text:
Connecting Arduino with GPS receiver
I have the components as shown and I installed the TinyGPS library.
I'm pretty new to hardware stuff and I'm not sure if these wires would work? (pins on both sides)
The GPS module has 5 pins - GND,5V,IN,OUT and I can barely read the last one. I'm assuming I need to connect only the first 4?
Thanks a lot.

looks like you really need wires with male and female ends.....

@ChadG: So I thought. Is there any workaround, like using a breadboard to interface?

yes... if you put the gps in a breadboard, then the male/male jumpers would be fine.....

I'm assuming I need to connect only the first 4 ... never assume anything .... please post a closeup of the GPS module, back and front, with the writing oriented upright (i'm too lazy to turn my laptop sideways. lol)

@jsotola: I figured this out, thanks nonetheless :)


text:
Arduino Uno 2 I2C devices problem
I have two I2C devices connected to an Arduino Uno: an RTC and an OBD interface (see links below). The SCL/SDA of both devices connect parallel to SCL/SDA (respectively) of the Uno. My problem: when I set the time on the RTC (either using the autoset option, or explicitly) it reports back odd readings, like the date set back by 4 days, the hour set back by 2 hours etc. This happens even with the default bare-bones RTC sample sketch.
I tried two RTCs (one DS1307, and the one linked below): both show the same strange behavior. I tried 2 configurations: 1) NO pull-up resistors on either device, 2) two 10K pull-up resistors on BOTH devices. Both situations produce RTC errors. If I detach the OBD sensor from SCL/SDA, the RTC shows the proper time. If I remove the RTC, the OBD by itself (works fine. Before I spend more time experimenting: any advice how to solve this pull-up resistor situation (if this is what it is)?
Adafruit DS3231 Precision RTC
OBD Freematics interface

I imagine you are using the Adafruit Library, since thats the URL of the product you posted.
If so, in RTClib.h:
#define DS1307_ADDRESS  0x68
#define DS3231_ADDRESS  0x68

And in the OBDs product page:
OBD I2C Address: 0x68

MEMS I2C Address: 0x62

Which obviously causes a conflict.
It seems that they have a fixed I2C address (some devices are configurable via software, others with external pins). So the solution would be to use other RTC, other OBD (or change its address) or use a bus splitter, or use a MCU with more than one I2C bus.

Thanks, well spotted, I'll research this. Why don't they make I2C devices with a small, on-board, solderable jumper to quickly set the address to something else than the default? Rhetorical question...

Well, they do, it is just not all of them that have this feature :)

If anyone has the same problem: turns out Adafruit has a multiplexer just for this purpose. Also, there's LTC4316 which (supposedly) converts I2C addresses on the fly.
Adafruit TCA9548A I2C multiplexer
LTC4316


text:
Uno pin connection: Atmega16u2 & ATmega328P
On my Uno, I set up the HoodLoader2 (link below) so I can program both the ATMega16u2 and the ATmega328P. I can communicate between the two using the serial port. However, I need the serial port to communicate between the Uno and the PC. Can I communicate between the 328 and 16u2 using a common digital pin? All I need to communicate is a simple yes/no state, preferably in both directions. In other words: can I connect a digital pin (say 12) on the Uno to, say, PB1 pin on the 16u2's ICSP header, set pin 12 value to HIGH on the 328P, then read that state on the 16u2 via PB1? And vice versa, via another pair of pins? There's a Q that's close to what I want (link below) and the user there (@jsotola) seems to have the knowledge, but I can't comment under his comment, as I don't have 50 reputation.
HoodLoader2
Accessing digital pins from the ATMega16u2

You could use from PB1 to PB3 from 16u2 (SCK, MOSI, MISO) wich are exposed to its ICSP.
Add a wire from one of them to your atmega328 :)

Thanks. What does "PB" stand for? Is this a "normal", digital pin, with HIGH and LOW states?

It means port B (PB1 physical pin 15 to PB3 pin 17). Don’t Know how hoddler name the pins :) here you’ll fins the uno schematic https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf

This is the original ATmega pin naming and stands for Port B, pin 1. all the pins are separated into banks (ports) of 8 pins each. For pin functions, refer to the relevant datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf

It seems that SCK MOSI and MISO correspond to D1, D2 and D3 (https://github.com/NicoHood/HoodLoader2/wiki/Arduino-Uno-Mega-16u2-Pinout) on the 16u2. And yes they are digital « normal ;) » pins


text:
Error on sending AT+CWJAP_DEF commands to ESP8266
I am trying to send AT commands to ESP8266 to get connected with internet with the Wifi.
When I am sending AT and AT+RST command on serial monitor then I am getting OK and ready response which seems perfect.
Then I am sending AT+CWLAP to get list of available wifi networks which is also executing correctly.
AT+CWLAP

+CWLAP:(3,"Moto",-42,"a4:70:d6:7a:fa:6c",1,25,0)
+CWLAP:(4,"PRANJAL",-95,"1c:a5:32:3d:f5:c4",1,-16,0)
+CWLAP:(2,"VIHAN",-94,"c8:3a:35:2f:1d:81",1,-21,0)
+CWLAP:(3,"Tenda",-93,"c8:3a:35:20:a9:b1",9,-4,0)

OK

Then I sent AT+CWMODE? which is also perfect.
AT+CWMODE?

+CWMODE:1

OK

Now I am trying to connect ESP8266 with above listed Wifi with this command, it is sending an ERROR on serial monitor.

AT+CWJAP_DEF="Moto","reset1234"

Error
⸮=IRe"Moto","reset1234"

ERROR

Can anyone suggest me what could be the reason of this issue ?at

Don't cross post.

Alright! I just tried to connect with different wifi and it got connected with it. It was some kinda issue with mobile hotspot.

The source of such problems are mostly as under

Bad / loose wiring (power and communication)
software serial is not much reliable
Arduino serial monitor is not a user friendly way of testing out ESP modue

To solve wiring related problems for good check out this design.
To solve communication monitoring problems check out this solution
Use USB to TTL interface to connect ESP module directly to your PC without using an Arduino (find details here)

Based on the gibberish echo, the possible causes are:

Insufficient power. You need a source that can supply up to 300mA which is about the max consumption for the module. A good-sized capacitor across the ESP power rails (10uF maybe) wouldn't hurt.
Baud rate is too high. If you're using an Arduino as 'middle-man' and talking to the ESP8266 through a SoftwareSerial port, you're likely to face this sort of issue if the baud rate is as high as 115200; SoftwareSerial is unreliable at such rates.

I connected VCC and CH_PD to 3.3 V, should I connect GPIO0 and GPIO1 also to 3.3 V ? and ESP8266 baud rate is 9600

I connected GPIO0 and GPIO1 to 3.3V and your solution is not working :(

@Williams What solution? I didn't mention GPIO pins. I asked you to provide a better power source to it or reduce the baud rate. Which did you do?

My baud rate is already 9600 and VCC and CH_PD to 3.3 V. How I can provide better power? can you please suggest

@Williams How are you powering it at the moment?

I connected VCC and CH_PD of ESP8266 to 3.3 V of Arduino, GND to GND

@Williams Do you have an LM1117T regulator? Or any other 3.3V regulator?

Let us continue this discussion in chat.


text:
Display Wireless Temperature Sensor data to Web page by using Serial communication
I am reading from wireless temperature sensor with help of gateway receiver connected to Arduino UNO, using this code
I need to display the data of the wireless sensor on the webpage.
Any suggestion on which help to start working using serial com or should I have to use Ethernet port for this?

On what web page?

So you want to read serial port data from a webpage, I am not a web developer, but I suggest you to read the following links.
You can use a local server to read the data (NodeJs, php) :

https://stackoverflow.com/questions/20549151/how-to-read-serial-port-data-from-javascript
https://stackoverflow.com/questions/29619929/read-data-form-serial-port-on-windows-with-php


text:
Control I2C relay board from two Arduino Uno
how can I make multi master Arduino device to work with single I2C device?
As both the master device are 20 m away from Slave device,
I am using the I2C relay board to connect with 2 Arduino boards and need to connect I2C device and create the two way switching technique from this.
Any suggestions here will be a great help.

Why would you want to use a highly priced device with an unsuitable interface with no support when there are hundreds of relay modules which use simple logical levels?

Yes there are TTL relay modules with almost identical form factor and you can buy them for <10% of the price of the OP's board.  What is the reason you need I2C, because of the long distance between master and slave?

Hi MichaelT, Actually I am looking for the solution to use I2C relays for longer distance and setting the priority of master device (Arduinos) to work as per the requirement.

What you want is to operate in multi-master mode.  This is a supported configuration of I2C - however the Arduino API has no support for it.
It involves each master identifying if a collision has occurred and stopping transmission if it has - to then retry transmission later on.
The Arduino hardware can do it, but the software can't. You would have to bypass the software and control the I2C interface yourself (or locate a better library than the Wire library that supports multi-master).

Hey, What if instead of using Arduino, I 'll use ESP8266 or ESP32?
Also If I 'll go with Arduino then any IC package will be useful to achieve this kind of mode?

The answers by Majenko and chrisl are far too optimistic in my opinion.
A distance of 20 meters is not possible. The I2C bus can be 20 cm or 50 cm.
There is no library that supports a multi-master bus for the Arduino Uno.
You have to change your project. Make one Arduino board the Master, and let the Master retrieve data from the other board and the Master writes to the relay board. You need a bus capable of such a distance or use wireless. The RS-485 bus has no problems with 20 meters. Adafruit has a number of RFM69 modules, those should have no problem with 20 meters.

There are chips that translate the I2C bus signals into differential signals that can be used with a twisted pair cable (for example a cheap Cat5 ethernet cable). The SparkFun Differential I2C Breakout makes it easy to put a I2C device at a longer distance.
(Thanks to @PimV for this addition).

Sparkfun has a "Differential I2C Breakout Board" that enables distances of 100 ft (link.

@PimV yes, those are nice modules. They create a rs-485 alike signal over twisted pair wires. When a ethernet cable is used and connected properly then it should have no problem with 20 meters.

Hi, The Differential I2C Breakout board seems better Idea.
But Could it be possible that instead of using Ethernet Port, I can use 2 cables at longer distances also?

An simple Cat5 ethernet cable is cheap and is according to certain specifications for a twisted pair cable. The PCA9615 chip on the Sparkfun chips works best with a ethernet cable. Using just any two cables (of two wires each plus GND) is doubtful. When that cable is not shielded, it might pick up too much electric noise. When that cable is shielded, the capacitance to GND might be too high. A lot can happen in a cable of 20 meters.

The Wire library has no complete multi-master support (as I remember). You can join the bus as slave and becoming master by using the master functions for the time of these transmissions (on execution of endTransmission() the master style I2C transmission is started. When it's finished the library will change to slave again). But you will run into problems, when the two masters send at the same time.
The I2C protocol incorporates a technique named bus arbitration. When two masters write to the bus at the same time, the first one to write a 1 on the bus, must retreat from transmission and become slave again. Unfortunately it seems, that the Wire library doesn't implement this.
So you might not run into problems, until the master are sending simultaneously. Depending on what the Arduinos also have to do, you may be able to recover from such a condition by using the Watchdog Timer to reset both masters, when they are stuck there.
Or you try to find a good I2C/TwoWire library, that works for Arduino and has Bus arbitration implemented.

Sidenote: 20m is quite a long distance for I2C. It is designed for short distances, mostly on the same PCB (hence it is called Inter Integrated Circuit, short IIC or I2C). You may not run into issues, but you should keep this in mind. The bus will have a greater capacitance and you may need strong pullup resistors.


text:
How do I supply either (1) dual voltage or (2) negative voltage?
Sorry in advance if this question already exists--I tried to search but my keyword knowledge is shaky. I have created a Colpitts oscillator on breadboard using AA batteries as the power supplies. I want to implement this oscillator with an Arduino. (Once it's set up, I want to use its voltage to do some things, but that isn't part of this question.)
In the image below, I have two voltages, Vcc (positive voltage) and Vee (negative voltage). My simulations indicate I can run the oscillator either with a dual voltage (+5V and -5V), or with one negative voltage (-5V) and the other set to ground. Either provides a 100 kHz oscillation from about -5 to 2 V. So:

Is there a way to provide a dual voltage supply from the Arduino Uno?
Is there a way to provide a single negative voltage supply from the Arduino Uno?

Thanks!

No, but you could use a dedicated IC, for example http://www.ti.com/lit/ds/symlink/lm27762.pdf

After reading the post carefully, I'm confused why this is marked as off-topic.

You can make -5 V if you use an external power source, like in the circuit below (untested).
Connect the GND (-) from the Arduino to the +5V from the External (5V) source, than 0V will be the GND (with respect to the Arduino), but the GND of the external source will be -5V with respect to the Arduino.
I only used the resistors to get no short circuits, you can replace it by your own circuit (connecting the 5V arrow to Vcc and the -5V arrow to Vee).

simulate this circuit – Schematic created using CircuitLab


text:
New code results in audio noise
I am working on a circuit that can record audio to an SD when a switch is HIGH and stop recording when the switch is LOW. I am using the TMRpcm library. I previously had an issue solved on these two forumsRecording Audio - Film Name Errorand Trying to save .wav files with new name every loop. These solutions solved my problem but have left me with a new one. Currently the audio recorded on the new code (which I have pasted below) results is a very noisy and muffled audio quality; while the audio recorded on the old code (also posted below) is very clear. Could this be a physical issue and if so what should I do about it? Or is it an issue I am missing in the code?
OLD CODE - provides good quality audio
//////////////////////////////////////// SD CARD
#include <SD.h>
#include <SPI.h>
#include <TMRpcm.h>
#define SD_ChipSelectPin 10
TMRpcm audio;
//////////////////////////////////////// SWITCH CASE
int audiofile = 0;     // # of recording
unsigned long i = 0;
bool recmode = 0;      // recording state
//////////////////////////////////////// SWITCH
int inPin = 2;         // input Switch Pin
int state = HIGH;      // the current state switch
int reading;           // the current reading from the switch

void setup() {
  Serial.begin(9600);
  pinMode(A0, INPUT);  // Microphone
  pinMode(inPin, INPUT_PULLUP); // Switch
  //////////////////////////////////////// SD CARD
  SD.begin(SD_ChipSelectPin);
  audio.CSPin = SD_ChipSelectPin;
}

void loop() {

  reading = digitalRead(inPin);
  ////////////////////////////////////////
  while (i < 300000) {
    i++;
  }
  i = 0;
  ////////////////////////////////////////
  if (reading == LOW) {
    if (recmode == 0) {
      recmode = 1;

      Serial.println("Recording");

      audiofile++; // To move case
      switch (audiofile) {
        case 1: audio.startRecording("1.wav", 16000, A0); break;
        case 2: audio.startRecording("2.wav", 16000, A0); break;
        case 3: audio.startRecording("3.wav", 16000, A0); break;
        case 4: audio.startRecording("4.wav", 16000, A0); break;
        case 5: audio.startRecording("5.wav", 16000, A0); break;
        case 6: audio.startRecording("6.wav", 16000, A0); break;
        case 7: audio.startRecording("7.wav", 16000, A0); break;
        case 8: audio.startRecording("8.wav", 16000, A0); break;
        case 9: audio.startRecording("9.wav", 16000, A0); break;
        case 10: audio.startRecording("10.wav", 16000, A0); break;
      }
    }
  }
  ////////////////////////////////////////
  else if (reading == HIGH) {
    recmode = 0;

    Serial.println("Hung-Up");
    switch (audiofile) {
      case 1: audio.stopRecording("1.wav"); break;
      case 2: audio.stopRecording("2.wav"); break;
      case 3: audio.stopRecording("3.wav"); break;
      case 4: audio.stopRecording("4.wav"); break;
      case 5: audio.stopRecording("5.wav"); break;
      case 6: audio.stopRecording("6.wav"); break;
      case 7: audio.stopRecording("7.wav"); break;
      case 8: audio.stopRecording("8.wav"); break;
      case 9: audio.stopRecording("9.wav"); break;
      case 10: audio.stopRecording("10.wav"); break;
    }
  }
}

NEW CODE - poor quality audio
//////////////////////////////////////// SD CARD
#include <SD.h>
#include <SPI.h>
#include <TMRpcm.h>
#define SD_ChipSelectPin 10
TMRpcm audio;
//////////////////////////////////////// SWITCH CASE
unsigned int i = 0;     // # of recording
unsigned long d = 0;
bool recmode = 0;      // recording state
//////////////////////////////////////// SWITCH
int inPin = 2;         // input Switch Pin
int state = HIGH;      // the current state switch
int reading;           // the current reading from the switch

void setup() {
  //Serial.begin(9600);
  pinMode(A0, INPUT);  // Microphone
  pinMode(inPin, INPUT_PULLUP); // Switch
  //////////////////////////////////////// SD CARD
  SD.begin(SD_ChipSelectPin);
  audio.CSPin = SD_ChipSelectPin;
}

void loop() {
  char buffer[50];
  sprintf(buffer, "%i.wav", i++);
  reading = digitalRead(inPin);
  ////////////////////////////////////////
  while (d < 300000) {
    d++;
  }
  d = 0;
  ////////////////////////////////////////
  if (reading == LOW) {
    if (recmode == 0) {
      recmode = 1;

      //Serial.println("Recording");

      audio.startRecording(buffer, 1600, A0);
      //Serial.println(buffer);
    }
  }
  ////////////////////////////////////////
  else if (reading == HIGH) {
    recmode = 0;

    //Serial.println("Hung-Up");

    audio.stopRecording(buffer);
  }
}

Old code:
audio.startRecording("1.wav", 16000, A0);

New code:
audio.startRecording(buffer, 1600, A0);

Spot the typo?

Thank you, I have no idea how I missed that (16000)

Easily done. It just takes a fresh pair of eyes.


text:
SIlly PID question using the PID library
I'm new to PID.
My goal: control the motor to get it to run a given RPM by a potmeter (which is setpoint).
Sensor is optical (detects white line, reflections), counts 100 round in x amount of time. Small calculation gives detected RPM.
I'm using an Arduino and the PID library.
Now my question.
Let's say I've implemented the PID lib on the arduino. It all calculates and so on, but it gives a PID_value which I don't understand.
Ex:
setpoint = 5000
detected = 4999
received PID value = 40
It's my guess that this (or rather: all) PID-lib I'm using always gives a value between 0 and 255 and I have to map/scale that value to my AC trigger.
Could someone point me in the right direction? Thanks!

Which PID library? Can you post your code?

See PID Library - SetOutputLimits() - you can change the limits.
For a meaningful result you need to make the output do something reasonable to the speed. Since your detected speed is lower than the desired speed, you have found it outputs a positive value, which is good, as far as it goes. But you have to interpret that in the context of what you are currently sending to the motor. If you are using PWM to control the motor you could feed the output (40 in this case) to the motor. If that makes it go even slower hopefully the PID library will compensate.
It's hard to make more suggestions without seeing the code.

you, sir, are a genius. Thank you, my brain did stop at #include <PID.h> I will look into the RTFM bit of PID....


text:
Sparkfun CAN Shield BMW OBD2 reading
I bought the CAN-Shield from Sparkfun https://www.sparkfun.com/products/13262 and I also got the Uno from Sparkfun just to be sure everything works fine.
Some info about my car:

BMW E91 2006
OBD2 is available
KWP 2000 and other lines are available
like the ones with the same baud rates from the demo

I tried the SparkFun_CAN_Demo which is available on their website and GitHub.
My output is that
CAN init is successful but I don´t know if that´s true...
If I try to read the RPM, for example, I get a buffer with a size of 1 -> " ".
My questions are:

Did I something wrong with the MCP2515 how do I know if it´s dead?
Does anybody know if the demo is working properly or not?
What´s the right way to get data from an BMW with OBD2?

what is the content of the buffer?

Do you know the bitrate of your BMW's CAN-Bus? If not, have you tried different bitrates?

@oh.dae.su I tried different bitrates but none work I know that my BMW supports KWP 2000 with a bitrate of 10.5kbits and the standard OBD-II ISO with a rate of 500kbits

@jsotola it´s just a space char -> " "

First off I cannot say much about the library that you are using I have't tried that one yet as for the shield i have some of those and there are two versions of them check your PIN outs on them the cs pin is either on d9 or d10
the other thing is make sure that you are in the right operation mode ie. Normal and maybe give this library a try I have had lots of success with this one:
https://github.com/coryjfowler/MCP_CAN_lib
as for the baud rate I have tried all types of ways of getting the right baud rate for certain vehicles but the best remains start small and step it up till you get the one that gives you reply
make sure that you ground the Arduino to the car as well it works without that but sometimes it does nothing If you are using the OBDII cable it should be grounded by default

Thank you for your reply, your suggestions seem to be a good way to find out what I´ve done wrong.

I have battled in the beginning and am still battling with the STM32 CAN bus but i think I have the Arduino one sorted from my side give that library a try it is the best one i could find be sure to use this line:
if(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK)
and this:
CAN0.setMode(MCP_NORMAL);
one to set your device up right


text:
Newbie question: Set servo at certain degrees when something happens
I am trying to set my servo at f.e. 90 degrees when the friendlyValue of the soil sensor is < 50%. The servo isn't moving at all, is it because the code is running too fast and the servo doesn't have time to reposition in between? I tried putting in delays but that didn't work, how do I fix this?
I am new to Arduino and would appreciate any help.
#include <Servo.h>
Servo myservo;

int dryValue = 1024; // max
int wetValue = 0; // min

int friendlyDryValue = 0; // %
int friendlyWetValue = 100;

int sensor = A0;
int sensorValue;

void setup() {

  Serial.begin(115200);

  pinMode(A0, INPUT);
  pinMode(D6, OUTPUT);
}

void loop() {

  int rawValue = analogRead(A0); // soil sensor

 Serial.print("Raw: ");
  Serial.print(rawValue);
  Serial.print (" | ");

   int friendlyValue = map(rawValue, dryValue, wetValue,     friendlyDryValue, friendlyWetValue);

  Serial.print("Friendly: ");
  Serial.print(friendlyValue);
  Serial.println("%");

if (friendlyValue <50)
{
  myservo.write(9);
  }
  else
  {
    myservo.write(90);
    }
  }

You should call https://www.arduino.cc/en/Reference/ServoAttach with the pin you have to connected to. Also what is the debug output on the serial monitor? And how is the server connected to the Arduino?

have you tried to run a servo demo sketch?

From your statement pinMode(D6, OUTPUT);, It looks you're using pin6 for the servo - ? If so, you need instead: myservo.attach(6); to prepare a servo object to use that pin to drive a servo. Not having done this is the reason why your servo wasn't moving. There is an example program to drive a servo using the servo library on the Arduino site.
Your code will run very fast, but since soil moisture can't change rapidly, the value being read from the soil sensor shouldn't either - unless there is electrical noise (and there will always be some; it's a question of how much). Your print statements should show you how consistent the readings are.
There are a couple of things you can do about it:

Delay for a second or so at the bottom of the loop() function so the servo updates will come less frequently and the servo will have time to track them. This really doesn't help with a noisy signal though, and you probably don't want it to track noise. Also, I don't usually suggest using delays but in so uncomplicated a program as this one, it is really the most straightforward approach.
Calculate the servo position from an average of a few sensor readings rather than using just one. This will help with noise so the servo should only have to track real data rather than data+noise.
Do both. Update less frequently and average a few readings taken a few 10s of milliseconds apart. This will both reduce noise and keep the servo updates to within its tracking ability.


text:
Will a 12 VDC 1A Power Supply Adapter supply too much power and damage an Arduino Mega 2560?
The specs shown here:

show that it has 54 digital pins with each outputting a DC current of 20mA which makes it 54 * 20 = 1080 mA
Plus the DC current of the 3.3V Pin of 30mA we get a total of 1110mA.
Is this how one should go about doing the computations?
If the adapter is insufficient will a 12 VDC 2A Power Supply Adapter be appropriate or excessive?
Any links to read up on will be greatly appreciated as well.
Links for this question:
https://store.arduino.cc/mega-2560-r3
https://store.nerokas.co.ke/index.php?route=product/product&product_id=567
PS: All I'm planning to connect to the board is: 'a PIR sensor (the first version not Rev B)', a '5V relay' and possibly a 'ESP8266 ESP-01S Relay Module'

You may be able to draw 20mA from a pin, but you cannot draw 20mA from each pin. The absolute max is 200mA for entire package.

Incorrect re: 200mA max. There are 4 VCC/4 GND pins, rated for 200mA each, so the uC chip can potentially support 800mA.  This is straight from Atmel tech support.  Further, there are limits to how much each port can support as seen in the notes of Table 31.1 of the datasheet, page 356, document # 2549Q–AVR–02/2014. There may be a later revision at www.microchip.com (they bought Atmel a while ago and have been re-releasing data sheets).  20mA as a max is good usage, more current than that and highs may drop to <4.2V, and lows may rise to > 0.9V.

No. You have everything wrong there.
First off, a power supply does not provide power. It provides voltage. The device attached to it then draws current. As much current as it needs at any particular moment in time.  The current rating of a power supply is the maximum that the power supply can give.
The same goes for Arduino IO and power pins: The current ratings are the maximum current you can draw from the pin.
Exactly what current it will draw from the power supply depends completely on what is connected to what pins, and even what calculations the Arduino is doing at the time.  To get a ball-park figure of current requirements you need to know the current requirements of whatever is attached. If a device has its own power input that is the current you need to worry about. If a device is powered directly from an IO pin (such as an LED) then that forms part of the Arduino's current (which starts at about 40mA or so for the board itself).
There are many other factors to take into consideration:

The 5V regulator on the Arduino can't give more than 1A maximum, and considerably less than that when powered from a high voltage like 12V.
The DC jack on the Arduino is limited to 1A due to a polarity protection diode.

It is usually recommended to use a separate 3.3V regulator for an ESP8266 module (or 5V if your module has a built-in 3.3V regulator) due to the lack of power capacity in the Arduino's on-board regulators.
As a rough guestimate:

Arduino: 40-60mA
ESP8266: 200mA (when transmitting)
PIR: Negligible
Relay: 50mA when active

So you'd be looking at 300mA as a minimum. More is better. 1A should be more than sufficient. 2A would be overkill but give a big margin of error.
For everything you have there, it would be better to use a 5V power supply, not a 12V power supply.

Good answer, but one comment: It’s my understanding that the Arduino itself is fairly dumb about power management and runs all it’s subsystems at full power, so what it’s calculating doesn’t have a lot of influence on its power consumption (in contrast, modern high end CPUs have sophisticated power management systems, and throttle down subsystems when you’re not using them.)

It is fairly dumb, yes. Maybe calculations isn't the right word. What internal programs are doing what at any given time has a large bearing. You can also shut down portions of the chip, and enter various sleep modes to reduce power. Different instructions do use different amounts of power though, depending on what they do.

I would bet driving the various interface subsystems would have a fairly large influence on power. Those GPIO lines have fairly “stiff” gates, the UARTS and other subsystems, etc. For that matter the LEDs on the board draw not-insignificant power.

In addition to what Majenko told you, some additional information:
The Arudino uses a linear power supply. That type of power supply works by converting all the excess voltage above the output voltage to heat. So if you feed it 12V, at 1A, it has to convert 1 amp of  12V-5V, or 7 watts of power to heat. The heat sink on the Arduino is not up to dissipating 7 watts of heat.
A linear power supply needs a little more than the output voltage. Feeding it 7.5V would be just about right. You should be able to get a full amp of 5V out of the Arduino’s power supply if you feed it 7.5V at the input, although the output voltage will probably droop some as you approach the max output, and it will get hot. Don’t put it in an airtight container.
As Majenko says, you shouldn’t add up the max current output of every pin on the Arduino to get its power requirements. A digital output line will use almost no current unless it is feeding an output that draws current. Think of the power supply as a spring-fed well, and the output as scoops that scoop water out of the well. As long as you don’t scoop water out of the well faster than it can be replace by the spring, you’re ok. If you only use a couple of small scoops, you’ll hardly take any water out of the well. (If you only have a couple of low power outputs connected, you’ll only draw a small amount of current.)
The Arduino draws a moderate amount of current all by itself. See the specs for details.


text:
listing sd card files on a tft screen
I'm currently working on a Arduino project that plays audio files from SD card through a speaker.
First Arduino sends the list of all music files, and when I send it a file name, the music is played.
The project is working well but there's no GUI. Everything has to be done via serial, and now I want to add a TFT screen that will list the music files on the screen, so that whenever I touch a file name  it should be played.
I haven't bought the TFT yet, and that's because I have a little question for which I need an answer.
If I start listing the files, can I scroll up and down ? Because at some point the TFT screen will become full of text, and I don't want the text to be overwritten.
Any help would be appreciated.

If I start listing the files, can I scroll up and down ? Because at some point the TFT screen will become full of text, and I don't want the text to be overwritten.

If you program that kind of facility, yes.
A TFT screen is like a blank piece of paper, and you have a set of crayons. You draw on the screen (sometimes with pre-defined shapes, called "letters"). If you want to change what is on the screen you can either throw away your piece or paper and start with a new blank page, or you can get some Tip-Ex® and cover up parts that were there already so you can draw over them.
If you want scrolling you will have to work out for yourself how best to do that given the limited resources you have available.
The simplest method is just to retain a list of the filenames in memory and print just a subset of them on the screen. "Scrolling" then just means displaying a different subset of names.