text:
Interrupt crashes code when implemented
I've got a mini weather-station with a Davis Anemometer Vantage Pro that uses a reed switch to detect rotations. Using the rotations it then can convert to MPH. When using it alone, I have no problem measuring the wind speed. It measures the rotations over a 3 second period, and finds the average wind speed over those 3 seconds; however, when implemented into a group of code that also writes Temperature, Humidity, and Accelerometer data to an SD card, it crashes my code. For the sake of keeping this comment shorter, I am using code from http://cactus.io/hookups/weather/anemometer/davis/hookup-arduino-to-davis-anemometer-wind-speed, and am implementing into the code below. It's a big chunk, but the important stuff should be the ISR_rotation and enabling interrupts at the start of the loop.
// going to include all the libraries we need and definitions
#include "SD.h" //sd card
#include"SPI.h" //sd card
#include "SHT1x.h" //temp/humid
#include <Wire.h> //accelerometer
#include <Adafruit_MMA8451.h> //accelerometer
#include <Adafruit_Sensor.h> //accelerometer
#include <math.h> //for wind speed
//define pins and functions
#define dataPin 6 //data pin for temp/humid
#define sckPin 7 //serial clock for temp/humid
#define WindSensorPin (2) //pin for wind sensor
SHT1x th_sensor(dataPin, sckPin); //caling sht1x.h
Adafruit_MMA8451 mma = Adafruit_MMA8451(); //calling the accelerometer library

//WindSpeed stuff
volatile unsigned long Rotations; // cup rotation counter used in interrupt routine
volatile unsigned long ContactBounceTime=0; // Timer to avoid contact bounce in interrupt routine
float WindSpeed; // speed miles per hour

//SD card stuff
const int chipSelect = 10;
String dataString =""; // holds the data to be written to the SD card
File sensorData;

//Temp/Humid stuff
float humid; // humidity value
float temp_c; // temperature value

void setup(){
  // Open serial communications
  Serial.begin(9600);
  Serial.print("Initializing SD card...");
  pinMode(chipSelect, OUTPUT); //sd writing
  pinMode(WindSensorPin, INPUT); //wind data
  attachInterrupt(digitalPinToInterrupt(WindSensorPin), isr_rotation, FALLING);//""wind interrupt""

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
  // don't do anything more:
  return;
  }
  //accelerometer setup
  if (! mma.begin()) {
    Serial.println("Couldnt start");
    while (1);
  }
  Serial.println("MMA8451 found!");
  mma.setRange(MMA8451_RANGE_2_G);
  Serial.print("Range = "); Serial.print(2 << mma.getRange());
  Serial.println("G");
}

//
void loop(){
  //This interrupt portion is for incrementing Rotations
  Rotations = -22; // Set Rotations count to 0 ready for calculations
  //interrupts(); // Enables interrupts
  //delay (3000); // Wait 3 seconds to average
  //noInterrupts(); // Disable interrupts
  //convert to mp/h using the formula V=P(2.25/T) where T is the delay in seconds
  //V = P(2.25/3) = P * 0.75
  //WindSpeed = Rotations * 0.75;

  //read the temperature/humidity sensor
  humid=th_sensor.readHumidity();
  temp_c=th_sensor.retrieveTemperatureC();

  //read the 'raw' data in 14-bit counts for accelerometer
  //mma.x for x direction, mma.y for y direction, mma.z for z direction
  mma.read();
  //Convert 14 bit to SI units (m/s^2)
  sensors_event_t event;
  mma.getEvent(&event);
  delay(3000);
  WindSpeed = Rotations * 0.75;
  //read the wind speed data

  //build the data string
  dataString = String(temp_c) + "," + String(humid) + "," + String(event.acceleration.x) + "," + String(event.acceleration.y) + "," + String(event.acceleration.z);// + "," + String(WindSpeed); //to CSV
  saveData(); // save to SD card
  //for testing with serial monitor to see if we are obtaining correct values
  Serial.print("Temperature: ");
  Serial.print(temp_c);
  Serial.print(", Humidity: ");
  Serial.println(humid);
  Serial.print(" X: ");
  Serial.print(event.acceleration.x);
  Serial.print(" Y: ");
  Serial.print(event.acceleration.y);
  Serial.print(" Z: ");
  Serial.println(event.acceleration.z);
  Serial.print("Rotations: ");
  Serial.println(Rotations);
  delay(3000);
}

//
void saveData(){
if(SD.exists("data.csv")){ // check the card is still there
  // now append new data file
  sensorData = SD.open("data.csv", FILE_WRITE);
  Serial.println("Data written");
    if (sensorData){
    sensorData.println(dataString);
    sensorData.close(); // close the file
    }
  }
else{
  Serial.println("Error writing to file/Card removed");
  }
}

// This is the function that the interrupt calls to increment the rotation count
void isr_rotation () {
if ((millis() - ContactBounceTime) > 15 ) { // debounce the switch contact.
  Rotations++;
  ContactBounceTime = millis();
  }
}

When any wind information and interrupts are commented out, I have no problem at all with writing to SD card and getting the correct data from the accelerometer and sht10. I must be doing something wrong with the interrupt, but I'm not sure. I've read to not include any serial prints, delays, keep em short, etc. and it works alone. It crashes right after running the setup (before it can serial print any information), which makes me believe it's something with the interrupt. I've tried commenting out noInterrupts() and it returns trash data for rotations, so that's not usable. In case it's important, the memory usage is in the 60% range, so that shouldn't be relevant.
Thanks for any help or advice you have.
EDIT: After totally removing the interrupt() and noInterrupts() portion, I get trash data for rotations that changes depending on the debounce timing (higher debounce limit=fewer triggered rotations). I seem to get a constant Rotations range of 20-23 that does pretty accurately depict how many rotations I add (for example spinning 8 times gets me around 30). I also prettied it up the code a little bit.

I think the code besides measuring wind speed also uses interrupts. So if you are turning all of them off with noInterrupts() they cannot work either. Instead try to only disable the interrupt for Wind speed measurement

just an observation - indentation - you don't seem to want to write readable code

Your basic flaw is that you turn interrupts off (prior to commenting those lines out), and then attempt to use the SD card which almost certainly will want to use interrupts.
Your technique of turning interrupts on, and then doing a big delay, is not one I like. I comment on that sort of thing in my page about interrupts, in particular in reply #10. The essence of that reply is:

Timing an interval
I have seen example code suggesting you count things for a second by turning interrupts off for a second and then on again. I don't recommend this, because for one thing, you can't do serial prints if interrupts are off.
Example (not recommended):
volatile unsigned long events;
const unsigned long INTERVAL = 1000;  // 1 second

void eventISR ()
  {
  events++;
  }   // end of eventISR

void setup ()
  {
  Serial.begin(115200);
  attachInterrupt (digitalPinToInterrupt (2), eventISR, FALLING);
  }   // end of setup

void loop ()
  {
  events = 0;       // reset counter
  interrupts ();    // allow interrupts
  delay (INTERVAL); // wait desired time
  noInterrupts();   // stop interrupts

  Serial.print ("I counted ");
  Serial.println (events);
  }  // end of loop

(This is effectively what your code does).
That may work for simple situations, but turning interrupts off means that the Serial prints won't work until they are turned on again (which they may not be in a more complex sketch).
It is better to use the millis() result and just detect when the time limit is up.
Improved sketch:
volatile bool counting;
volatile unsigned long events;

unsigned long startTime;
const unsigned long INTERVAL = 1000;  // 1 second

void eventISR ()
  {
  if (counting)
    events++;
  }  // end of eventISR

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  attachInterrupt (digitalPinToInterrupt (2), eventISR, FALLING);
  }  // end of setup

void showResults ()
  {
  Serial.print ("I counted ");
  Serial.println (events);
  }  // end of showResults

void loop ()
  {
  if (counting)
    {
    // is time up?
    if (millis () - startTime < INTERVAL)
      return;
    counting = false;
    showResults ();
    }  // end of if

  noInterrupts ();
  events = 0;
  startTime = millis ();
  EIFR = bit (INTF0);  // clear flag for interrupt 0
  counting = true;
  interrupts ();
  }  // end of loop

In loop() here we wait for the interval (1 second in this case) to be up, otherwise we return, effectively doing nothing. You could of course do other things instead of just returning.
If the time is up we display the count.
If counting is not currently active (and presuming we want it to be active) we remember the start time, reset the counter to zero, and let it start counting up.
That code seemed to work OK up to 100 kHz, although the counts were getting a bit inaccurate. You can do more precise timings by using the hardware counters / timers. Details at my Timers and counters page.

Why are you clearing the interrupt flag in your loop code? I think, this is not needed here. I would also suggest, only attach the interrupt for the pin, when it is needed for measurement. After the measurement period is over the detachInterrupt() function disables only this particular interrupt without messing with the others interrupt sources.

Why? To avoid a spurious interrupt (event) which might have occurred before the timing recommenced.

the measurement period is over the detachInterrupt() function disables only this particular interrupt - feel free to post an alternative answer that shows how this might work.

Consider using one of the timers as a counter the the interrupts will not cause problems with the SD card.


text:
simultaneously read 16 hall sensor and maximum current allowed by Arduino
My question is about maximum current allowed by Arduino.
I know it's 200mA in Arduino and 40mA in every pin (lower in arduino mini). Just wondering if simultaneously read 16 hall sensor (than can be all activated at the same time) is too much.
My calculation is 200 / 16 = 12.5 mA máximum current I can drive to a pin from a sensor, but it's enough to read the sensor? Specs from 3144 hall sensor says it outputs 25mA when activated. Can I put a resistante between output's sensor and Arduino pin?
I'm planning to use Arduino mini and sensor hall 3144.
Sorry for my english, and thanks in advance!
p.s: The original idea was read all 64 sensors with one Arduino, but breaking it into several arduinos is easiest as my electronics knowledge is seriously limited :)

Which Arduino? Which hall effect sensor?

Arduino mini and 3144 hall sensor. I've edited the post, thanks for the appointment!

I know that i can reduce input current on each pin using resistors, but what is the minimum current to activate an Arduino digital pin?

I've seen people multiplex a grid of hall-effect sensors.

Since this sensor doesn't need to be driven directly from a pin, the maximum current for one pin is not important here. The hall sensor uses two of it's pins as supply voltage. The output pin is an Open-Collector pin. So it will be connected to GND trough a transistor depending on the magnetic field. If you use an external pullup resistor (as connection between OUTPUT and positive supply voltage), you get somewhat like a voltage divider. Since the hall sensor seems to behave as a switch, there will only be two possible states. When the magnetic field is low, the transistor doesn't let the current flow. The pullup resistor can pull the pin to the positive supply voltage (5V -> 1 as digital value). If the magnetic field is high enough, the transistor will open the connection to GND. Now a maximum of 25mA of current can flow throw it to GND. The voltage of the pin is now determined by the voltage divider the transistor and the pullup resistor build. You can calculate the virtual "resistance" of the transistor in this state with Ohm's law

R = U/I

(R is resistance, U is voltage and I is current) With 5V supply voltage and 25mA current you get a resistance of 200 Ohm. Since you just want to use the sensor as a switch, you only have to ensure, that the pin cannot be pulled to a significantly greater value than 0V. So grab a resistor, that is significantly higher than 200 Ohm and use it as pullup resistor. Keep in mind, that you always must use the pullup resistor with the supply voltage, that runs the Arduino. A higher voltage can fry the Arduinos components.
Then you connect this pin to a digital pin of the Arduino, which you configure as INPUT. In this state the pin has a high impedance, so that the current, that flows into it, is really small (it CAN source 25mA, but it does not have to. The current depends on your external circuit). So this isn't something you have to bother about.
This leaves us with the supply current, that the sensor needs to work. In the datasheet it says, that at a supply voltage of 8V the supply current is at maximum 9mA. For 16 sensors this gives us a total of 144mA, which is still comfortable inside the 200mA the Arduino can provide. So you should be able to drive all of them safely.
That said, if you want to add more components, that draw current, it might be better so source the current you need not over the Arduino but directly from your power source (if this is possible for you). Depending on the current you may need, it can also be good, to get an external voltage regulator (if your supply doesn't directly give you 5V), that can provide enough current.

So I only need to use a resistor to control the voltage from sensor to arduino , thank you Chrisl. It's complicated to calculate resistance value? I've read that typical are 10k ohm, but I guess it depends on voltage provided by external battery...

I'm a little confused with the resistor... If I have 9V as external supply, then I have to reduce this to 5V before carry this current to Arduino pin?

I edited my answer to make it clearer, what I meant. If you don't understand, what I wrote, you should read a tutorial or similar about switches and pullup/pulldown resistors. Maybe you can start here: [ https://learn.sparkfun.com/tutorials/pull-up-resistors ]

As Gerben mentioned in a comment, you could set up a matrix of the sensors.
Since the 3144 effectively is a switch to ground (when the magnet comes close it pulls the data line low) you would wire them up like a keypad matrix. I recently did an answer about a keypad matrix. If you wanted 64 sensors you would only need 16 Arduino pins (8 for the rows and 8 for the columns).
The keypad matrix I described already drives the rows low, so that is the right polarity for the sensors. You would just need a pull-up for the columns, say 10k. The sensor then just has to sink 5/10000 amps (0.5 mA) which is well within spec.
The supply voltage to the sensors can be provided independently of the Arduino (however 5V would be reasonable). Since the sensors apparently usually consume 4.4 mA, then 64 would consume 282 mA, which is probably quite reasonable to supply from the Arduino 5V pin.
The diodes mentioned in the keypad matrix answer are probably a sensible precaution if you are likely to have more than one sensor activated at once.

Hi Nick, it's a new approach for me that looks pretty good... I'll read your keypad matrix answer, thanks for your time!

Just one question about sensor matrix, it can manage several sensors activated at the same time?

(Answered by me: Yes, it can. You already specified at the end of the answer, that's the point for diodes)

source: Stack Exchange

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

sort: votes


text:
Electric meter pulse counting using LLC
I am trying to create an electric meter reading setup for Arduino, and I have been searching for it and almost every posts available is using LDR sensor.
http://www.reuk.co.uk/wordpress/solar/flashing-led-on-electricity-meter/
https://jonarcher.info/2014/03/arduino-based-electricity-monitor/
And since it is using LDR, the system should be kept in a dark area, or that the LDR is taped to the flashing LED so that no other light source will interfere the sensor.
But I wanted to have a different setup, and what I am thinking is:

inside the electric meter, tap into the blinking LED
From the LED, connect it to an LLC (https://www.sparkfun.com/products/12009)
From the LLC, connect it to the Arduino
Arduino will sense/detect the pulse of the LED.

Is this a possible setup? Will it not fry the Arduino or the LLC? Will Arduino be able to detect the pulse?
If not, are there any other options? can I use discrete components instead? (I will be the one creating the circuit connection for the LED and Arduino, using resistor, diodes, etc.)

You know you aren't allowed to open you electricity meter, right? If the company finds out, you're screwed.

Yes, I am quite aware of that. But this is for a project only. :)

Relieved to hear that. Then an opto-coupler is the most ideal solution.

for a project only ... is this for a school project? ... if i was teaching your course, i would give you lower marks because of the use of an illegal hack

When you aren't using the same power supply as the product you are interfacing with, it's usually a good idea of have some form of electrical isolation, which is what the LDR+LED was doing -- there was no way for a voltage spike to reach the Arduino, nor was there any way that different "ground" potentials could cause problems. (Imagine if the ground reference for the meter was floating at a high voltage with respect to earth-ground, but your Arduino power supply's negative line was referenced to earth ground.)
A good way to get electrical isolation is with an opto-coupler, also called an opto-isolator, which is essentially an LED and a photo-transistor inside the same package. The LED side is completely electrically isolated from the photo-transistor side, but light can pass from the LED to the phototransistor.
You would connect the opto-coupler so that current passes through the LED side when the pulse happens, and with a pull-up or pull-down resistor on the phototransistor side, which gets pulled down or up (depending on the circuit) when the LED is on.

simulate this circuit – Schematic created using CircuitLab

so this means the LED side of the opto-coupler will be the one tapped into the electric meter's LED?

Correct. Depending on the particular model of opto-coupler, you can put it's LED in series with the meter's LED and hope the voltage drop will not be too much, or you can just replace the meter's LED with the opto-coupler's LED if you are allowed to make that kind of modification.

Oh okay. How about the connection for the Arduino side? Is it okay if the 5V will come from Arduino Uno's 5V and then the "Arudino input" will be connected to Arduino's Pin 10?

5V would come from the Arduino 5V supply, yes. The input would be any digital input pin -- if your code wants to check pin 10, no problem.

If you plan to put the opto, instead of the led, you may have to add an additional resistor in series with the led. Depending on what value they used in the meter. As the opto uses a IR led, which has a lower forward voltage that the visible led you'd replace.

Thanks! Any optocoupler you can recommend?

I won't recommend any particular, except to say that the easiest to set up are the 4-pin. Search the usual vendors, read the datasheets. In the datasheet examine the LED side forward voltage (Input Forward Voltage) and the CTR (Current Transfer Ratio), which tells you the current that will flow through the output side compared to the current flowing through the input side. It all depends on your circuit.

Alright! Last thing, according to the electric meter I'll be testing, it is 1600 imp/kWh. In getting an optocoupler, is there someting related to this which I need to check on the datasheet of the optocoupler I'll be buying?

Unless you’re pulling megawatts of power, you don’t have anything to worry about with that pulse rate and any opto.

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


text:
Pro Mini atmega168 voltage woes
I have a fistful of Pro Mini clones with atmega168 ICs. Oddly they have 16MHz crystals. When I feed it nominal 3.7V (really 4V, but it will spend most time around 3.7) via the RAW pin, I see 2.6V on VCC and RST pins. Of course I’d like a bit more for my MOSFETs - what’s the cause of this? It’s a 1.4V drop, is this common for pro minis?
I can feed 3.3V to VCC with a regulator, but the 16MHz crystal is puzzling. Clocked for 16MHz?

Bypass the regulator, and connect the battery directly to the VCC pin. However, running at 16Mhz requires at least 3.8 Volts, according to the datasheet. Lower voltages may work, but aren't guarantied.

Yes, I did that, and it works as one might expect. The chinese have made many wonderful arduino clones; this is a collector’s item... (I also have a Nano with a 12MHz crystal). In any case my problem has been resolved.

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


text:
RGB LED strip green LEDs cannot be dimmed to less than 50%
I have an RGB LED strip which I want to control with my arduino uno, everything works fine, except for the green LEDs.
They cannot be dimmed to less than 50%, because they will simply turn off.
I have this test code in my setup:
Serial.write("dimming green test started");
for(int x = 255; x > 0; x--) {
    analogWrite(greenPin,x);
    Serial.write(" - g:");
    Serial.print(x);
    delay(6);
  }
  Serial.println();
  Serial.write("dimming green test done");
  Serial.println();

And the green LEDs are fully turned on in the beginning, and at about 127, the just turn off. All the other colors are perfectly dimmable.
I checked the energy usage, and green does only use a little more than the other colors, so that's not the problem.
Are green LEDs not dimmable? Or is this just an optical effect?
(I use a setup very similar to this one with one difference: but only use 5V, because my LED strip only needs 5V)

switch connections at arduino. swap pin 4 and 7 ... does the problem move to red color?

the pins marked with ~ are the PWM pins ... use those

so why does blue and red work :p

I used pins 5-7 (so the image was not exactly correct)

analogWrite only works on pins that support PWM. Those are the pins with the ~ next to it.
On no-PWM pins, analogWrite will set the pin to LOW, for all values lower than 128, and HIGH for all the higher values. Which is what you are experiencing.

interestingly, none of the 3 pins chosen by the OP - 2,4 and 7 - have that ~ symbol in the image in the question!

@JaromandaX the OP said the image was from a similar project, so I’m not assuming he used those exact pins.

with one difference - well, there's three connections to LED's, but only one fails to work ... must be at least two differences between actual wiring and what OP shows in the question :p

I used pins 5-7, so only one of them was not PWM


text:
Wire.h library works on Uno but won't compile for ATtiny85
TL;DR:

Arduinos are current hungry so I want to switch my microcontroller
code works on Uno, I change upload to ATtiny85, code doesn't compile
Wire.h breaks at the TWBR input
Should I keep trying to fix this or should I just use ATmega328P without the Arduino?

So I'm working on a project where I send data from an IMU (MPU6050) to a phone using Bluetooth LE (HC08) with a bit of signal filtering by a microcontroller in between. I've been using Pro Minis but the amperage consumption by these boards is ridiculous, so I'm trying to replace these with some ATtiny85's that I have laying around.
The problem is, the Wire.h library won't compile for the ATtiny85. It's also worth noting that the default MPU6050 code mandates use of an interrupt pin, which ATtiny's don't have, so I've modified the code to work without it (I'm not sure if that's part of the problem).
#include <SoftwareSerial.h>
#include "I2Cdev.h"
#include "MPU6050_6Axis_MotionApps20.h"
#include "Wire.h"

//==============================================================================
// MPU6050 initialization code
MPU6050 mpu;
uint16_t packetSize;
uint16_t fifoCount;
uint8_t fifoBuffer[64];
Quaternion q;
VectorInt16 aa;
VectorInt16 aaReal;
VectorInt16 aaWorld;
VectorFloat gravity;

//==============================================================================
// microcontroller initialization code
int avg_counter = 0;
int pts_to_avg = 15;
int * x_array = (int*)malloc(sizeof(int) * 25);
int * y_array = (int*)malloc(sizeof(int) * 25);
int * z_array = (int*)malloc(sizeof(int) * 25);

//==============================================================================
// HC-08 initialization code
const byte rxPin = 3;
const byte txPin = 4;
SoftwareSerial bleSerial(rxPin, txPin);

//==============================================================================
void setup() {
  // MPU6050 setup code ========================================================
  Wire.begin();
  TWBR = 24;
  mpu.initialize();
  mpu.dmpInitialize();
  mpu.setXAccelOffset(-1343);
  mpu.setYAccelOffset(-1155);
  mpu.setZAccelOffset(1033);
  mpu.setXGyroOffset(19);
  mpu.setYGyroOffset(-27);
  mpu.setZGyroOffset(16);
  mpu.setDMPEnabled(true);
  packetSize = mpu.dmpGetFIFOPacketSize();
  fifoCount = mpu.getFIFOCount();

  // microcontroller setup code ================================================

  // HC-08 setup code ==========================================================
  // make sure your HC-08 is set to the same baud as below!
  bleSerial.begin(19200);
  delay(100);
}

//==============================================================================
void loop() {
  while(fifoCount < packetSize){
    fifoCount = mpu.getFIFOCount();
  }

  if(fifoCount == 1024){
    mpu.resetFIFO();
    bleSerial.println(F("FIFO overflow!"));
  }else{
    if(fifoCount % packetSize != 0){
      mpu.resetFIFO();
    }else{
      while(fifoCount >= packetSize){
        mpu.getFIFOBytes(fifoBuffer, packetSize);
        fifoCount -= packetSize;
      }

      mpu.dmpGetQuaternion(&q,fifoBuffer);
      mpu.dmpGetAccel(&aa, fifoBuffer);
      mpu.dmpGetGravity(&gravity, &q);
      mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
      mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);

      // points are averaged to keep the baud low w/o FIFO overflow
      if(avg_counter <= pts_to_avg){
        // add live data to this array and hold onto it to be averaged
        x_array[avg_counter] = aaWorld.x;
        y_array[avg_counter] = aaWorld.y;
        z_array[avg_counter] = aaWorld.z;
        avg_counter++;
      }else{
        // average data from the array
        int x_average=0;
        int y_average=0;
        int z_average=0;

        // sums the data in #_average
        for(int i = 0; i < avg_counter; i++){
          x_average += x_array[i];
          y_average += y_array[i];
          z_average += z_array[i];
        }

        // divides by avg_counter (which should == pts_to_avg)
        x_average /= avg_counter;
        y_average /= avg_counter;
        z_average /= avg_counter;

        // resets counter so the array data can be overwritten with future data
        avg_counter = 0;

        // prints data to serial port (if BT is connected, sends via BT)
        bleSerial.print(x_average);
        bleSerial.print(",");
        bleSerial.print(y_average);
        bleSerial.print(",");
        bleSerial.println(z_average);
      }
    }
  }
}

When using Arduino as ISP, selecting "Board: ATtiny25/45/85", "Processor: ATtiny85", & "Clock: Internal 1MHz", the following error showed up:
exit status 1
'TWBR' was not declared in this scope

this error did not occur when compiling for the Uno. If you comment out TWBR, then you get an enormous error message (I'll only paste a bit):
In file included from c:\users\auphynne\appdata\local\arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2\avr\include\avr\io.h:99:0,

                 from C:\Users\auPhynne\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\libraries\Wire\src\utility\twi.c:25:

C:\Users\auPhynne\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\libraries\Wire\src\utility\twi.c:426:15: error: 'TWINT' undeclared (first use in this function)

    TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;

               ^

C:\Users\auPhynne\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\libraries\Wire\src\utility\twi.c:426:28: error: 'TWSTA' undeclared (first use in this function)

    TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;

                            ^

C:\Users\auPhynne\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\libraries\Wire\src\utility\twi.c:426:40: error: 'TWEN' undeclared (first use in this function)

    TWCR = _BV(TWINT) | _BV(TWSTA)| _BV(TWEN) ;

                                        ^

exit status 1
Error compiling for board ATtiny25/45/85.

To try to remedy this, I went into
C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries\Wire\src\utility\twi.c

and hardcoded this line from
// initialize twi prescaler and bit rate
cbi(TWSR, TWPS0);
cbi(TWSR, TWPS1);
TWBR = ((F_CPU / TWI_FREQ) - 16) / 2;

to
// initialize twi prescaler and bit rate
cbi(TWSR, TWPS0);
cbi(TWSR, TWPS1);
TWBR = 24;

and I still got the same gruesome error message.
Pins are what you'd expect, 5v power to both modules and grounded, plus:

Uno D4 -> HC08 RXD
Uno D3 -> HC08 TXD
Uno SCL -> MPU6050 SCL
Uno SDA -> MPU6050 SDA

(again note that the interrupt pin is not used, and this worked quite well when building on the Uno! I got data on my phone's BT serial terminal app so that doesn't seem to be the problem)
Any ideas on how I can get Wire.h to compile on my ATtiny85?
Or... should I just abort and go with the ATmega328P (without the accompanying Uno) since it comes in the Quad Flat SMD package? (footprint matters for the long term)

If you really want to minimize power consumption, you should probably connect the sensor directly to custom firmware on a BTLE MCU, without an intervening part.  You can run Arduino code on an nRF51822, though that may not be the lowest power software approach for it.  Also a MEMS sensor + BTLE is a common demo for the companies which make the latter, so you may be able to find the hardware already made with working example software.

I'd suggest going with an Arduino Pro Mini, (and an external usb-to-serial converter). Those use the same ATMega328P, but without the power wasting extra's of the uno. They are also a lot smaller. You could do some modifications to the board to get a bit more battery life, like removing the power led.

I am getting the same error even though I am using <TinyWireM.h> as the other libraries are <Adafruit_BNO055.h> and <SparkFun_Qwiic_OpenLog_Arduino_Library.h> use Wire.h library and ATTiny85 throws an error during the compilation. Can anyone help please. Code (Just including the libraries causes the error) #include <SparkFun_Qwiic_OpenLog_Arduino_Library.h> // Data logger #include <Adafruit_BNO055.h> //IMU #include <Adafruit_Sensor.h> #include <TinyWireM.h> #include <utility/imumaths.h> void setup() { // put your setup code here, to run once: } void loop() { // put your main code here, to run

You get this error, because the ATTiny85 doesn't have full I2C hardware. It only as an USI (Universal Serial Interface). This can be utilized to do the rest of the I2C protocol via software. There are some libraries out there to do that, most of them are somewhat named TinyWire. There were dedicated libraries for master and slave operation named TinyWireM and TinyWireS. And I composed one library with both functionalities (and some more) in TinyWire. The last one - I think - is not usable for you, because theSoftwareSerial library needs the PinChangeInterrupt to work, but TinyWire uses it for detecting stop conditions on the I2C bus.
So for your case you can use the TinyWireM library. Note that the master operations need exact timing. Using to much interrupts in this time can cause problems in transmission. Test it and disable interrupts, if it is needed.

I'm using the MPU6050 in my project and the library MPU6050.h, which is includes library I2Cdev.h, which includes library Wire.h and uses it a lot - I have a sinking feeling that it will not suffice to replace all instances of Wire.foo() with TinyWireM.foo() in the I2Cdev.h library.. ? The library TinyWireM.h absolutely looks like the right solution, thank you so much, but if implementing it is going to be too complex I'm not sure I'd have the coding skill to pull it off (in which case I'll just stick with ATmegas :l )

In principle the TinyWireM library has many of the same functions as the Wire library (except for the slave functions). But there might be other issues, with simply changing this. You can try to change it, the easier way would be to use an Arduino Pro mini (as mentioned by Gerben). And if this answered your question, please mark it as correct :D

If you want Wire.h library to work on attiny85 use:
https://github.com/SpenceKonde/ATTinyCore
I did and it compiles.


text:
Adafruit Huzzah Feather not resetting and serial monitor garbage

Hi there,
I have an Adafruit Huzzah Feather project laid out as you can see in the diagram above.
Currently I am having trouble getting it to reliably reset and start the sketch. More often than not I receive garbage in the serial monitor and the sketch doesn't begin.
The baud rate is set to 115200 and when the sketch occasionally I begin to see the expected behaviour and serial messages.
I have done some tests to see if the serial connection is causing a problem. I uploaded a sketch with and without Serial.begin(115200);. Without this the sketch behaves as expected (I'm flashing an LED sequence to know when the loop has begun). When I add serial communication back I get about 50/50 success rate when resetting.
Here are some thoughts about what could be the problem:

A problem with circuitry. Not sure if something is causing the board to occasionally activate the bootloader? After reading some of the FAQs I'm wondering if I'm accidentally pulling a GPIO pin low. However time has been spent making sure the problematic GPIO pins (0, 2 15) aren't being used.
Possible problem with the board itself - but this is unlikely because there are two of them with exactly the same problem.
Problem with the code. (https://pastebin.com/VAEreu6b)

Any thoughts and suggestions are very welcome at this stage.
Best,
Gareth
EDIT: Forgot to add code. Now here: https://pastebin.com/VAEreu6b

... and the code is?

Ah yes! That would be helpful: https://pastebin.com/VAEreu6b

GPIO1 and 3 are used by serial, is there a conflict there?

GPIO1 isn't being used and 3 is connected to an accelerometer using i2c. Would that cause a problem?

@gfte yes it is the problem. pin 4 and 5 are default for I2C in esp8266 arduino core. the accelerometer library uses pin 3?

Serial is connected to USB, so pin 1 and 3 should not be used if USB communication is used


text:
DS18B20 sending variable via Enthernet shield
I am trying to send temperature read from DS18B20 to a web server. I know two things: to read a temperature, and to send something to web server. What I don't know is how to convert float that temperature reading function is giving to me to string that I need to send to the server.
I am reading temperature with OneWire and DallasTemperature libraries (just a standard sketch ending with:
sensors.requestTemperatures();
Serial.println(sensors.getTempCByIndex(0));//sensors.getTempCBy... returns float, from my understanding

I am sending data via ethernet shield, and important part is:
 client.println("GET /led-ekran-vremenska-prognoza/?temp1=" + String(sensors.getTempCByIndex(0)) + "&temp2=" + String(dht.readTemperature()) + "&humidity="+String(dht.readHumidity())+"&secret=111 HTTP/1.1");

I know that the problem is that String(sensors.getTempCByIndex(0)) is not converting to right value. Arduino just stops working there, if that makes sense. At least serial communication stops working, since I don't see any more output...
Basically, TL:DR, I think that the question is how to convert float to string in Arduino? I have read a million topics on this but still cant figure it out, especially sicne it works for temp2 and humidity in example above.

I think that the question is how to convert float to string in Arduino? ... why the misleading title? ... why all the stuff about 1-wire and temperature?  .... ask what you mean to ask, do not give a long unrelated story

Uhm, maybe because "I think" part? I am not so good with Arduino programming, and I don't see how including as much RELEVANT information as possible is a bad thing?

Having re-read the question just before posting this answer, I find it odd that the DHT temp and humidity (also floats) work for you - how odd

Use dtostrf
char tStr[9] = { 0 }; // buffer to store the string - length 9, because at most you need 8 chars "-23.5678" , plus null terminator
dtostrf(sensors.getTempCByIndex(0), 7, 3, tStr)

Note: dtostrf returns char pointer to tStr
The 7, 3 is ... 7 = total length of string, 3 = number of decimal digits - So depending on your resolution, you can change those values
Resolution     Arguments to dtostrf
 9             5, 1                  -nn.n
10             6, 2                  -nn.nn
11             7, 3                  -nn.nnn
12             8, 4                  -nn.nnnn

Of course, you can use any arguments for any resolution, the table just shows what you would need if you wanted to show the exact data coming in
For example, I use resolution 12, but I'm not really interested in displaying more than tenths of a degree - so I use 5,1 for the format

This is an awesome explanation of dtostrf. I experimented a little with samples that I found online, but could not figure it out.
Anyway, I tried the code that you posted, and I get the error when I try to combine results with the rest of the string:
client.println("GET /led-ekran-vremenska-prognoza/?temp1=" + tStr + "&temp2=" + String(dht.readTemperature()) + "&humidity="+String(dht.readHumidity())+"&secret= HTTP/1.1");
Error:
invalid operands of types 'const char [42]' and 'char [9]' to binary 'operator+'

the issue is the + operator on char * .. try + String(tStr) + ...


text:
Keypad password check issue
I am working on a school project, basically I have to create a lock system that opens a fictive gate when the correct code is entered. We have been asked to simulate our system before actually building it. So, I made the following circuit in Proteus(Labcenter Electronics' simulation software):

Here's what my system should do: A variable contains the correct code and the user must type a code on the keypad, and if it is correct, a green LED turns on and the LCD screen displays "Acces Granted!" if the code is wrong, the screen will display "Access refused!". It's a basic system, but I'm trying to make it as simple/short as possible(I have to explain it in an oral presentation, so the simpler the better) and for some reason, I can't get my code to work. Ideally, I'd like to have the LCD display a * for each character typed, liked on a real security system, but I haven't managed to do that either. I've been working on it for hours, trying different variants and etc.. but nothing seems to work the way I want to. BTW, my circuit works perfectly fine and the initialisation part of my code is therefore correct as well. Can anyone help me figure out what's wrong with my code and how I can make it better?
Here's my code so far:
#include <LiquidCrystal.h>
#include <Keypad.h>

//define LED pins
#define redLED 11
#define greenLED 10

String codeSerrure = "87362";   //correct code that opens the imaginative gate
String enteredCode = "";
int keyPressed;

const byte rows = 4;
const byte cols = 3;

char touches_digicode [rows] [cols] = {

  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins [rows] = {25, 26, 27, 28};
byte colPins [cols] = {24, 23, 22};

Keypad leDigicode = Keypad( makeKeymap(touches_digicode), rowPins, colPins, rows, cols);
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

void setup(){
  lcd.begin(16, 2);
  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  digitalWrite(redLED, HIGH);
}

void loop(){
  lcd.setCursor(0,0);
  lcd.print(" Entrez le code");

  keyPressed = leDigicode.getKey();
  enteredCode += String(keyPressed);
  if(enteredCode.length() >= 5){
    if(enteredCode == codeSerrure){
      digitalWrite(greenLED, HIGH);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("  Acces autorise!");
      delay(4000);
      digitalWrite(greenLED, LOW);
      digitalWrite(redLED, HIGH);
      enteredCode = "";
    }
    else{
      digitalWrite(redLED, HIGH);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("  Acces refuse!");
      delay(4000);
      enteredCode = "";
    }
  }
  if(keyPressed == "#"){
    lcd.clear();
    enteredCode = "";
  }
}

The problem is that when I run this code in the simulation software, the LCD displays "Acces refuse!" and the red LED is on. No matter what keys I press (on the keypad) nothing happens. So the problem is that my code jumps straight to the else statement, inferring that the password typed is wrong (although no password was actually typed). I think the error is in here:
keyPressed = leDigicode.getKey();
  enteredCode += String(keyPressed);
  if(enteredCode.length() >= 5){
    if(enteredCode == codeSerrure){

Btw, forgive the french words, I am french. Also, I forgot to say, the # key should, clear the entered code. Any explanations, code samples or links would help.

Don't cross post. You already asked this on SO.

print enteredCode to serial right after this line ... enteredCode += String(keyPressed);

Your code does not compile in the Arduino IDE (1.0.6.2). There is an issue with this line: if(keyPressed == "#"). If I replace the double quotes with single ones, it compiles. Are you sure the variable keyPressed should be an int? Perhaps it's suppose to be a char?

@jsotola I will try that and report back, thank you!

@VE7JRO When I clicked the verify button in the Arduino IDE and it compiled fine for me. And I'm not sure which data type to use although char is probably better, because I have tried different ideas with both int and char and neither have worked.

i know this is a hobby project, but in real-world security: you would want to do a constant-time compare on the entered code, not a quick string compare, you want to rate-limit the rate at which guesses are accepted: i can brute-force the C++ shown in seconds; how? I reset the unit instead of waiting 4000ms if the green LED doesn't go off after the keys are entered; delay() on setup().

@dandavis Thanks for the advice man, but as I said in the title this is a school project, and if I can't even get the basic version to work, how the heck am I going implement your idea. However, if I manage to get it all working how I want, I might try this if it's not too complicated. Thank you for explaining anyway man!

The getKey() Funktion returns the define NO_KEY if no key was pressed, which is set in Keys.h as the NULL char (char with the value 0). In every loop cycle you are adding one character with value 0 to your string. But all functions, that handle strings, will stop, when they find a character with value 0 (it is the delimiter of C strings). Also a string with many NULL chars in it will not be matched to a string only consisting oft digits.
So you should check the return value of getKey for the NO_KEY define:
if(keyPressed != NO_KEY){
  enteredCode += String(keyPressed);
}

This avoids adding NULL chars to your string.

Yes, getKey() is not blocking which seems to be what the OP is assuming.

I hadn't thought of this. I will integrate it in my code and check for errors, thank you!

After reading all of your comments, I made some changes to my code and I was able to figure out a few other things that weren't working before. I think, because of the way I had coded my password checking function it made all the rest more complicated. I have also implemented the erase key feature, so a press of the * or # keys, erase the entered code. I still need to implement the feature that displays a * on the lcd each time the user presses a key, but I a not sure of what way to do this. Anyways, here's my working code if you're interested:
#include <LiquidCrystal.h>
#include <Keypad.h>

//define LED pins
#define redLED 11
#define greenLED 10

String codeSerrure = "87362";
String enteredCode = "";
char keyPressed;

const byte rows = 4;
const byte cols = 3;

char touches_digicode [rows] [cols] = {

  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins [rows] = {25, 26, 27, 28};
byte colPins [cols] = {24, 23, 22};

Keypad leDigicode = Keypad( makeKeymap(touches_digicode), rowPins, colPins, rows, cols);
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

void setup(){
  lcd.begin(16, 2);
  pinMode(redLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  digitalWrite(redLED, HIGH);
}

void loop(){
  lcd.setCursor(0,0);
  lcd.print(" Entrez le code");

  keyPressed = leDigicode.getKey();
  if(keyPressed != NO_KEY){
    if(keyPressed == 0x23 || keyPressed == 0x2A){
      lcd.clear();
      enteredCode = "";
    }
    else{
      enteredCode += String(keyPressed);
    }
  }

  if(enteredCode == codeSerrure){
      digitalWrite(greenLED, HIGH);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("  Acces autorise!");
      delay(4000);
      digitalWrite(greenLED, LOW);
      digitalWrite(redLED, HIGH);
      enteredCode = "";
      lcd.clear();
  }
  else if(enteredCode.length() >= 5){
      digitalWrite(redLED, HIGH);
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("  Acces refuse!");
      delay(4000);
      enteredCode = "";
      lcd.clear();
  }
}

Thank you to everyone for the help (I'm a noobie)! I'm aware that my code is problably not the best way to do what I'm trying to do, so any suggestions and upgrades to the code you could give me are very welcome. Thanks again!
The final version of my code with all the features working can be found in this thread, for those interested.

For the * for every digit, you can use an integer variable, that gives you the position in the entered code (so if enteredCode is empty, pos = 0; if you enter a digit, you do pos++;) And directly after you added the new digit to your enteredCode string, you can use lcd.setCursor(1,pos);lcd.print("*"); to print your * to the LCD. Of course you have to set the position right for your LCD (I haven't looked for how many rows and columns you have in your display)

And since your main question (why your code wasn't working) is now answered, you should mark one question as correct, either mine or yours, depending on what you think is better.


text:
Does the position in which you mount an IMU matter?
Forgive me, I'm sure this is a total noob question, but I have never seen it actually addressed in any example or demo.
When using something like a MinIMU-9 board (https://www.pololu.com/product/2738/), does it matter what position you mount the board on your project?  I mean, does it have to be positioned so the proper axes line up with the axes of your vehicle, or is there some calibration to set that alignment?
For a ground vehicle where I will concerned primarily with only one axis, are all axes interchangeable?

Single rotor helicopters inherently hover tilted at a slight angle. There's a popular micro RC helicopter with 6-axis flybarless electronics where the PCB faces forward, and the MEMS sensor is aligned on the board at the approximate opposite of that angle of rotation, so that the chip is actually standing vertically on edge in flight.  Presumably this helps prevent yaw from cross coupling to the pitch and roll gyro readings in a way that would require extra math to untangle.

If the axes of measurement don't line up with the axes of motion, then comparing the IMU outputs to vehicle-relative (VR) coordinates will require some vector arithmetic to convert one to the other. It can be done, but requires some engineering time to code it and processor time to run.
It wasn't clear to me at a quick read whether your chosen IMU can do the coordinate translation itself, or your MCU has to do it. In either case, the computation will always reduce the accuracy of the original data, maybe a lot, maybe inconsequential, but expect some degradation.
Bottom line is: if you can line them up, things get simpler.


text:
sending 16 bit command via SPI to a NCV7719 (half bridge)
I am trying to send a 16 bit command to a Half bridge (data sheet here http://www.onsemi.com/pub/Collateral/NCV7719-D.PDF) to open one of the transistors to turn on an LED. at the bottom of the data sheet (page 13) it says which bit needs to be a 1 or a 0 in order to activate the half bridge. This is the code I wrote but it isn't work (I'm assuming I'm not sending the 16 bits properly). Can someone figure out why this isn't working?
#include <SPI.h>

void setup() {
  // put your setup code here, to run once:
  pinMode(10,OUTPUT);
  pinMode(8,OUTPUT);
  digitalWrite(8,HIGH);
  SPI.begin();

}

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

  //pulling pin low to decide to write to device
  digitalWrite(10,LOW);

  //function to send information
  //truning on half bridge 4
  SPI.transfer(0000010000000000);
delay(500);
  //finish transfering data
  digitalWrite(10,HIGH);

}

FYI, 0000010000000000 is not a binary constant in C++ syntax.

SPI writes in 8-bit bytes. So the writes need to look like this:
  SPI.transfer(0b00000100);  // first byte
  SPI.transfer(0b00000000);  // second byte

Possibly in the other order depending on which byte the device expects first.


text:
Trigger external interrupt on Arduino Uno R3 with an LED and a button
I want to cause the external interrupt on digital pin 2 (PD2 on ATmega328). I have chosen any logic change mode. Here is my code:
void setup()
{
    DDRD &= ~( 1 << DDD2 );//PD2 on input mode
    EICRA |= ( 1 << ISC00 );//any logic change
    PORTD |= ( 1 << PORTD2 );//pull-up enable
    EIMSK |= ( 1 << INT0 );//turns on INT0

    DDRD |= ( 1 << DDD5 );//PD5 on output mode
    PORTD |= ( 1 << PORTD5 );//turn on PD5

    SREG |= ( 1 << 7 );//global interrupts enabled
}

void loop()
{

}

ISR( INT0_vect )
{
    if( ( PIND & ( 1 << PIND5 ) ) > 0 )//if turned on
    {
         PORTD &= ~( 1 << PORTD5 );//turn off led
    }
    //and vice-versa
    else
    {
         PORTD |= ( 1 << PORTD5 );
    }
}

Here is how I connect things.
NOTE: I did not find an ordinary button which just connects two contacts ( which I actually use ). Here if I understand correctly the button in the picture connects left pair and right pair of contacts so everything is connected when pushed and disconnects them from each other when released.

The problem is when I push the button no interrupt occurs. What am I doing wrong?

If the button isn't pressed, the pin is floating, reacting to all electrical things near it. You habe to usw the resistor as pullup or pulldown. That might be the problem. Google pullup resistor and find a tutorial about it

As I know ATmega328 already has pull-up resistors. That is why I turn it on by specifying appropriate bit in PORTD register.

But your fritzing shows, that the button is connected to 3.3V, not to ground. And when you are using the internal pullup, you don't need another resistor

And your code doesn't compile, because in the ISR you try writing to register PIND5, which is only a pin, not a register. You have to write to PIND. Also in your last statement you have an extra parenthesis.

The setup function is only run once. You get no speed gain by writing directly to registers in the setup function. The gcc compiler has "_BV()" and Arduino has "bit()" to select a bit. You don't use both. The Arduino also enables the global interrupt. You can make it yourself easier with the Arduino functions, and only optimize the ISR if you have to.

@chrisl, Those are typos. Thank you for noticing. Edited. But why should I write it to PIND not a PORTD? Your typo?

Pin 2 is pulled up by internal R then pulled up when button is pressed?
Connect button to GND.

OMG. I did not understand correctly what pull-up means. Thank you all. Now it works.


text:
Stop Arduino Timer after some seconds
I'm building a basic program that when a button is pressed, a buzzer comes on.
I would like however to make it so that the buzzer stops after a short period of time (e.g. 5-7 seconds).
Here is the code I have so far which is pretty basic I know forgive me but I have no clue on how to go forward.
// Setting The Pin Numbers
const int touchsensor = 2;     // the number of the touchsensor pin
const int buzzer =  4;         // the number of the LED pin

// variables:
int touchsensorState = 0;      // variable for reading the touchsensor status

void setup() {
  // initialize the buzzer as an output:
  pinMode(buzzer, OUTPUT);
  // initialize the touchsensor as an input:
  pinMode(touchsensor, INPUT);
}

void loop() {
  // read state of the pushbutton value:
  touchsensorState = digitalRead(touchsensor);

  // check if the touch sensor is pressed. If it is, the touchsensorState is HIGH:
  if (touchsensorState == HIGH) {
    // buzzer will emit sound:
    digitalWrite(buzzer, HIGH);
  } else {
    // buzzer will not sound:
    digitalWrite(buzzer, LOW);
  }
}

Easy way: After turning on the buzzer, delay for your wanted amount of milliseconds, then turn the buzzer off. Little bit harder but more efficient way: Blink without Delay technique (https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay)

You set a timestamp = millis() when the button is pushed and then you disable the buzzer only when millis() - timestamp > timeout
if (touchsensorState == HIGH) {
    // buzzer will emit sound:
    digitalWrite(buzzer, HIGH);
    timestamp = millis();
}
if(millis() - timestamp > timeout) {
    // buzzer will not sound:
    digitalWrite(buzzer, LOW);
}

Note: If you press the button during the time the buzzer is active, it will re-write the timestamp so that it is triggered in "now + timestamp", i.e. prolong the time when it's turned off. You may want to insert a "if button is already active, do not modify timestamp" logic if you need it.

You can time this with the millis() function. Refer to the BlinkWithoutDelay example from the Arduino IDE.
Then you set a timestamp, when the button is pressed:
if(touchsensorState == HIGH) timestamp = millis();

And then you are checking this timestamp against the current time:
if(millis() - timestamp > duration){
  digitalWrite(buzzer, HIGH);
} else {
  digitalWrite(buzzer, LOW);
}

duration is the timespan during which the buzzer should stay on after the button was released. If you want to turn it of, regardless of the button state, you can add a boolean flag to your if-statement, to set the timestamp only, when the button was pressed first:
if(!button_pressed && touchsensorState == HIGH){
  timestamp = millis();
  button_pressed = true;
}

In this case you have to reset the button_pressed variable to false, when you are turning of the buzzer in the millis()-else-statement

I keep getting timestamp was not declared in this scope?

because you have to declare it as a variable (of type unsigned long, since this is the return type of millis())


text:
MPU6500 via SPI
I'm trying to communicate with an MPU6500 sensor via SPI as I need the fastest possible update rate. I have trouble finding an easy to understand sample code, or perhaps a lightweight library how to configure and initialize the sensor and read gyro / accelerometer data via SPI.
So far I started adapting the code and info found at https://playground.arduino.cc/Main/MPU-6050 thought it would be fairly easy to use SPI instead of I2C "Wire", and adapt the configuration and registers based on the datasheet, but I realized there's too many possible pitfalls.
Any recommendations?

What library you already found? And what part of the sample code you have questions about?

@MichelKeijzers added info.

I retracted my close flag, I never tried this sensor, normally components are either for SPI or I2C (or another communication means), but not supporting both, so I am surprised you can even change from I2C to SPI.

Read the data sheet and SPI protocol is quite easy to implement!

Thanks Michel, yes it does definitely support both.

For anyone who has not yet figured this out, its very simple.
Basically, for SPI communication with the sensor MPU 6500, its a bit different from what I2C has to offer.
In I2C, basically you will find the data packet is as follows:
(7 bit Slave Address + Read/Write Bit), but in SPI it is as follows:
(Read/Write Bit + 7 Bit Register Address), notice we dont even need the slave address in SPI as the Chip Select is connected from processor(Master) to Sensor(Slave).
So for SPI, lets say you want to write a value 64 to register 0x6B, then:
Transmission_data[2];
Transmission_data[0] = 0x6B;
Transmission_data[1] = 64;
Lets say you want to read a value from register 0x43, which is GYRO_X_High Byte value, then,
Transmission_data[1];
Transmission_data[0] = 0x43 | 0x80; // you need to or it with 0x80(decimal = 128)
Thanks...Hope this helps someone in need of help for SPI as I struggled too in finding this information.


text:
How to send float numbers from python3 with struct to arduino
I have searched several questions and through google but could not find a solution. I am simply trying to send a float number from python3 with struct to arduino or if there is any other ways other than processing a char array at the arduino side because it is very slow in my opinion..
My arduino code:
void setup() {
  // initialize the serial communication:
  Serial.begin(9600);
}

void loop() {

  unsigned long t = millis();
  float x = analogRead(A3);
  float y = analogRead(A2);
  float c = Serial.read();
  Serial.println(c);
  //Serial.print(t/1000.0);
  //Serial.print(" , ");
  //Serial.print(x);
  //Serial.print(" , ");
  //Serial.println(y);

  // wait a bit for the analog-to-digital converter to stabilize after the last
  // reading:
  //delayMicroseconds(200);
  //delay(2);
  delay(250);
}

My python3 code :
import serial

import struct

arduino = serial.Serial('/dev/ttyACM0', 9600)
data = arduino.write(struct.pack('f', 111.32))
while True:
#    arduino.write(b"123")
    data = arduino.write(struct.pack('f', 111.32))

Getting the serial output as :
163.00
222.00
66.00
215.00
163.00
222.00
66.00
215.00
163.00
222.00
66.00
215.00
163.00

How can i solve my problem ?
EDIT : I changed the arduino code according to the answer the new arduino code is
float f;
void setup(){
  Serial.begin(9600);
}

void loop(){
  while(Serial.available() >= 3){

    f = Serial.read() << 24;
    f = ((unsigned long) f) | (Serial.read() << 16);
    f = ((unsigned long) f) | (Serial.read() << 8);
    f = ((unsigned long) f) | Serial.read();
    Serial.println(f);
  }
  Serial.println(f);
}

However, the output is now as such:
ovf
ovf
ovf
ovf
ovf
ovf
ovf
4294941184.00
4294941184.00
4294941184.00
4294941184.00
4294941184.00
4294941184.00
4294941184.00

I found a better way dealing with the conversion from char to float (note that you yourself have to add the setup() function for initiating Serial):
float f;
byte *fdata = (byte *) &f;
int num = 0;

void loop()
{
  if(Serial.available()){
    char c = Serial.read();
    if(c == 'B'){
      fdata[3] = c;
      num = 1;
    } else if(num == 1){
      fdata[2] = c;
      num++;
    } else if(num == 2){
      fdata[1] = c;
      num++;
    } else if(num == 3){
      fdata[0] = c;
      num = 0;
      Serial.write(fdata, 4);
      Serial.println(f);
    }
  }
}

First we are defining our float variable f and then a pointer of type byte named fdata. We are setting this pointer to point to our float variable. Now you can treat this pointer as an array. Since the type of the pointer is byte, we can access the first byte of f with typing fdata[0]. The other bytes can be accessed through fdata[1], fdata[2] and fdata[3].
In the loop example we are checking, if there is any byte in the buffer and read it. If it is the value of the character 'B' (which I used as a trigger, that your float starts, since the float number 111.32 starts with this value) we copy it to the last (most significant) byte of the array (aka float variable f). One after another we are doing the same with the other bytes.
When we received the last of the 4 bytes, we write the value back to Serial, once as pure byte data and once as ASCII encoded string.
In Python you can use the code, you already used:
arduino.write(struct.pack('>f',111.32))

You can read the output of the above sketch back with
arduino.readline()

PS: From my tries I guess the previous problem with getting ovf was, that the byte order was reversed (which simply would have been solved by using <f for the struct in python). But I personally like this way better, because it uses less casting.

Thank you for this and previous answers !! This will do i guess.

There is no way around dealing with serial bytewise, since the communication over serial relies on bytes as a unit. You can write the received bytes directly to the float variable. That is faster, than save them to a char array first:
float f = Serial.read() << 24;
f = ((unsigned long) f) | (Serial.read() << 16);
f = ((unsigned long) f) | (Serial.read() << 8);
f = ((unsigned long) f) | Serial.read();

With this the bytes of the float value have to be send with the order from most significant to least significant. I don't know, how the data is formatted, if you send a struct over python. The casting to unsigned long is important here to do the bitwise OR (unsigned long and float have both 4 bytes). (I tried it and it works for me)
Also be aware, that you shouldn't read from Serial, when there is no received byte in the buffer. You can check this with Serial.available(). If there is no new byte in the buffer the Serial.read() function returns an integer with value -1
EDIT:
The code above works, if you transmit the data directly as byte. In your comment you wrote, that you want to write arduino.write(b"111.32") in python. Here you are transmitting an ASCII string representation of the float number 111.32. This is not as fast as transmitting byte data (since you may need way more bytes for one float than 4). In this case you can use either Serial.parseFloat() to get the float from the serial buffer (but ensure, that all bytes for this number have been received with Serial.available()) or you can save the bytes to a string and using String.toFloat() to get the float out of it.
Since you wanted to do it the fast way, you should transmit the numbers as byte data. To do this in python, have a look at the answer of this question. It explains the python code for it (be sure, that you get the ordering of the bytes the same in python and Arduino).

When I try your code it gives an error like invalid operands of types 'float' and 'int' to binary 'operator| to all |= operators. I can send the float number as arduino.write(b"111.32") . Will this be better for your approach? I also added the Serial.available() part thank you.

Ah, ok. Now I understand, what you are trying to do. I will edit my answer. And yes, I didn't anticipated, that you have to cast

Thank you for your reply. However, I am still stuck at a point. You say that i have to send it as byte data and the way I change a float number to a byte representation is data = bytes(23.2) right ? and then i try arduino.write(data) but data = bytes(23.2) gives an error which says  float object is not iterable. I know I ask much but can you also provide a python sample code please ? Or when i try to do it with arduino.write(struct.pack('>f', 23.2)) it gives the serial output as ovf

I added a link to a question, which answers this for you

Thank you for the link. I have already checked that question and got the struct way from there. However, when I use your code to read the data i got overflow. Couldn't solve it. :( Updated the question accordingly


text:
One port of motor shield doesn't operating stepper motor

One port of my motor shield (i.e M1 & M2) is not driving the stepper motor as it should.stepper motor jitters at its position.
While the other port (M3 & M4) works fine but it makes stepper motor too hot and also it's respective motor driver L293D IC.
While all the ports of motor shield works fine with DC Motor.

I am making CNC plotter using this setup.
I am powering motor shield with 12 V adapter and Arduino is connected with USB cable.
This is the code I am using :
#include <Servo.h>
#include <AFMotor.h>

#define LINE_BUFFER_LENGTH 512

char STEP = MICROSTEP ;

// Servo position for Up and Down
const int penZUp = 115;
const int penZDown = 83;

// Servo on PWM pin 10
const int penServoPin =10 ;

// Should be right for DVD steppers, but is not too important here
const int stepsPerRevolution = 48;

// create servo object to control a servo
Servo penServo;

// Initialize steppers for X- and Y-axis using this Arduino pins for the L293D H-bridge
AF_Stepper myStepperY(stepsPerRevolution,1);
AF_Stepper myStepperX(stepsPerRevolution,2);

/* Structures, global variables    */
struct point {
  float x;
  float y;
  float z;
};

// Current position of plothead
struct point actuatorPos;

//  Drawing settings, should be OK
float StepInc = 1;
int StepDelay = 0;
int LineDelay =0;
int penDelay = 50;

// Motor steps to go 1 millimeter.
// Use test sketch to go 100 steps. Measure the length of line.
// Calculate steps per mm. Enter here.
float StepsPerMillimeterX = 100.0;
float StepsPerMillimeterY = 100.0;

// Drawing robot limits, in mm
// OK to start with. Could go up to 50 mm if calibrated well.
float Xmin = 0;
float Xmax = 40;
float Ymin = 0;
float Ymax = 40;
float Zmin = 0;
float Zmax = 1;

float Xpos = Xmin;
float Ypos = Ymin;
float Zpos = Zmax;

// Set to true to get debug output.
boolean verbose = false;

//  Needs to interpret
//  G1 for moving
//  G4 P300 (wait 150ms)
//  M300 S30 (pen down)
//  M300 S50 (pen up)
//  Discard anything with a (
//  Discard any other command!

/**********************
 * void setup() - Initialisations
 ***********************/
void setup() {
  //  Setup

  Serial.begin( 9600 );

  penServo.attach(penServoPin);
  penServo.write(penZUp);
  delay(100);

  // Decrease if necessary
  myStepperX.setSpeed(600);

  myStepperY.setSpeed(600);

  //  Set & move to initial default position
  // TBD

  //  Notifications!!!
  Serial.println("Mini CNC Plotter alive and kicking!");
  Serial.print("X range is from ");
  Serial.print(Xmin);
  Serial.print(" to ");
  Serial.print(Xmax);
  Serial.println(" mm.");
  Serial.print("Y range is from ");
  Serial.print(Ymin);
  Serial.print(" to ");
  Serial.print(Ymax);
  Serial.println(" mm.");
}

/**********************
 * void loop() - Main loop
 ***********************/
void loop()
{

  delay(100);
  char line[ LINE_BUFFER_LENGTH ];
  char c;
  int lineIndex;
  bool lineIsComment, lineSemiColon;

  lineIndex = 0;
  lineSemiColon = false;
  lineIsComment = false;

  while (1) {

    // Serial reception - Mostly from Grbl, added semicolon support
    while ( Serial.available()>0 ) {
      c = Serial.read();
      if (( c == '\n') || (c == '\r') ) {             // End of line reached
        if ( lineIndex > 0 ) {                        // Line is complete. Then execute!
          line[ lineIndex ] = '\0';                   // Terminate string
          if (verbose) {
            Serial.print( "Received : ");
            Serial.println( line );
          }
          processIncomingLine( line, lineIndex );
          lineIndex = 0;
        }
        else {
          // Empty or comment line. Skip block.
        }
        lineIsComment = false;
        lineSemiColon = false;
        Serial.println("ok");
      }
      else {
        if ( (lineIsComment) || (lineSemiColon) ) {   // Throw away all comment characters
          if ( c == ')' )  lineIsComment = false;     // End of comment. Resume line.
        }
        else {
          if ( c <= ' ' ) {                           // Throw away whitepace and control characters
          }
          else if ( c == '/' ) {                    // Block delete not supported. Ignore character.
          }
          else if ( c == '(' ) {                    // Enable comments flag and ignore all characters until ')' or EOL.
            lineIsComment = true;
          }
          else if ( c == ';' ) {
            lineSemiColon = true;
          }
          else if ( lineIndex >= LINE_BUFFER_LENGTH-1 ) {
            Serial.println( "ERROR - lineBuffer overflow" );
            lineIsComment = false;
            lineSemiColon = false;
          }
          else if ( c >= 'a' && c <= 'z' ) {        // Upcase lowercase
            line[ lineIndex++ ] = c-'a'+'A';
          }
          else {
            line[ lineIndex++ ] = c;
          }
        }
      }
    }
  }
}

void processIncomingLine( char* line, int charNB ) {
  int currentIndex = 0;
  char buffer[ 64 ];                                 // Hope that 64 is enough for 1 parameter
  struct point newPos;

  newPos.x = 0.0;
  newPos.y = 0.0;

  //  Needs to interpret
  //  G1 for moving
  //  G4 P300 (wait 150ms)
  //  G1 X60 Y30
  //  G1 X30 Y50
  //  M300 S30 (pen down)
  //  M300 S50 (pen up)
  //  Discard anything with a (
  //  Discard any other command!

  while( currentIndex < charNB ) {
    switch ( line[ currentIndex++ ] ) {              // Select command, if any
    case 'U':
      penUp();
      break;
    case 'D':
      penDown();
      break;
    case 'G':
      buffer[0] = line[ currentIndex++ ];          // /!\ Dirty - Only works with 2 digit commands
      //      buffer[1] = line[ currentIndex++ ];
      //      buffer[2] = '\0';
      buffer[1] = '\0';

      switch ( atoi( buffer ) ){                   // Select G command
      case 0:                                   // G00 & G01 - Movement or fast movement. Same here
      case 1:
        // /!\ Dirty - Suppose that X is before Y
        char* indexX = strchr( line+currentIndex, 'X' );  // Get X/Y position in the string (if any)
        char* indexY = strchr( line+currentIndex, 'Y' );
        if ( indexY <= 0 ) {
          newPos.x = atof( indexX + 1);
          newPos.y = actuatorPos.y;
        }
        else if ( indexX <= 0 ) {
          newPos.y = atof( indexY + 1);
          newPos.x = actuatorPos.x;
        }
        else {
          newPos.y = atof( indexY + 1);
          indexY = '\0';
          newPos.x = atof( indexX + 1);
        }
        drawLine(newPos.x, newPos.y );
        //        Serial.println("ok");
        actuatorPos.x = newPos.x;
        actuatorPos.y = newPos.y;
        break;
      }
      break;
    case 'M':
      buffer[0] = line[ currentIndex++ ];        // /!\ Dirty - Only works with 3 digit commands
      buffer[1] = line[ currentIndex++ ];
      buffer[2] = line[ currentIndex++ ];
      buffer[3] = '\0';
      switch ( atoi( buffer ) ){
      case 300:
        {
          char* indexS = strchr( line+currentIndex, 'S' );
          float Spos = atof( indexS + 1);
          //         Serial.println("ok");
          if (Spos == 30) {
            penDown();
          }
          if (Spos == 50) {
            penUp();
          }
          break;
        }
      case 114:                                // M114 - Repport position
        Serial.print( "Absolute position : X = " );
        Serial.print( actuatorPos.x );
        Serial.print( "  -  Y = " );
        Serial.println( actuatorPos.y );
        break;
      default:
        Serial.print( "Command not recognized : M");
        Serial.println( buffer );
      }
    }
  }

}

/*********************************
 * Draw a line from (x0;y0) to (x1;y1).
 * int (x1;y1) : Starting coordinates
 * int (x2;y2) : Ending coordinates
 **********************************/
void drawLine(float x1, float y1) {

  if (verbose)
  {
    Serial.print("fx1, fy1: ");
    Serial.print(x1);
    Serial.print(",");
    Serial.print(y1);
    Serial.println("");
  }

  //  Bring instructions within limits
  if (x1 >= Xmax) {
    x1 = Xmax;
  }
  if (x1 <= Xmin) {
    x1 = Xmin;
  }
  if (y1 >= Ymax) {
    y1 = Ymax;
  }
  if (y1 <= Ymin) {
    y1 = Ymin;
  }

  if (verbose)
  {
    Serial.print("Xpos, Ypos: ");
    Serial.print(Xpos);
    Serial.print(",");
    Serial.print(Ypos);
    Serial.println("");
  }

  if (verbose)
  {
    Serial.print("x1, y1: ");
    Serial.print(x1);
    Serial.print(",");
    Serial.print(y1);
    Serial.println("");
  }

  //  Convert coordinates to steps
  x1 = (int)(x1*StepsPerMillimeterX);
  y1 = (int)(y1*StepsPerMillimeterY);
  float x0 = Xpos;
  float y0 = Ypos;

  //  Let's find out the change for the coordinates
  long dx = abs(x1-x0);
  long dy = abs(y1-y0);
  int sx = x0<x1 ? StepInc : -StepInc;
  int sy = y0<y1 ? StepInc : -StepInc;

  long i;
  long over = 0;

  if (dx > dy) {
    for (i=0; i<dx; ++i) {
      myStepperX.onestep(sx,STEP);
      over+=dy;
      if (over>=dx) {
        over-=dx;
        myStepperY.onestep(sy,STEP);
      }
    delay(StepDelay);
    }
  }
  else {
    for (i=0; i<dy; ++i) {
      myStepperY.onestep(sy,STEP);
      over+=dx;
      if (over>=dy) {
        over-=dy;
        myStepperX.onestep(sx,STEP);
      }
      delay(StepDelay);
    }
  }

  if (verbose)
  {
    Serial.print("dx, dy:");
    Serial.print(dx);
    Serial.print(",");
    Serial.print(dy);
    Serial.println("");
  }

  if (verbose)
  {
    Serial.print("Going to (");
    Serial.print(x0);
    Serial.print(",");
    Serial.print(y0);
    Serial.println(")");
  }

  //  Delay before any next lines are submitted
  delay(LineDelay);
  //  Update the positions
  Xpos = x1;
  Ypos = y1;
}

//  Raises pen
void penUp() {
  penServo.write(penZUp);
  delay(penDelay);
  Zpos=Zmax;
  digitalWrite(15, LOW);
    digitalWrite(16, HIGH);
  if (verbose) {
    Serial.println("Pen up!");

  }
}
//  Lowers pen
void penDown() {
  penServo.write(penZDown);
  delay(penDelay);
  Zpos=Zmin;
  digitalWrite(15, HIGH);
    digitalWrite(16, LOW);
  if (verbose) {
    Serial.println("Pen down.");

  }
}

This are the connections I made:

I tried replacing motors with each other but the case remains same just the motor now connected to the port(which is not working ) starts jittering and another one works but gets too hot.

I ran into the same issue yesterday. The problem is that one of the pins of the M1 Port touches the housing of the usb-jack and shortens Vcc to Gnd. Try to put some tape around the housing...
bye


text:
Read CID from SD card with ESP8266
I would like to get the serial numbers of SD cards, with follow code:
#include <SPI.h>
#include <SD.h>

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

cid_t cid;  // *****at the top with the other globals (for get cid)

// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
const int chipSelect = 4;

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

  Serial.print("\nInitializing SD card...");

  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card inserted?");
    Serial.println("* is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    return;
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }

  // print the type of card
  Serial.print("\nCard type: ");
  switch (card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    return;
  }

  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("\nVolume type is FAT");
  Serial.println(volume.fatType(), DEC);
  Serial.println();

  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();       // we'll have a lot of clusters
  volumesize *= 512;                            // SD card blocks are always 512 bytes
  Serial.print("Volume size (bytes): ");
  Serial.println(volumesize);
  Serial.print("Volume size (Kbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Mbytes): ");
  volumesize /= 1024;
  Serial.println(volumesize);

  Serial.println();

  // *****list all files in the card with date and size
  //Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  //root.openRoot(volume);
  //root.ls(LS_R | LS_DATE | LS_SIZE);

  card.readCID(&cid);
  Serial.print("Serial number: "); Serial.println(cid.src); // psn is the serial number field of the struct

}

void loop(void) {

}

I tried to get serial from SD card but I only get this "Serial number: 2065301974". I really need it in hex format, for example "0x0033515c".
Also, I would like to get the complete CID like this:
CID: 0x1B, 0x53, 0x4D, 0x30, 0x30, 0x30, 0x30, 0x30, 0x10, 0x45, 0x5D, 0x04, 0xE5, 0x00, 0xF9, 0x69

TLDR. Is your question "how do I convert a decimal string into a hex number"?

I see no "src" in the cid_t structure....

the CID is not a true "serial number" it's easily hackable. don't use this for security.

cid_t is a structure that has all sorts of information in it in different formats.  The serial number (psn) is just a 32-bit unsigned integer.  You can print it as hex by printing it as hex.
Serial.println(cid.psn, HEX);

If you want to get the raw data of the structure (which I assume may correspond to the raw data read from the card, but don't quote me on that) you can access the struct as 8-bit values:
uint8_t *p = (uint8_t *)&cid;
for (int i = 0; i < sizeof(cid); i++) {
    Serial.print("0x");
    Serial.print(p[i], HEX);
    Serial.print(" ");
}
Serial.println();

Thank you for your help. I tried this and I got: 12 10 17 4D 49 42 53 54 2 0 0 5 A2 0 19 11 0 0 0 0 I know that is wrong because I got serial of sd card on linux and the real serial number ir "0x000005a2" and what I really want is the complete cid number as shown here a.d-cd.net/ec9effas-960.jpg I´m very grateful –

These are the data obtained from Linux: cid: 041641534d492d534403000000001601 serial: 0x03000000 And these are the data obtained from ESP8266: cid (with your code): 1210174E4361726410001C5019AF0000 serial (whit cid.psn): 0xAF1900C5 Then, apparently it is not showing the correct dada... I think something is wrong with the code. Please help me.

How are you getting the data in Linux?

The CID I find in this file SYS->BLOCK->MMCBLK0->DEVICE->cid and the serial I find in this file SYS->BLOCK->MMCBLK0->DEVICE->serial

Are you sure that you are looking at the right device?

Yes, because when I disconnect the sd card... this folder "MMCBLK0" disappears... and when I connect the sd card... this folder "MMCBLK0" appears... Is it OK?

What device are you using for this test? (the Linux device I mean)...?

The Linux kernel handles two different formats of CID. Maybe that has something to do with it. The source is here.

I think I need get raw cid. Any idea for get on Arduino? The complete CID (32 digits, like this: 041641534d492d534403000000001601)

To print the serial number in hex Serial.println accepts a format parameter:
Serial.println(cid.psn, HEX);

The cid variable is a struct so you can access the the other fields via the structure. But if you really want to access the raw bytes you could cast cid to a pointer then access the individual bytes:
uint8_t *rawcid = reinterpret_cast<uint8_t*>(&cid);
Serial.println(*(cid+3), HEX); // print the 4th byte

Be aware that casting like this can be tricky and you will likely shoot yourself in the foot more than once.

Thank you for your help. I tried this and I got: 12 10 17 4D 49 42 53 54 2 0 0 5 A2 0 19 11 0 0 0 0
I know that is wrong because I got serial of sd card on linux and the real serial number ir "0x000005a2" and what I really want is the complete cid number as shown here https://a.d-cd.net/ec9effas-960.jpg
I´m very grateful

The serial number is just a small part of the Cid. You can see 0 0 5 A2 which as uint32_t is 000005a2 in the string of bytes you have.

These are the data obtained from Linux:
cid: 041641534d492d534403000000001601
serial: 0x03000000
And these are the data obtained from ESP8266:
cid (with your code): 1210174E4361726410001C5019AF0000
serial (whit cid.psn): 0xAF1900C5
Then, apparently it is not showing the correct dada...
I think something is wrong with the code.
Please help me.


text:
Can't identify + or - in the 5v USB wall adapter, does it matter?

I want to power the UNO with the USB power adapter (the charger of a phone), the adapter delivers 5.0 volts and comes from the wall (in the photo a regulator is added). However, the legs of the USB adapter look the same, can I plug it to the wall indistinctly like I do when I charge the phone, or do I need to know which leg is + and which one is - ? (I don't have measurement equipment).

the circuitry of the adapter corrects the polarity to the USB cable for you.

Does the phone charge OK whichever way you plug it in? If so, why wouldn't the Arduino?

Power (which comes from your wall outlet), is AC, which means alternating current. It changes 50 or 60 times per second from direction, so this is the reason it does not matter if you plug it reversed or not. Some countries have plugs which can be plugged in normally or 180 degrees rotated (but you cannot see what is 0 or 180 degrees since these are symmetrical).
The circuit inside the adapter makes sure the AC is converted to DC, where it matters what is Plus or Minus.

It does not matter which orientation you plug it into the mains plug.
The power supply produces the same 5V regardless, and the USB plug has a fixed/standard polarity on the pinout.


text:
Servo position is always changing
When I send an SMS like this:

Tilt:090
Azimuth:120

First time an SMS is read, the servo rotates to the correct position, but after they change a small angle, it's like noise.
I do following things to stop that change:

First try with motor driver

Capacitor circuit use

Here is my code:
#include <AFMotor.h>
#include <Sim800l.h>
#include <SoftwareSerial.h>
#include <Servo.h>

Sim800l Sim800l; //to declare the library
Servo Tilt;
Servo Azimuth;

String text; // to storage the text of the sms
uint8_t index; // to indicate the message to read.
int t, pos, old_pos, pos1, old_pos1; // to indicate the int value.

void setup()
{
    Tilt.attach(9); // attaches the servo on pin 5 to the servoH object
    Azimuth.attach(10); // attaches the servo on pin 6 to the servoV object
    Serial.begin(9600); // only for debug the results .
    Sim800l.begin(); // initializate the library.
    index = 1; //  position in the prefered memory storage.
}

void Tilt_servo()
{
    if (old_pos > pos) {
        for (int q = old_pos; q > pos; q--) {
            Tilt.write(q);
            delay(20);
            Serial.println("position dicreasing");
        }
    }
    else if (old_pos < pos) {
        for (int q = old_pos; q < pos; q++) {
            Tilt.write(q);
            delay(20);
            Serial.println("position increasing");
        }
    }
    else {
        Tilt.write(pos);
    }
}

void Azimuth_servo()
{
    if (old_pos1 > pos1) {
        for (int d = old_pos1; d > pos1; d--) {
            Azimuth.write(d);
            delay(20);
            Serial.println("position1 dicreasing");
        }
    }
    else if (old_pos < pos) {
        for (int d = old_pos1; d < pos1; d++) {
            Azimuth.write(d);
            delay(20);
            Serial.println("position1 increasing");
        }
    }
    else {
        Azimuth.write(pos1);
    }
}

void loop()
{
    delay(1000);

    Serial.println("---------------------------------------------------------------------------");
    old_pos = pos;
    old_pos1 = pos1;

    Serial.println("old_pos:");
    Serial.println(old_pos);
    Serial.println("old_pos1:");
    Serial.println(old_pos1);

    text = Sim800l.readSms(index);
    Serial.println(text);
    String W = text.substring(33, 45); // filter phone number...
    Serial.println(W);
    String y = text.substring(20, 30); // filter REC UNREAD
    Serial.println(y);

    if (y == "REC UNREAD") {

        String s = text.substring(74, 79); // filter the "Tilt:"
        Serial.println(s);
        String p = text.substring(79, 82); // filter the position
        int t = p.toInt(); // convert position as int value
        Serial.println(t);
        pos = t;

        String v = text.substring(83, 91); // filter the "Azimuth:" letter
        Serial.println(v);
        String u = text.substring(91, 94); // filter the position as string
        int b = u.toInt(); // convert position as int value
        Serial.println(b);
        pos1 = b;

        if (s == "Tilt:" && v == "Azimuth:") {

            Tilt_servo();
            delay(1000);
            Serial.println("done....Tilt...");
            Serial.println(pos);
            Azimuth_servo();
            delay(1000);
            Serial.println("done....Azimuth...");
            Serial.println(pos1);
        }
        //Sim800l.delAllSms();
        //delay(5000);
    }

    else {
        Tilt.write(pos);
        Azimuth.write(pos1);
    }

    delay(1000);
    Sim800l.delAllSms();
    delay(5000);
    Serial.println("---------------------------------------------------------------------------");
}

you need to start troubleshooting by writing minimal code that positions one servo, holds position for a second or so, then positions servo to another point and holds again .... test all servos that way

i tested all servo.then they all work correctly. but above code running it start the same problem

comment out lines like this Serial.println("position1 dicreasing"); ... see if that may clear it up ... btw, the word is "decreasing"

i tested. in these two lines executed that error happen.so it can be affect sim800l library.    text = Sim800l.readSms(index); and Sim800l.delAllSms();


text:
Can't reprogram Arduino on protoboard (perfboard), but could program the same circuit on breadboard
So I have a circuit that works well when it's on a breadboard and without removing any pins I'm able to upload sketches, but for some reason when I transition it to a protoboard I can no longer upload sketches.
My circuit consists of an MPU6050, an Arduino Pro Mini, and a HC-08 BLE module. I've tried protoboarding this circuit twice with Arduino Pro Minis and once with an Arduino Nano, and now I'm not able to upload sketches to any of these three circuits.
I'm using perfboard (not stripboard, so yes I have already connected the jumper wires to the header pins) and know that the circuit partially works since the IMU, Arduino, and BLE LEDs all light and you can connect to the BLE on a mobile terminal app.
The error I get is:
avrdude: stk500_getsync(): not in sync: resp=0x00,

I use SoftwareSerial.h so NO pins are connected to the Arduinos 0 and 1 pins.
I've already tried restarting the IDE
I've tried disconnecting/reconnecting the USB cable
There's only one COM# port so I'm sure I'm using the right one.

I'm so stumped because this error message did not occur when I was playing with the same circuit on a breadboard...
Any ideas on how I can fix this or what I'm doing wrong?

something is probably pulling the power down .... disconnect the arduino from the circuit and try loading

Did you remember to include all the bypass capacitors?

.. I'm using an arduino Pro Mini, and didn't use any bypass capacitors in my breadboarded circuit, can you clarify?

Maybe post a sketch of your circuit?

https://arduino.stackexchange.com/questions/8847/getting-avrdudestk500-recv-programmer-is-not-responding-while-uploading-sk


text:
How to create a device with buttons that records when they are pressed
I want to build a very simple device, which has a bunch of buttons for switching "settings" and LED lights to show which "setting" it is on.  I also want it to record the times of the transitions between settings so that I can later connect it to a computer through USB and retrieve the timestamps of the setting changes, i.e. when the buttons were pressed.
What is the best way to do this?  Is it with Arduino or some other way?  If it is with Arduino, what would I need to buy, and what would I need to read?

What research have you done? Code?

Arduino is ideal for it. Buy Arduino or Genuino UNO with Starter Kit. Starter kits contain buttons, LEDs, resistors, breadboard and example projects brochure.
link: Getting Started with Arduino

All is reasonably easy.

Buttons: use separate buttons, or think about a small 4x4 matrix keypad.
LED: WS8212 etc or use your own separate LEDs (very cheap)
Record times: store them on a SD card
USB: It is possible to send texts via USART which can connect via USB; also you can consider putting the SD card directly in your computer.


text:
other interrupts in rc channel reader
I have the sketch from James Waldby (Read RC receiver channels using Interrupt instead of PulseIn) working beautifully. I want to use a switch on my TX to start and stop a sequence of lights (emulating guns firing on a ship model). But first, I need the delayed flash routine to work. I have tried a loop counting millis() differences to separate the sequences, but the delays don't delay.
 void loop(){
  rc_read_values();//Mr. Waldby's interrupt routine
  currentMillis = millis();
  previousMillis = currentMillis;
  if(fireGun ==1){
    interval = 3000;
  }else{
    interval = 1500;
  }
  interval = 3000;
  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

//if(fireGun ==1){
  analogWrite(led, 255);
  delay(50);
/* a real gun flash doesn't cut right off; it fades away.
  This sequence simulates that  */
  while(brightness > 0){

    // change the brightness for next time through the loop:
    brightness = brightness - fadeAmount;
    analogWrite(led, brightness);
    delay( 7);
  }
  brightness = 80;
}

The intention here is to flash the led every 3 seconds. The flash loop works fine, but the 3 second delay doesn't.
The delay routine works ok in a sketch by itself.
Any thoughts about what I might be doing wrong?

go through the loop() code listing step by step ... write values of variables on a sheet of paper as you go along

  currentMillis = millis();
  previousMillis = currentMillis;

So currentMillis and previousMillis will always be exactly the same, right?

  if (currentMillis - previousMillis >= interval) {

So if 0 >= interval (which it won't be) do something?
Therefore your fading code will never be executed.


text:
Selecting different arrays using a list of pointers
I have different arrays of different sizes, and a list of pointers to the addresses of each array. How do I select each array using the list of pointers, and access it's elements. On Teensy 3.2 board.
int * arr_list[3];
const int arr_sizes[3] = {3,4,5};  // array of the array sizes
const int ar1[3] = {12,2,8};       // arrays of  different sizes
const int ar2[4] = {41,3,6,47};
const int ar3[5] = {9,32,1,5,7};

void map_arrays(){          // list of pointers with the addresses of the
                            // arrays
arr_list[0] = (int*) &ar1;
arr_list[1] = (int*) &ar2;
arr_list[2] = (int*) &ar3;
};

int arr_number = 1;          // select array
int a = arr_sizes[arr_number];    // the size of the selected array
int *b = arr_list[arr_number];
int test = 0;

void setup() {

Serial.begin(57600);  //serial monitor

}

void loop() {

for (int i=0; i<a; i++) {     // for the selected arr_number iterate and
test = b[i];                  // return the index elements

}

Serial.println("size =");
Serial.println(a);
Serial.println();
delay(1000);
Serial.println("index =");
Serial.println(test);
Serial.println();
delay(500);

 }

You terminate each array appropriately.

You have it right, only fix initialization of test variables:

you do not call map_arrays() in setup()
you assign uninitialized arr_list item to b

const int* arr_list[3];
const int arr_sizes[3] = { 3, 4, 5 };  // array of the array sizes
const int ar1[3] = { 12, 2, 8 };       // arrays of  different sizes
const int ar2[4] = { 41, 3, 6, 47 };
const int ar3[5] = { 9, 32, 1, 5, 7 };

void map_arrays() {          // list of pointers with the addresses of the
// arrays
  arr_list[0] = ar1;
  arr_list[1] = ar2;
  arr_list[2] = ar3;
}

int arr_number = 1;          // select array
int a = arr_sizes[arr_number];    // the size of the selected array
const int *b;
int test = 0;

void setup() {

  Serial.begin(57600);  //serial monitor

  map_arrays();

  b = arr_list[arr_number];

  for (int i = 0; i < a; i++) {     // for the selected arr_number iterate and
    test = b[i];                 // return the index elements
    Serial.println(test);
  }

  Serial.println("size =");
  Serial.println(a);
  Serial.println();
  delay(1000);
  Serial.println("index =");
  Serial.println(test);
  Serial.println();
  delay(500);

}

void loop() {
}


text:
Not getting pure color while using the FastLED with WS2812b
I am working with the LED strip WS2812b and FastLED library, currently I have only 3 LEDs connected in such a way that the first 2 receive a color (say green) and the last one receives another one (say blue).
The problem is that by putting the color (blue) on the last LED, the other two (currently only in green) also take a portion of blue, preventing it from being a pure (green) color. It happens with any combination of color.
I leave the piece of my code referring to the LED strip:
#include "FastLED.h"
#define NUM_LEDS 3
#define DATA_PIN 2

//Variables declaration...
....

void setup() {
  FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
.....

  }

void loop() {
  ReadMySerial();       //This function take data from serial port and set the color for the leds
  FastLED.setBrightness(brigth);

  for (int pinNo = 0; pinNo <= 2; pinNo++){
    leds[pinNo].setRGB(green_inactive,red_inactive,blue_inactive);
    FastLED.show();
      if (digitalRead(pinNo+3) == HIGH){
        leds[pinNo].setRGB(green_reactive,red_reactive,blue_reactive);
           FastLED.show();
            }
        }

  }

I already change the pin for where I put the signal for the LED strip, I try to change the type of LED strip

FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS)
FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS)
FastLED.addLeds<WS2812, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS)

without any success...
Can anyone point me in the rigth direction?
Edit: actually, the first LED of the strip is flashing, not in the way of the Blinking example, but I can see a little flashing.

Hey @gre_gor, how can I put lists when I'm asking?

https://arduino.stackexchange.com/editing-help

I can see what the problem is, I put FastLED.show(); where it should not, that's also why I saw the flash ... fix it and here's the result:
void loop() {
  ReadMySerial();       //This function take data from serial port and set the color for the leds
  FastLED.setBrightness(brigth);

  for (int pinNo = 0; pinNo <= 2; pinNo++){
    leds[pinNo].setRGB(green_inactive,red_inactive,blue_inactive);
    FastLED.show();
    if (digitalRead(pinNo+3) == HIGH){
      leds[pinNo].setRGB(green_reactive,red_reactive,blue_reactive);
    }
  }

  FastLED.show(); //NOW IS IN THE RIGHT POSITION
}