How do I use the timers on an Arduino Uno R3? I want to make a simple circuit which returns the time/delay between two, consecutive loud sounds (i.e, a mic reading of ~600) coming from a speaker. I have set up and ADMP 401 microphone for this purpose. How do I measure the time it takes for this application?

Your question is probably not as simple as it may seem.

One approach I would use if I was to address this same problem would consist in:

converting the analog output of the mike into a digital value (based on a threshold to determine)
connect this digital signal to one Arduino pin that can trigger an interrupt when its level changes

Let's first start with the easy part: Arduino program.

Let's say we have a digital signal that raises to 1 as soon as a sound of too high amplitude is captured by the mike; it shall stay 1 as long as the sound does not reduce amplitude enough. We will connect this signal to Arduino pin 3; then we can use attachInterrupt() to have a function called whenever this pon level raises to 1:

volatile static bool started = false;
volatile static unsigned long timing = 0;
volatile static bool finished = false;

void loud() {
    if (started) {
        timing = micros() - timing;
        started = false;
        finished = true;
    } else {
        timing = micros();
        started = true;
        finished = false;
    }
}

void setup() {
    pinMode(3, INPUT);
    attachInterrupt(1, loud, RAISE);
}

void loop() {
    if (finished) {
        // Do something with timing
    }
}

Now the hardest part: electronics!

A first issue we have to deal with is related to the fact that the raw mike signal will have same wave shape as the sound it captures, this wave has a frequency that can vary between 10Hz (bass) and 20KHz (treble).

Indeed, if we convert the mike analog output to a logical value (1 when the analog value is above a threshold we'll call Vt, 0 when it is under Vt) fast enough, then, if the environmental sound as an amplitude above Vt, the logical input connected to your Arduino will oscillate at the same frequency as the sound! This would make our efforts pointless as you would measure the period of the sound wave instead of the elapsed time between two distinct sound bursts.

That means that we should probably first "smoothen" the analog sound signal in order to avoid disturbance of its frequency.

Hence point 1 will have to deal with these 2 aspects:

smoothen analog input value
compare smoothened value with Vt threshold and provide a logical value from this comparison

Comparison can rather easily be performed by an op-amp used as a comparator.

However, the main difficulty you may have with an op-amp is the need for a symetric voltage supply (e.g. +5V/-5V) although it is possible to use a single supply but that raises further limitations (outside the scope of my answer).

Smoothening the signal is potentially more complex, although it can be done with a simple capacitor, because smoothening the signal generally means weakening it, thus you would lose the initial amplitude of the sound signal.

So how can we deal with that?

A Schmitt trigger is probably a good solution for this problem but further experiment will be needed to confirm that.


How are errors (not related to syntax) managed in arduino and in the AVR architecture in general? I was just curious about how the AVR architecture manages errors that would cause a regular desktop program to crash. I'm talking about logical errors for example math problems that are undefined. Such as division by 0 and getting a square root of a negative number. At first I was expecting that by giving an error to the AVR chip it will just return 0. But I ran this program:

void setup() {
Serial.begin(9600);
}
void loop(){
int x = 0;
int p = 50;
int result;
result = p/x;
Serial.println(result);
result = sqrt(-10);
delay(1000);
Serial.println(result);
delay(10000);
}

and got this output:

4294967295
0

After this I got really confused. Why would the result variable take the maximum value of an unsigned long? Since I declared an int the micro controller must have dedicated 2 bytes of dynamic memory to this variable but apparently it somehow managed to get additional 2 bytes to store the data. Could this mean that the AVR chip can corrupt data in other memory locations while allocating new data for the variable that just was fed a undefined in to it? Okay maybe the AVR chip just sets any mathematical nonsense to 4294967295. But no in the example of getting the square root of -10 we see that the value became 0. Although this is probably a function processed by some library so maybe there is some kind of protection against these errors. Also, I tried to run the program above but with a byte variable for the result instead of int.

void setup() {
Serial.begin(9600);
}
void loop(){
int x = 0;
int p = 50;
int result;
result = p/x;
Serial.println(result);
result = sqrt(-10);
delay(1000);
Serial.println(result);
delay(10000);
}

And the result was the same. So, is there some kind of documentation about error management in AVR since this is important to know while development.

P.S. Everything was run on a real Atmega 328p chip on an arduino nano.

The simple answer is: they are not handled at all.

According to the C and C++ standards, what you are invoking is called
undefined behavior, meaning anything can happen. In practical
terms, it means that the compiler can do its optimizations assuming
you will never invoke undefined behavior, and completely disregard what
could happen if the assumption does not hold. The generated code could
be completely broken, it won't be the compiler's fault.

The AVR architecture cannot do divisions, nor floating point math. Thus
all the errors you have here happen at the software level. Note that
sqrt(-10) is not an error (it's NaN, which is correctly handled by
the avr-libc), but converting that to an int (which you do when you
assign it to result) is an error.

If you really want to know the details of what happens with each of
these errors, there is only one option: you have to disassemble the
executable program and read the assembly listing.


Can I do parallel processing in Arduino? I recently got to work with Arduino and I want to get parallel input from 5 LDRs and at the same instance I need to light a LED corresponding to that LDR if the resistance got high.

I read about a finite state machine, but I couldn't understand how it works.

Is it the only way for this type of problem or are there any other way?

You do not need parallel processing or finite-state machines for that:

// Vector with digital pin numbers for LEDs (with resistor to ground)
const int LED_MAX = 5;
const int LED[LED_MAX] = { 2, 3, 4, 5, 6 };

// Vector with analog pin numbers for LDR (with pullup resistor)
const int LDR_MAX = 5;
const int LDR[LDR_MAX] = { A0, A1, A2, A3, A4 };

// Analog value or lower when to light the LED
const int THRESHOLD = 200;

void setup()
{
   // All LED pins should be digital output pins
   for (int i = 0; i < LED_MAX; i++)
     pinMode(LED[i], OUTPUT);
}

void loop()
{
   // Read all LDRs and set LED pins according to threshold
   for (int i = 0; i < LDR_MAX; i++)
     digitalWrite(LED[i], analogRead(LDR[i]) < THRESHOLD);
}

But if you really want to describe this as multiple tasks you could use the Simple Scheduler library:

#include <Scheduler.h>

const int THRESHOLD = 200;

template<int LED> void setup()
{
   pinMode(LED, OUTPUT);
}

template<int LED, int LDR> void loop()
{
   digitalWrite(LED, analogRead(LDR) < THRESHOLD);
   yield();
}

void setup()
{
   Scheduler.start(setup<2>, loop<2, A0>);
   Scheduler.start(setup<3>, loop<3, A1>);
   Scheduler.start(setup<4>, loop<4, A2>);
   Scheduler.start(setup<5>, loop<5, A3>);
   Scheduler.start(setup<6>, loop<6, A4>);
}

void loop()
{
   yield();
}


How to rsync my node.js project to my intel edison board, through ssh? I would love to get rid of Intel's heavy XDK software, and be able to quickly push the updates of my node.js code into my Intel Edison (arduino compatible) board.

I tried this: rsync -avz ./ root@192.168.100.177:/node_app_slot/

But rsync is not installed on the board.

How would you do this?

rsync works by talking to the rsync executable running on the remote target; without said executable you will need to drop to either scp or a tar pipe.


How shiftOut function works internally? (explanation on source code) I were examining shiftOut() function code in wiring_shift.c and I didn't quite understand what is going in digitalWrite function. I see !!(val & (1 << i)) is taking the bit value from val but how exactly it works?

The whole function is below.

void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        if (bitOrder == LSBFIRST)
            digitalWrite(dataPin, !!(val & (1 << i)));
        else
            digitalWrite(dataPin, !!(val & (1 << (7 - i))));

        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}

I'll assume bitOrder == LSBFIRST.

i is the bit number, i.e. the “index” of the next bit to write
1 is 00000001 in binary
<< is the shift left operator. It returns its first argument shifted left by as many positions as indicated by the second argument
1<<i is binary 00000001 shifted left by i positions, i.e. something like 0...010...0, where the single 1 is in the i-th position counting from the right (rightmost being position 0)
& is the “bitwise and operator”, where any_bit & 0 is zero and any_bit & 1 is any_bit
val & (1 << i) is 0...0(i-th bit of val)0...0 in binary, where the i-th bit of val is in the i-th position of the result
!! is a double negation: it converts zero to zero and any non-zero value to one
!!(val & (1 << i)) is either 0 or 1, and is exactly the i-th bit of val


ACS712 Not working correctly with Arduino So I have the basic setup ready with one relay that is controlling a 200W bulb. The Phase of this bulb is passed through a current sensor acs712. While running a simple analog read example sketch, I get output 511 from ADC, which is as expected. Then I subtracted this 511 from my measurement and observed the results while turning on/off the bulb.

int sensorValue;

void setup()
{
  Serial.begin(9600);  // sets the serial port to 9600
}

void loop()
{
  sensorValue = analogRead(0);       // read analog input pin 0
  Serial.println((511-sensorValue), DEC);  // prints the value read
  delay(100);                        // wait 100ms for next reading
}

Here is the output graph;

While the bulb is off, the current remains 0, but when I turn on the bulb, the voltage fluctuates over positive and negative side. Why is the sensor showing this behavior ?, I am not using any additional capacitor for noise reduction. Do I need to ? but I guess this is not noise. Is it ?

You are seeing that because that is what the current is doing. It's called AC - Alternating Current. It's what the mains current is.

To work with AC you have to rapidly sample over a short period to get the maximum and minimum values. Subtract one from the other and that gives you the peak-to-peak current. You can then use that to calculate the RMS current which is what you are (most likely) interested in.

http://whatis.techtarget.com/definition/root-mean-square-RMS


Getting "avrdude:stk500_recv(): programmer is not responding" while uploading sketch to Arduino Pro Mini I recently bought an Arduino Pro Mini(3.3V 328p, 8MHz) along with a CP2102 USB to TTL UART convertor. When I try to upload a sketch to the Pro Mini using it, I get a avrdude:stk500_recv(): programmer is not responding error. My connection was like

Arduino pro mini                CP2102
TXO  ----------------------------> TXD
RXI  ----------------------------> RXD
VCC  ----------------------------> 3V3
GND  ----------------------------> GND
DTR  ----------------------------> DTR

I tried inter-connecting the TXO and RXI pins and had no luck. Also pressing and releasing the reset button on the Pro Mini doesn't seem to work either.  I also tried programming it with my Arduino Uno, by removing the 328 and connecting correspondingly. Still no use.

Does any one have any ideas?

rx -> tx
tx -> rx

Please check your connections.


HMAC SHA256 in Arduino use case? I am doing a school project and wanted to implement HMAC on a arduino UNO like board. I have been testing the Cryptosuite, but none of the examples work for me. Such as this one: https://github.com/Cathedrow/Cryptosuite/blob/master/Sha/examples/hmacsha256test/hmacsha256test.pde

This one https://github.com/simonratner/Arduino-SHA-256, a trimmed-down version, which sounds good but there's none working example.

Can any one point me to the right direction? Thanks a lot!!

When you are asking a question, here or on a forum, then please tell what you did and what the result was. When you say that it is not working, then we have not enough information and your question might not get answered.

I have tested the first link that you gave to Cryptosuite. It is outdated and needs to be fixed.
I renamed "hmacsha256test.pde" to "hmacsha256test.ino".
The compiler errors and warnings are in the lower part of the Arduino IDE. Scroll up to find the first problem and fix that. Repeat it until it works.

The PROGMEM requires that the 'const' keyword is used. For example in "sha256.cpp":

const uint32_t sha256K[] PROGMEM = {

The 'write' function should return a size_t value.

In sha256.h:

// virtual void write(uint8_t);
virtual size_t write(uint8_t);

In sha256.cpp:

size_t Sha256Class::write(uint8_t data) {
  ++byteCount;
  addUncounted(data);
  return 1;
}

Then it compiles and runs on a Arduino Uno, although there is a warning for low memory because 75% of the sram is used.

The second link is a changed version of the same Cryptosuite. It should be able to use the examples of the Cryptosuite, but it does not.
I can make that work as well.

Using the same example of the Cryptosuite "hmacsha256test.pde" (I renamed it to "hmacsha256test.ino"), create a object 'sha' after including the "sha256.h":

#include "sha256.h"
Sha256 sha;

In the example, replace all "Sha256" function calls with "sha" function calls:

sha.initHmac(hmacKey1,20);
sha.print("Hi There");

Then it works as well.


Arduino - Playing WAV files with a buzzer I have developed an Arduino program that plays a WAV file from the SD card using a speaker.

This is the circuit schematic

The sketch I'm using is based on TMRpcm library and PWM output

#include <TMRpcm.h>
#include <SD.h>
#include <SPI.h>
int sdpin=10;
TMRpcm tmrpcm;

void setup()
{
    Serial.begin(9600);
    pinMode(sdpin, OUTPUT);
    tmrpcm.speakerPin=9;
    tmrpcm.setVolume(3);
    SD.begin();
}

void loop()
{
    if(Serial.available()>0)
    {
        String data=Serial.readString();
        if(data=="pause")
        {
            if(tmrpcm.isPlaying()==1)
            {
                tmrpcm.pause();
            }
        }
        else if(data=="stop")
        {
            if(tmrpcm.isPlaying()==1)
            {
                tmrpcm.stopPlayback();
            }
        }
        else
        {
            String path="/Music/"+data;
            if(tmrpcm.isPlaying()==1)
            {
                tmrpcm.stopPlayback();
            }
            tmrpcm.play(path.c_str());
        }
    }
}

At first I could play the music with the speaker but then it stopped working and because I don't have enough skill to make one myself, I would like to know if I can use a buzzer for that.

I know that buzzers can be used to generate melody using the tone() function but I'm not sure if I can use them to play wav files using PWM output.

Any help will be appreciated.

When driving a passive buzzer, you should always have the signal output from the Arduino go to a transistor tied between the ground and the (-) negative side of the buzzer. Also, if you use a regular NPN transistor, you should also have a small resistor between the Arduino and the transistor base.

The transistor is providing two functions; it's potentially amplifying the signal (if the (+) positive side of the buzzer is at a higher voltage than the Arduino) and it's also isolating (partially) that voltage from the Arduino. This helps save pins!
The resistor is to limit the current going through the transistor and helps keep both your Arduino and the transistor healthy. Voltage thrills, current kills and resistors limit current. If you use a MOSFET you want to change this from a low-ohm series resistor to a high-ohm pull-down resistor -- 4.75K or 10K is fine. A MOSFET is much higher impedance than an NPN transistor and should not be left floating.
Additionally, you want to add a diode between the (+) and (-) terminals on the buzzer. This may be the most important part of the circuit! When oscillating, the buzzer (whether magnetic or piezo) acts like an inductor and will accumulate a charge over time. This will be heard as a slowly diminishing volume from the buzzer. This charge will eventually overcome the protection diodes built into the GPIO pin (or any transistor) and destroy it! The diode blocks that charge loop and saves your chips.


FastLED - How to Control specific LEDs I am fearly new to Arduino and FastLED. I found a nice Sketch which fits almost perfectly to my needs.

Just one Problem:

I dont want the Sketch to effect ALL LEDs in one color.
I want some LEDs in Red (ex. LEDs 0-4) Some in green and others in blue.

They could all have the same effect and timing, but it would be really neat if I could make them out of sync a little bit.

But having the possibility to make different LEDs different colored would be great. Here is the "Pulse" or "Breath" Sketch I want to use.

    #include <FastLED.h>

    #define NUM_LEDS 37
    #define DATA_PIN 11
    #define CLK_PIN 13

    CRGB leds[NUM_LEDS];

    int fadeAmount = 5;  // Set the amount to fade I usually do 5, 10, 15, 20, 25 etc even up to 255.
    int brightness = 0;

    void setup()
    {
      FastLED.addLeds<APA102, DATA_PIN, CLK_PIN, BGR>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
      FastLED.setBrightness(50);
    }

    void loop()
    {
       for(int i = 0; i < NUM_LEDS; i++ )
       {
       leds[i].setRGB(0,255,250);  // Set Color HERE!!!
       leds[i].fadeLightBy(brightness);
      }
      FastLED.show();
      brightness = brightness + fadeAmount;
      // reverse the direction of the fading at the ends of the fade:
      if(brightness == 0 || brightness == 255)
      {
        fadeAmount = -fadeAmount ;
      }
      delay(80);  // This delay sets speed of the fade. I usually do from 5-75 but you can always go higher.
    }

The colors of the LEDs in your sketch are set in this loop:

for(int i = 0; i < NUM_LEDS; i++ )
{
    leds[i].setRGB(0,255,250);  // Set Color HERE!!!
    leds[i].fadeLightBy(brightness);
}

You loop over all LEDs and set them to a specific color and brightness. The changes will be send to the LEDs, when you call FastLED.show() afterwards. There is nobody, that prevents you from setting a different color for each LED or to only chnage the value for some of the LEDs.

For example, to light the first 5 LEDs in red, the next 10 in green and leaving the rest as they were before, you can use this code (Just exchange it with your for loop):

for(int i=0;i<5;i++){
    leds[i].setRGB(255,0,0);
    leds[i].fadeLightBy(brightness);
}
for(int i=5;i<15;i++){
    leds[i].setRGB(0,255,0);
    leds[i].fadeLightBy(brightness);
}
FastLED.show();

The principle is, that you have an array with color values. Each value consists of 3 smaller values for red, green and blue (RGB)(The color results from the distribution between red, green and blue; the brightness results from the overall level of red, green and blue). And each value of the array is bound to an LED (First value to first LED, second value to second LED,...). You can change the color values in the array as you like. And when you want the LEDs to show the current values in the array, you send them out by using FastLED.show(). This means you have to call this function everytime, that you want LEDs to change. You don't have to change every value in the array for this to work.

If you would like to build an asynchronous change of colors, you can ditch the delay(80) and use non-blocking code like in the BlinkWithoutDelay example of the Arduino IDE. There you use the millis() function as a clock (it returns the milliseconds since the Arduinos startup). You take a timestamp at the beginning and compare the difference between it and the current time:

unsigned long timestamp=0;
unsigned long interval=80; //interval of 80 milliseconds

void loop(){
    unsigned long current_time=millis();
    if(current_time - timestamp > interval){
        // do something here, like setting LED colors
        timestamp = current_time;
        // don't forget FastLED.show(), to output the colors
    }
}

You can use multiple of these timestamps with if-statements, one for each segment you want to change in a different frequency.


Two devices on one SDA input I have two devices. Sensor for temperature and humidity and lcd screen. Both require SDA pin, and I have only one on my arduino.

I want my display to show current temperature but I don't know how to connect two things on one pin.

Can I somehow read from other pins maybe?

Also, what can I do if I have only 1 5V source and I have two devices that require 5V?

My arduino model is Arduino Mega 2560 R3

I have this aosong sensor (AM2301), and I have YwRobots 2 row LCD screen which I want to connect to my board along with sensor.

So... I'm not sure how to connect those two if both require SDA and I have only one.

You can have multiple I2C devices on the same bus (sharing both SDA and SCL), as long as they have different addresses. The library used to access them should know (or be told, if required) what the address for the device is.

If they are not I2C devices then they cannot both use SDA.

The Aosong device is not an I2C device, but there is no need to connect its "SDA" pin to the Arduino's "SDA" pin; any unused digital pin should work, as long as the library is told which pin to find it on and as long as the electrical requirements of the connection are met.


mcufriend 2.4 TFT with ESP8266 I have this TFT:

Now, the problem is, I will not use this as a shield (i.e. I will not just put it on top of an Arduino Uno). I will use it with an ESP8266 (NodeMCU). I want to know how to wire them up together. There is this website (and a few more that say the same way). But the problem is I cannot find SDI/MOSI or SDD/MISO on the TFT above.

You have an 8-bit parallel interface TFT display. It requires 13 GPIO pins - D0-D7 plus reset, chip select, read, write and register select. You can forego the "read" signal and tie it high to save a pin. You can probably do the same with the reset signal, meaning you need a minimum of 11 pins.

I am not sure the NodeMCU has that many available, does it? (maybe it does, I don't have one to hand right now), so you may want to try getting it going with an SPI or I2C IO expander (though slowly).

And then of course you have to find the right library for the chip on the display (there's a few it could be - I have seen at least 3 different ones on the same, or similar, carrier PCB) that works with the NodeMCU.


Measuring Battery level with ADC already in use I have NodeMCU v3 with ESP8266 and I am running small project where I am measuring the input from IR phototransistor via ADC pin (A0) and everything is working flawlessly.
But now I want to transfer it to battery source (powerbank -> microUSB) and I want to be able to tell the remaining battery capacity, but all tutorials I found were going through switching ADC(A0) to internal, thus disabling it.
Is there any other way I can either measure the battery OR input from phototransistor?
Thanks!

As @dandavis rightly says in the comments, you can't measure the battery voltage from a power bank.  This is because the power bank typically includes a step-up converter to turn the batter voltage (3.2 to 4V) into a stable 5V.  That 5V will alwaye be 5V (or thereabouts) until the battery runs out and the power bank shuts itself off.

To measure the battery state you will have to directly interface with the batteries (disassemble the power bank) and tap into the battery terminals themselves.

Some power banks also have LEDs in them to display the power remaining. It could be possible to interface directly with these as well.

One thing to note, though, is that using a power bank for an ESP8266 board is pretty silly.  You are taking nominal 3.6V, stepping it up to 5V, then linearly dropping it back down to 3.3V again.  Both stages involve power wastage - the 5V to 3.3V most of all (a linear regulator turns the waste voltage into heat).

You would be better removing the batteries from the power bank and wiring them directly to the power input - or better still, feed them through a high efficiency switching regulator to get a stable 3.3V and feed that directly into the 3.3V pin.  be sure to include some way of monitoring the battery voltage and shutting off the power when it gets too low. Since your ADC input is already in use the simplest way is to add an external ADC chip to your design.


How to override automatic control in Blynk app? I am a beginner to Blynk, and have successfully built a simple water temperature control project. It consists of ESP32, a plug-in water heater, and an AC relay board. The ESP32 controls the relay board, while the water heater is plugged into the relay board.
The code I have will turn on the relay once the water temperature dips below 16C. On the Blynk app, I want to add a button that allows the user to manually control the operation of the relay. But I am stumped as to how to code it. Since I have programmed the ESP to turn off the relay once the temperature is above 16C, if I try to switch it on manually at 20C, for example, the relay will not remain on, because IF statement will fail.
How can I code this to have a manual override capability? So that once the user turns on the button inside the Blynk app, the ESP will allow manual control of the digital pin (delay trigger), and will only revert back to automatic temperature control mode once the button is turned off?
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <OneWire.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 14        //data wire connected to pin 14
#define RELAY_PIN 23           //IoT relay connected to pin 23

OneWire oneWire(ONE_WIRE_BUS); //instance to communicate with any OneWire device

DallasTemperature sensor(&oneWire); //pass reference to Dallas Temperature object

BlynkTimer timer;       //create Blynk timer object for timed intervals
float waterTemp;        //temperature from DS18B20 in C

char auth[] = "xxxxxxx";
char ssid[] = "xxxxxxx";
char pass[] = "xxxxxxx";

void setup() {
  Serial.begin(9600);
  sensor.begin();
  Blynk.begin(auth, ssid, pass);
  sensor.setResolution(9);           //default is 9 bit
  timer.setInterval(1000L, sendTemp);
  pinMode(RELAY_PIN, OUTPUT);
  digitalWrite(RELAY_PIN, LOW);
}

void sendTemp() {
  sensor.requestTemperatures();      //must request reading first
  waterTemp = sensor.getTempCByIndex(0);
  if (waterTemp != DEVICE_DISCONNECTED_C) {
    Serial.print("Temp = ");
    Serial.println(waterTemp);
    Blynk.virtualWrite(V1, waterTemp);
    if (waterTemp < 16) {
      digitalWrite(RELAY_PIN, HIGH); //turn on IoT relay
    } else {
      digitalWrite(RELAY_PIN, LOW);  //turn off IoT relay
    }
  } else {
    Serial.println("Error: Could not read temperature data");
    Blynk.notify("Error: Could not read temperature data");
    digitalWrite(RELAY_PIN, LOW);
  }
}

void loop(void) {
  Blynk.run();
  timer.run();
}

Roughly like this:
Make a global variable int mode;
Read a Blynk app 3-way switch in the loop();
Set mode to the 1, 2 or 3 received from the Blynk app (for ON/OFF/AUTO);
Replace this bit of code:
if (waterTemp < 16) {
  digitalWrite(RELAY_PIN, HIGH); //turn on IoT relay
} else {
  digitalWrite(RELAY_PIN, LOW);  //turn off IoT relay
}

with
if (mode == 1) {
  digitalWrite(RELAY_PIN, HIGH);
} else if (mode = 2) {
  digitalWrite(RELAY_PIN, LOW);
} else {
  if (waterTemp < 16) {
    digitalWrite(RELAY_PIN, HIGH); //turn on IoT relay
  } else {
    digitalWrite(RELAY_PIN, LOW);  //turn off IoT relay
  }
}

You will still have to decide what happens when DEVICE_DISCONNECTED_C == TRUE, etc, but that is the gist of it.


Trying to individually control the servos in my robot using keyboard input #include<Servo.h>
Servo ser1;
Servo ser2;
Servo ser3;
Servo ser4;
Servo ser5;
int poser = 0;
int val;
int mot;

void setup() {
  Serial.begin(9600);
  ser1.attach(4);
  ser2.attach(5);
  ser3.attach(6);
  ser4.attach(7);
  ser5.attach(8);
}

void loop() {
    Serial.print("Choose the motor");
      mot=Serial.read();
      switch(mot)
      {
        case 1:
        {
            val = Serial.read();
            if (val == 'd')
             {
                poser += 1;
                ser1.write(poser);
               delay(15);
             }
           if (val == 'a')
             {
                poser -= 1;
                ser1.write(poser);
                delay(15);
             }
           break;
         }
       case 2:
         {
           val = Serial.read();
           if (val == 'd')
            {
               poser += 1;
               ser2.write(poser);
               delay(15);
            }
           if (val == 'a')
            {
               poser -= 1;
               ser2.write(poser);
               delay(15);
            }
           break;
         }
      case 3:
         {
           val = Serial.read();
           if (val == 'd')
            {
              poser += 1;
              ser3.write(poser);
              delay(15);
            }
          if (val == 'a')
            {
              poser -= 1;
              ser3.write(poser);
              delay(15);
            }
          break;
         }
       case 4:
         {
            val = Serial.read();
            if (val == 'd')
             {
                poser += 1;
                ser4.write(poser);
                delay(15);
             }
           if (val == 'a')
             {
                poser -= 1;
                ser4.write(poser);
                delay(15);
             }
           break;
         }
       case 5:
         {
           val = Serial.read();
           if (val == 'd')
             {
                poser += 1;
                ser4.write(poser);
                delay(15);
             }
           if (val == 'a')
             {
                poser -= 1;
                ser4.write(poser);
                delay(15);
             }
           break;
          }
      default:
          {
              Serial.print("Type valid number");
              break;
          }
    }
  }

The code just shows "Choose the motor type valid number" repeatedly and the arm contorts as soon as I upload it. Can someone please check the code and tell me what could've gone wrong?

I would suggest you to add these line in your code.

while(!Serial.available()){;} before mot = Serial.read();

This will hold you logic till any input received from Serial.

Same you add before val = Serial.read();.


How to properly link an Arduino and its sensors To finalize a prototype, I would like to have a proper structure containing the arduino (uno here), its shields and its sensors. I would like the sensors to be soldered to the arduino+shields block, but the sensors were sold on a small separate PCB (example).

What is the recommended method to have a strong, clean link between the two ?

You could solder those modules to a prototype shield.  If you replace the header with a right-angle one (or even just bend the pins on the existing one) you could even mount it vertically to save space.

Prototype shield:

Right-angled headers:


Shift between the carrier frequency of the signal transmitted with arduino and my garage door RC (433 mhz) I have this 433 mhz transmitter and receiver for arduino.

I want to replay my garage door remote control with this transmitter so I reversed the RC (remote control) signal with RTL-SDR/sdrsharp and audacity.
It is not working.

Why is there a shift between the carrier frequency of the signal transmitted with arduino (RH_ASK library) and my garage door RC ?
How can I change this ?

The reason is that your garage door opening is operating on a different carrier frequency than your transmitter module.  The plot you are showing is called a "waterfall" plot and shows the frequency on the "x" axis with time progressing from top-to-bottom.
The garage door remote appears to be centered just above 433.900 MHz while your transmitter is around 434.000 MHz.  While that might not seem like a large difference, these things are designed to be receptive in a very narrow band.
So you need to read the specifications of your transmitter module and see if its frequency is adjustable and, if so, adjust it upward to the correct frequency.


Non-blocking strobing code? I'm trying to figure out how to create some non-blocking code to strobe some RGB leds with analogwrite  7 times a second; I'm really not to sure how to go about this. If anybody could give me some help that'd be great! :)

What you want can be achieved with your MCUs timers and their associated interrupts. Timers are basically counters that run inside your hardware and they run decoupled from your code. Since one usually knows how fast these timers tick (e.g. how long it takes to count from one to two and so on) you can specify events that happen when a certain amount of timer ticks passed.

I suggest you have a look at SimpleTimer and Timer1 (the second page is only for ATmega168/328)

Both pages include some code samples where they specify some method that will be called every x milliseconds.


Use ESP-01 with Arduino Uno/Nano, with the ESP8266WiFi library There is this library - https://github.com/esp8266/Arduino
That provides a more user-friendly API for WiFi capabilities with the ESP8266.

However, all tutorials that I found so far for this library show how to program the ESP8266 (usually 12) directly. That is not what I'm looking for.

My current setup is having an Arduino Uno/Nano where the ESP8266 is connected to, say, GPIO8 and GPIO9 (RX, TX) and I use SoftwareSerial to communicate with it with AT commands. So I want to keep all the logic in my Arduino, but use ESP-01 only to provide WiFi capabilities to my Arduino.

However in that library I don't see the option to set the serial port pins (RX and TX) so I'm not sure if that's even possible.

In short - I want to use this library, but not program the ESP directly. Also, I'm using an ESP-01 and not 12.

Thanks.

You cannot use that "library". Simply because that isn't a library, that is a core. It's the entirety of the Arduino API designed to run on an ESP8266.

You can use it to program the ESP8266 directly and nothing else. No part of that has anything at all to do with Arduino boards like the Uno.


Can I compile c/c++ code on the linux part of the Arduino Yun? Can I compile c/c++ code on the linux part of the Arduino Yun?

How complete is the linux part of the Arduino Yun?
Can I scp some c/c++ code onto the Atheros AR9331 chip compile it?

Or must I first crosscompile all software and then put them onto the Atheros?

The Yun's OS (Linino) is based on OpenWRT, and the official toolchain from OpenWRT does not appear to have changed much. It could probably be done, the question is if you'd really want to though.

The limited resources (storage, RAM, CPU) means you would most likely not fit all the parts of the toolchain for C/C++ compilation (perhaps with the exception of very basic programs without many dependencies). The YUN's package manager (opkg) should contain pre-built packackes if they exist, but given that even the list of packages is only kept in RAM to conserve space, I doubt the entire toolchain with libraries needed to compile useful stuff would fit.

The official way to build things for OpenWRT appears to be cross-compilation on a much beefier machine, if only because it takes a fraction of the time needed by a native compiler. All in all, you're also very likely to save time and resources by cross-compiling and have more resources left on the YUN itself.


HCSR04 Sensor without delay I've made a code to make a stepper work together with a HCSR04 sensor. The problem here is that the sensor has to use a delay in order to work. This delay messes with the smootness of the stepper.

If I remove the code for the sensor the stepper runs verry smooth, adding the sensor code causes the stepper to run 'shaky'.

The code:

int trigPin = 11;
int echoPin = 10;

void setup()
{
pinMode(trigPin, OUTPUT); //Sensor
pinMode(echoPin, INPUT); //Sensor
pinMode(6,OUTPUT); // Enable
pinMode(13,OUTPUT); // Step
pinMode(12,OUTPUT); // Dir
digitalWrite(6,LOW); // Set Enable low
digitalWrite(5,LOW); // Set Step low
Serial.begin(9600);
}

void loop()
{
//rotateleft();
//Serial.println("ik draai nu exact een rotatie linksom");
//delay(1000);
//rotateright();
//Serial.println("ik draai nu exact een rotatie rechtsom");
//delay(1000);
//velocity();

 //sensor
 long duration, distance;
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2); //**problem**
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(5); //**problem**
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 distance = (duration/2) / 29.1;
 Serial.print ("cm:");
 Serial.print (distance);

//eigen creatie
if (distance > 20 && distance < 30)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(1000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(1000); // Wait
}

if (distance > 10 && distance < 20)
{
  digitalWrite(13,HIGH); // Output high
  delayMicroseconds(3000); // Wait
  digitalWrite(13,LOW); // Output low
  delayMicroseconds(3000); // Wait
}

if (distance > 1 && distance < 10)
{
  //digitalWrite(13,HIGH); // Output high
  //delayMicroseconds(1000); // Wait
  digitalWrite(13,LOW); // Output low
}

else
{
 velocity();
}

}

void velocity()
{
 digitalWrite(13,HIGH); // Output high
 delayMicroseconds(500); // Wait
 digitalWrite(13,LOW); // Output low
 delayMicroseconds(500); // Wait
}
 }

Have you searched for other libraries or example code for this particular sensor?

I found this NewPing library that claims to have been developed to fix poor performance of such modules due to poor timing methods.


Forbidden characters in TCP/IP I'm trying to send data from my ESP8266 to a NodeJS TCP server, the connection and basic charakters (48-90) are working fine, but if I use others like ASCII-Code (0,1,2,3...)  I don't get any usefull data out of it. So what I was thinking about that there are some character which aren't allowed to send over TCP/IP.

By the way,
I'm using this to write to the server, and I work with the standard WiFi Client library

char arr[255]
for(int i = 0; i < 255; i++){
   arr[i] = (char)i;
}
client.print(arr);

Nodejs File:

// Load the TCP Library
net = require('net');

var mysql = require('mysql');

// Keep track of the chat clients
var clients = [];
var uploadCounter = 0;

initMySQLConnection();

// Start a TCP Server
net.createServer(function (socket) {

    // Identify this client
    socket.name = socket.remoteAddress + ":" + socket.remotePort

    // Put this new client in the list
    clients.push(socket);

    // Send a nice welcome message and announce
    socket.write("Welcome " + socket.name + "\n");
    broadcast(socket.name + " connected\n", socket);

    // Handle incoming messages from clients.
    socket.on('data', function (data) {
        broadcast(">> " + data, socket);

        uploadData(data);
    });

    // Remove the client from the list when it leaves
    socket.on('end', function () {
        clients.splice(clients.indexOf(socket), 1);
        broadcast(socket.name + " disconnected.\n\n");
    });

    // Send a message to all clients
    function broadcast(message, sender) {
        clients.forEach(function (client) {
            // Don't want to send it to sender
            if (client === sender) return;
            //client.write(message);
        });
        // Log it to the server output too
        process.stdout.write(message)
    }

}).listen(10101);

// Put a friendly message on the terminal of the server.
console.log("Chat server running at port 10101\n");

var connection;
function initMySQLConnection() {
    connection = mysql.createConnection({
        host: "host",
        user: "user",
        password: "pass",
        database: "database"
    });

    connection.connect(function (err) {
        if (err) {
            console.log('error when connecting to db:', err);
        }
    });

    connection.on('error', function (err) {
        console.log('db error', err);
        if (err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
                                    // lost due to either server restart, or a
        } else {                                      // connnection idle timeout (the wait_timeout
            throw err;                                  // server variable configures this)
        }
    });

    setInterval(function () {
        connection.query('SELECT 1');
    }, 60000);
}

function uploadData(data) {
    data = String(data);

    console.log("Package Length: " + data.length);
    console.log("GOT ASCII CODE: ");
    for (var i = 0; i < 255; i++) {
        console.log(data.charCodeAt(i));
    }

    //upload Code
}

The print function takes an array of characters as zero terminated c-string. It prints until a byte with value 0. You have zero at arr[0] so it is an empty string.

To send bytes, write function is used. The print functions convert parameters to text or expect text as zero terminated char array.

In your case it should be client.write(arr, length); where length is the number of bytes you want to send from the buffer arr.


Trying to flash ESP8266 with Arduino UNO This is my first project other than some of the starter projects. I am trying to flash the firmware onto an ESP8266 wifi module using and arduino uno. It would be nice to know if anything is wrong/redundant in the picture below (I was looking at a few different diagrams to try and figure out what was right). I have found some tutorials saying that TX should go to RX instead of TX to TX so that is what I am doing. I am trying to use the level shifter to go from 5v to 3.3v because I wasn't sure if I had enough current going to the ESP8266 when just directly hooked up to 3.3v on arduino (I read in a few places that the arduino doesn't have a strong enough current to operate the wifi module). I found some tutorials which use a voltage regulator, I tried doing that but had the same results I am getting now. I have also read that you don't need a level shifter or voltage regulator but it might harm the components so I haven't tried that way yet.

I am the point where I plug it into my computer via USB, open the Arduino IDE > Tools > Serial Monitor.

I type the command 'AT' and there is no response - I tried every baud setting. Sometimes it randomly outputs a question mark or two.

Other things of note: When I plug it in, the ESP8266 blue light flashes once. When I was modding the header pins of the ESP8266 I kind of fumbled it a lot - could that have broken some aspect of the chip? Also while modding the header pins, I pushed them all in to make them longer and bent them on the other side, so it would work with the breadboard - I'm wondering if the soldering connections need to be stronger (you can kind of see in the picture).

This is the schematic for what I was trying to achieve basically, while also using the level shifter:

Any advice with regards to anything you see here would be great, I am new to the world of circuits.

Note: there is a ground wire that is not in the frame of the picture connecting one side of the breadboard to the other, that part of this is one thing I was wondering about.

You do not need the level shifter. The input pins of the ESP8266 contain over-voltage (though not over-current) protection. All you need to do is limit the current that can flow through the over-voltage protection circuit, and all that needs is a series resistor in the region of 100Ω or so.

And the Arduino already has that protection between the ATMega16U2 and the TX/RX pins anyway in the form of 100Ω resistors that it uses to prevent short circuits between the two MCUs on the board, so you don't need to add it in this instance (you do if you want to communicate between the ATMega328P and the ESP8266, but only between the Arduino's TX and the ESP8266's RX pins).

When it comes to actively running the ESP8266 it can be beneficial to power it from a more powerful 3.3V regulator than the 150mA one on the Arduino since when transmitting the ESP8266 wants more than that, but for simple flashing of it the Arduino's 150mA regulator should do the job fine.

One thing to note though: I don't like the look of the soldering on your ESP8266 pins. I would be inclined to re-solder those joints. Add a bit of flux to help the solder flow properly.


Connecting to Alexa with FAUXMOESP library not detecting the device I am using NodeMCU (ESP8266 12E) module from some days. I am trying to connect to Alexa for voice controlling. I have Amazon Alexa Echo 2 from which I am trying to discover my nodemcu as a smart home device.

Here is my sketch I am trying to use to detect.

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <fauxmoESP.h>

fauxmoESP fauxmo;

const char* ssid = "myssid";
const char* password = "mypassword";

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

  fauxmo.enable(true);

  fauxmo.addDevice("light one");
  fauxmo.addDevice("light two");

// this is not able to detect .onSetState function I am not sure about the reason.

//  fauxmo.onSetState([](unsigned char device_id, const char * device_name, bool state, unsigned char value) {
//        Serial.printf("[MAIN] Device #%d (%s) state: %s value: %d\n", device_id, device_name, state ? "ON" : "OFF", value);
//    });
}

void loop() {
    fauxmo.handle();

}

void wifisetup() {
  pinMode(2, OUTPUT);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  IPAddress ip(192, 168, 1, 243); // this 3 lines for a fix IP-address
  IPAddress gateway(192, 168, 1, 1);
  IPAddress subnet(255, 255, 255, 0);
  IPAddress dns(192, 168, 1, 1);
  WiFi.config(ip, dns, gateway, subnet);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(10000);
    digitalWrite(2, HIGH);
    ESP.restart();
  }
  if (WiFi.status() == WL_CONNECTED) {
    digitalWrite(2, LOW);
    Serial.println("");
    Serial.println("Your ESP is connected!");
    Serial.println("Your IP address is: ");
    Serial.println(WiFi.localIP());

    delay(100);
  }

}

I am using https://bitbucket.org/xoseperez/fauxmoesp library to do the setup. Alexa is not able to detect my device. Not sure whats the issue with this, but in the Serial Monitor I can see the logs which is showing that I am getting ping from Alexa to my ESP8266.

Taking an output pin is compulsory? I have tried that too although but no output found.

Thank you!

If you are using fauxmoESP library version 3.0 and above your device will not be detected by alexa, i dont know why this is.
You may degrade fauxmoESp version to 2.4.0 so that your issue ie. .onSetState will be resolved.

Are you able to connect wifi?


yellow LED not turning off in traffic light simulation I wanted to make a simulation of a traffic light, and since I don't have any sensors I used a button to change between the different states (red/stop and green/drive). When the states are changing I wanted to have a short yellow blink-
 just like normal traffic lights work. But in the first state(green), yellow doesn't turn off. In the second the same problem occurs, but if I press the button, that I connected to GPIO pin 2, the LED turns off. It makes no sense to me, as the switch sentence turn off the yellow LED before powering the others (in both cases). In addition, I can't wrap my head around the fact that the yellow LED turns off after I press the button once more, as I only have two cases in the switch sentence, but it now seems like there is three.

void loop() {
// Turn the green led on (GPIO PIN 11) if button pressed once. If button is pressed again switch to yellow then to red.

if(switchLedBtn.pressed()) {
colour = colour + 1;
if(colour > 3) {
  colour = 1;
 }
}

switch(colour) {

// Turn off red, turn on yellow in half a second, then power green (green(0), yellow(1) and red(2))
case 1: digitalWrite(ledPins[2], LOW); digitalWrite(ledPins[1], HIGH); delay(500); digitalWrite(ledPins[1], LOW); digitalWrite(ledPins[0], HIGH);
        break;

// Turn green off, turn yellow on for a second, then power red
case 2: digitalWrite(ledPins[0], LOW); digitalWrite(ledPins[1], HIGH); delay(1000); digitalWrite(ledPins[1], LOW); digitalWrite(ledPins[2], HIGH);
        break;

Your program runs in a tight loop - an extremely tight one which does all but nothing in any state but 1 or 2.  However what happens in these states is interesting.

Essentially what you have is

Quickly check for input - which won't be detected unless the bottom is being held down at this precise narrow slice of time between long delays
Turn on an LED, apparently from your comment the yellow one
Change the LEDs but recycle so quickly that this fact is generally invisible.

The result of this is that instead of a brief pulse of yellow, you will be seeing near constant yellow, because that is the only part of your loop which takes any time.

Probably what you want to do is to advance the state when you are done with your brief yellow flash.  But it's not possible to say what you should advance the state to, since it's unclear how you want this light to work.  If it is purely timer-based, then you don't need any input at all; while if the button is supposed to do something but a timer should also be used, then you have a more complicated problem.

Essentially, before you can write any code you must write in words or diagrams a comprehensive set of "rules" for what the system is supposed to do.


Write a Struct using ArduinoBLE library Hello I'm trying to send some Structs such as:
typedef struct __attribute__ ((__packed__)) myohw_command_set_mode {
    myohw_command_header_t header; ///< command == myohw_command_set_mode. payload_size = 3.
    uint8_t emg_mode;              ///< EMG sensor mode. See myohw_emg_mode_t.
    uint8_t imu_mode;              ///< IMU mode. See myohw_imu_mode_t.
    uint8_t classifier_mode;       ///< Classifier mode. See myohw_classifier_mode_t.
} myohw_command_set_mode_t;

To another device via BLE using the Arduino BLE library.
I have the services and characteristics all set up correctly.
My problem is that arduino BLE .writeValue() function expects some specific formats and i'm not quite sure the best way to convert this struct to one of them.
  int writeValue(const uint8_t value[], int length);
  int writeValue(const void* value, int length);
  int writeValue(const char* value);
  int writeValue(uint8_t value);
  int writeValue(int8_t value);
  int writeValue(uint16_t value);
  int writeValue(int16_t value);
  int writeValue(uint32_t value);
  int writeValue(int32_t value);

What format should i use? And what is the best way to cast the Struct to the format?
Thanks,

What format should i use?

int writeValue(const uint8_t value[], int length);

And what is the best way to cast the Struct to the format?

writeValue((uint8_t *)&myStruct, sizeof(myStruct));


What difference between readString and while loop read From Arduino code, I have a question for SoftwareSerial Class

First: when I use more example for Esp8266 those functions use while loop to read response string from Esp when we send AT_Command to ESP.

getResponse(const uint32_t  wait) {
    String tmpData = "";
    long int time = millis();
    while ((time + wait) > millis()) {
        while (esp8266->available() > 0) {
            char c = esp8266->read();
            if (c == '\0') continue;
            tmpData += c;
        }
    }
    tmpData.trim();
    return tmpData;
}

I know that SoftwareSerial Class have a public method is readString() then I'm tried to use that and it return same result returned by while loop read:

getResponse(const uint32_t  wait) {
    String tmpData = "";
    tmpData = esp8266->readString();
    return tmpData;
}

Thanks for any. I'm working on improving my Eng.
Regards

Your while loop reads all the characters up until it reaches character 0 (it also has a timeout, although the timeout has been coded wrong since it can't deal with clock rollover). The .readString() method reads characters until no characters arrive within a timeout period (1s if memory serves me correctly).

Your while loop is the more reliable method since it uses a specific delimiter to identify blocks of data (strings) rather than assuming that:

The string will all arrive with no delays greater than the timeout
The strings will be sent with a gap of at least the timeout length between them.

Personally I would never recommend using any of the "helpful" functions provided for reading from a Stream object other than the basic .read() function.


'Keyboard' not found when trying to use Keyboard.write from the  library I am trying to get a response from the arduino when I press a key, but when I try to upload the code it says that it could not find 'Keyboard' with 'Keyboard.write'. Here is my code. Ignore the bits with servo stuff, that is for the project later on. I am using the arduino mega 2560.

  #include <Servo.h>
  #include <Keyboard.h>

Servo myservo;
Servo myservo2;

int pos = 0;
int pos2 = 0;
String comdata = "";
int lastLength = 0;

void setup() {
myservo.attach(12);
myservo2.attach(11);
Serial.begin(9600);
pinMode(2, INPUT_PULLUP);
Keyboard.begin();
}

void loop() {
if (Serial.available() > 0) {
 // read incoming serial data:
 char inChar = Serial.read();
 Keyboard.write(inChar + 1);
}

}

The Mega2560 can't be a keyboard. It lacks the required hardware.

Instead you need to use one of the pure USB boards, like the Leonardo.


the arduino software is looking for spi.h in a example code I'm having a problem in compiling the example ScanNetwork codes in arduino it brings up an error that states "SPI.h: No such file or directory." Now I added an SPI folder in the libraries but after verifying it shows another error. I did the same thing to others but the compiler is looking for more and more files. What can I do?
By the way, I'm using a Gizduino+ w/ ATmega644.

"SPI.h: No such file or directory." Now I added an SPI folder in the libraries but after verifying it shows another error. I did the same thing to others but the compiler is looking for more and more files. What can I do? By the way, I'm using a Gizduino+ w/ ATmega644.

Did you check the product web-page for the IDE patch. You must install the core for this Arduino clone. There might be some issues with which version of the IDE to use and what version of the library. Check the product web-page for more details.

Your question is too product specific and this is not that type of support page.

Cheers!


Is it possible to reprogram an atMega328 chip inside of a pcb? I have already soldered the atMega chip with instructions onto the perfboard, and I may need to make changes to it. Is it possible to reprogram it without taking it out of the PCB?

I'm assuming you're trying to program using an AVR programmer.

Yes, it's very likely you'll be able to do that. You need to connect the AVR programmer to the correct MCU pins (Sck, Si, So and Rst), including ground and vcc... as you would do with the chip by itself.

If you have any othe SPI device connected to the same pins, make sure it's not enabled - that might be as simple as having the device's CS pulled high.

The way you'll make the connection is up to you, you might need to use some clips, pogo pins or simply solder some wires to the MCU pins.

If you have other things connected to any of the MCU programming pins, you might need to disconnect, but that will vary case by case.

Cheers


Help compiling multiple .ino file code with code! (I'm not sure what to name this) Ok, so i'm trying to make This Project and the code comes all in different .ino files but in the video its all in one program. So how do I compile all of the code onto the arduino? (By the way the code is on step 5 in a .zip file) Thank you!

One of the .ino files is likely the main code file.  Name the enclosing folder with the name of the .ino file, then compile it as normal.

In this case, AbHhGD.ino is the main file, and its folder should be named 'AbHhGD'

The comments indicate there are missing libraries you likely need to install.


How to move a servo with a function Im currently moving a servo from one side to another by using the typical for loop like this:
int lightON = 180;
int lightOFF = 90;

if (buttonState == HIGH) {

  digitalWrite(LED, HIGH);
  for (pos1 = lightOFF; pos1 <= lightON; pos1 += 1) {
    servo1.write(pos1);
    delay(15);
  }
  digitalWrite(LED, LOW);

}

That would be moving the servo one way and if I push the button again the servo would move another way.
if (buttonState == LOW) {

  digitalWrite(LED, HIGH);
  for (pos1 = lightON; pos1 >= lightOFF; pos1 -= 1) {
    servo1.write(pos1);
    delay(15);
  }
  digitalWrite(LED, LOW);

}

The thing is, I have this very same code in 3 other servos and I don't want to be repeating the same code with 2 different variables (pos and servo) over and over again, so I tried
void runServoLight(int pos, int light1, int light2, Servo servo, int state) {

  if (state == 1) {

  digitalWrite(LED, HIGH);

  for (pos = light1; pos <= light2; pos += 1) {
     servo.write(pos);
     delay(15);
  }

  digitalWrite(LED, LOW);

  } else if (state == 0) {

  digitalWrite(LED, HIGH);

  for (pos = light2; pos >= light1; pos -= 1) {
    servo.write(pos);
    delay(15);
  }

  digitalWrite(LED, LOW);

  }

}

Now instead of running the whole for loop code I only run:
runServoLight(pos1, lightON, lightOFF, servo1, 1);

The problem is that it doesn't seem to work and I can understand why, I may be writing the function wrong but im nor really sure. I would really appreciate some help. Thank you!

You wrote:

void runServoLight(
        int pos, int light1, int light2, Servo servo, int state)

Here you are giving the list of parameters used by the function. In C++,
parameters are by default passed by value. This means that, when the
function is called, the arguments passed in the call are copied into
the parameters listed here, which are local variables of the function.
Changes to those parameters will not propagate to the arguments provided
by the caller.
This can be an issue for the Servo object. This object keeps some
internal state, which has the memory of the current configuration of the
timers. Since you are working on a copy of the provided object, the
original object is not updated when you act on the copy. I do not know
whether this is making your program misbehave, but it would be safer to
pass the Servo object by reference:
void runServoLight(
        int pos, int light1, int light2, Servo &servo, int state)

This way the object will not be copied: the function will instead work
on the original object provided by the caller.
The same may apply to the pos parameter. The very first thing the
function does with this parameter is to overwrite it. Then there is no
point in receiving that value from the caller. You can instead remove
the parameter and create a local variable with the same name:
void runServoLight(int light1, int light2, Servo &servo, int state) {
    int pos;  // local variable
    ...
}

If you want the caller's version of this variable to be updated, you
could pass it by reference, just like the Servo object. It is,
however, more efficient to keep the variable local and have the function
return the final position. The call would then look like:
pos1 = runServoLight(lightON, lightOFF, servo1, 1);

One final point that is not visible in the snippets you showed: are you
doing edge detection on the buttons? Edge detection means that you act
on the changes of state of the buttons, not on the states themselves.
For example, you move from lightOFF  to lightON not when the button
state is HIGH but rather when it turns HIGH.


WiFi101 Client HTTP POST fails after 3rd request I would really appreciate any help, my home project has been put on hold for weeks as I haven't been able to figure this out. In a nutshell, I'm connecting to my wifi network, measuring temperature from a sensor, and sending that temperature data to a server via a HTTP Request. All of that stuff works.

I have it in a loop, and on the 3rd HTTP request I get 'Connection Failed' when it's trying to client.connect(server, 80) - I don't understand why it fails. I've tried adding client.stop() and client.flush() after each HTTP request, but nothing fixes it. Below is my sketch file with some of the temperature code removed to make it easier to read

#include <SPI.h>
#include <WiFi101.h>
#include <string.h>
#include <stdlib.h>
#include <OneWire.h>
#include <DallasTemperature.h>

//WiFi Client Setup
char ssid[] = "HIDDEN";    //  your network SSID (name)
char pass[] = "HIDDEN";       // your network password
int status = WL_IDLE_STATUS;    // the WiFi radio's status
char server[] = "HIDDEN";
WiFiClient client;

// Setup for temperature sensor
#define ONE_WIRE_BUS A5
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
DeviceAddress insideThermometer;

void setup() {
  Serial.begin(9600);
  WiFi.setPins(8,2,A3,-1);
  while (!Serial) {
    Serial.println("Waiting for serial");
  }

  //Connect to wifi shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    while (true);
  }
  wifiConnect();
  sensors.begin();
}

void loop() {
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }
  /*
  Code to get temperature here
  */
  httpRequest(temp);
  delay(10000); // 5min
}

void httpRequest(String temp) {
  String request = "POST /api/webhooks/temp?temperature=" + temp + " HTTP/1.1";

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    Serial.println("connected to server");
    client.println(request);
    client.println("Authorization: Token HIDDEN");
    client.println("Host: HIDDEN");
    client.println("Connection: close");
    client.println();
  }
  else {
    Serial.println("Connection failed");
  }
}

void wifiConnect() {
  //Attempt to connect to WiFi network:
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);
    delay(1000);
  }

  Serial.println("You're connected to the network");
}

I tried changing the strings to char's, that didn't work.
Verified that it was closing connections with the server, check.

Was reading around and saw someone who tried a soft reset of the wifi client here. I added the following to the end of my httpRequest() method

client.stop();
WiFi.end();
delay(10);
WiFi.begin(ssid, pass);

And now it's working just fine. I'm going to have it run all night and see if there are any issues, but it's definitely an improvement as I can make more than 3 requests :|

This seems like a terrible work around. Clearly something isn't getting reset after each HTTP request on the wifi client, and this (right now) is the only way to solve it. I'd really love any other feedback on a better ways to solve it. Seems like some issues with the WiFi101 Library.


I cannot find the I2C device by scanning I've been trying to get a LCD I bought from deal extreme to work for some time with my ATTiny85 chip. It should be capable.
I've tried googling the device but there is no proper documentation, so I figured the best way to get the address is to scan for it. How ever, the code below does not work :( any pointers? Anyone else who has gotten this I2C LCD display to work with Arduino?

As I have no other output then the screen, the thought behind the code is to scan for devices and then when it finds one (the LCD is the only one connected to the bus) should then print the address :)

I only have a serial programmer and attiny85 chips, so I have no way to bring it to a full Arduino UNO or whatever for further debugging.

#include <TinyWireM.h>
#include <LiquidCrystal_I2C.h>

void setup()
{
  TinyWireM.begin();
}

void loop()
{
  byte error, address;

  for(address = 1; address < 127; address++ )
  {
    TinyWireM.beginTransmission(address);

    error = TinyWireM.endTransmission();

    if (error == 0) break;

    delay(5000);
  }

  LiquidCrystal_I2C lcd(address, 16, 2);

  lcd.init();
  lcd.backlight();
  lcd.clear();

  lcd.setCursor(0, 0);
  lcd.print("Hello World - " + address);
}

I2C LCD: http://www.dx.com/p/iic-i2c-2-5-blue-screen-lcd-display-module-for-arduino-green-black-266170#.U6f_B_l_vIc

I'm not sure on your program, but I bought a LCD display from Deal Extreme. I use the following address to communicate with the display:

LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27

It seems as that is the correct address for the LCD.


Using a L2938D Motor Driver Module. (Not IC, Module) I have been trying to use my newly bought L293d Motor Driver Module to run motors(a single motor in this test case, simple 5V toy motor) from my Arduino UNO. Thing is, this is an entire module, not just the IC (in which case there are many tutorials available). So I was following this tutorial to try and get my motor running.

Here is the tutorial - http://www.instructables.com/id/Arduino-and-L293D-Robot-Part-1-/?ALLSTEPS
Here's what the module looks like -

There are 6 Pins on the module, which bring out the 6 inputs, EN1, EN2, IN1, IN2, IN3, IN4. Now since I am using only one motor, I connected my motor to the OUTPUT 1 & 2 header given on the module. I then take the 5V and GND from Arduino and connect them to my Module's 5V and GND header, (leaving the 12V one empty), I thought that this would be enough as my motor is also of 5V.
I then connected the IN1 and IN2 to the pins 7 & 8 on my Arduino and used the following code-

// Simple code to make the motor turn
int RightMotorForward = 7;
int RightMotorReverse = 8;

void setup()
{
  pinMode(RightMotorForward, OUTPUT);
  pinMode(RightMotorReverse, OUTPUT);
}

void loop()

{
   digitalWrite(RightMotorForward, HIGH);
   delay(10000);

   digitalWrite(RightMotorForward,LOW);
   delay(1000);
}

Nothing happened. The motor didn't work and I have no idea why. I've gone through the entire datasheet for L293D but I found nothing that could help me. I suspect that it has something to do with the EN1 pin, but I don't really know how to use it, the tutorial said to connect it to 5V, which I tried but no results. So where am I making the mistake? How do I get this to work?

While no one can tell you exactly how to connect that board without having its documentation or the board in hand to examine visually or with an ohm-meter, it is quite likely that by leaving the "12v" terminal unconnected, no power is being provided to the motor side of the circuit.

It kind of looks like there is a voltage regulator on board, so it may be that it will even provide 5v on that terminal when given something 7 volts (or so) or higher on the "12v" terminal - again, we cannot know without details of your exact board.

The L293 is an old and low-performing chip, with internal losses that mean  that to achieve 5 volts across a motor, you will need to supply very nearly 7 volts to the chip.  The difference gets wasted as heat.


Arduino Uno not working as usb HID interface I have an arduino uno rev 3 and it works perfectly fine. I the OS I am using is Kali Linux 2.0 and you can upload everything as normal to the arduino.
I am following this tutorial:Arduino Uno as usb HID interface device
to use my arduino uno r3 as a hid device. After I upload the

Arduino-keyboard-0.3.hex

file, I plug cycle the board and I try uploading the example blink program. It always says:

Serial Port /dev/ttyACM0 not found.
Retry the upload with another serial port?
/dev/ttyS0

the /dev/ttyACM0 is my default arduino port and /dev/ttyS0 is one of my usb devices that is plugged in. Neverless, I tried uploading but it says board isnt responding. Can someone help me with this please?

You have reprogrammed the ATMega16U2 chip to be a HID device. Thus it no longer functions as a serial interface between the Atmega328P and your computer. You need to reflash the firmware on the ATMega16U2 to return to normal operation.
I have instructions for how you might to this on my bootloader uploader page. In brief, you need to put the original hex file back:
sudo dfu-programmer atmega16u2 flash Arduino-atmega16u2-Uno-firmware-Rev3.hex

There are other ways of turning your Uno into a HID device. Search for "Virtual USB Arduino".
More easily, get a Arduino Leonardo or Arduino Micro which are designed for this sort of thing.

Yes but how can I use it as a HID? ...  it cannot detect it so how would I be able to upload code to it  ...

What is "it" here? Look at this photo:

There are two processors on the Uno. It sounds like you have reflashed the ATMega16U2. Do you want to use the ATMega16U2 as a HID or the Atmega328P as a HID? They need totally different techniques.
Once you reflash the ATMega16U2 you can't "get to" the Atmega328P via the USB interface.
On the page you linked there is a workflow for programming the ATMega16U2. Are you following it? If so, which part is not working for you? If not, why not?


Arduino and HC-05 hardware serial issues I have a software sending bitmap data to an Arduino Pro 5V 16MHz 328P that drives an LED display (sketch). This works using the USB-Serial adapter for the Arduino Pro with baud rates up to 500000 Baud. Now I wanted to switch to Bluetooth...
I tried connecting a 5V HC-05 module (set to 230400 Baud 8N1) to the hardware RX/TX pins on the Arduino Pro (Pins 0/1) and connect the PC to the Bluetooth serial port wirelessly (e.g. /dev/rfcomm0 on Linux). My problem is that I can receive data on the PC side using a terminal (the 'Ada' string is received), but nothing is displayed on the LED display. I have tried connecting an oscilloscope to the RX/TX pins on the Arduino and Data is arriving from the HC-05 module TX pin to the Arduino RX pin.
When the USB-Serial adapter is connected to the same pins (0/1 instead of the regular pin header) it still works as before, so there should be no connection issues.
What I tried was adding a 5kOhm resistor from the Arduino RX line to ground. (I found this hint somewhere here), but no dice...
I'm not sure what's wrong, because communication IS working over the USB-Serial adapter. Any ideas on what to try?!

A simple 10k/20k voltage divider is enough to bring the 5V arduino logic-level voltage down to ~3.3 for the HC-05.  It worked for me anyway.

The default baud rate for HC-05 is 9600 baud.  So unless you've changed this with AT- commands you will run into issues.  Although I read that some boards default to 38400 - best check your documentation.  All the cheap HC-05 boards I've tested default to 9600.


Use transistor to press button on external device I have a small device with a simple push button. I'd like my Arduino to be able to make the device register button pushes. It seems like the best way to do this is to use a transistor to close the circuit for the button when my Arduino sends it a pulse from one of its pins. I've mapped out what I think the circuit should look like on a breadboard. I didn't include the device in this diagram, but it's powered by a CR2032 watch battery, which seems to give 220 mAh at 3Vs.

Basically, the two sides of the button would be connected to the transistor's collector/emitter leads. Then the digital pin on my Arduino would be connected via a resistor to the base lead on the transistor. When the pin sends some current to the base lead, the transistor will make current flow through it and the device will register a button press.

I made this by adapting the circuit here, which looks like this:

Basically I got rid of the motor/load and flyback diode, and hooked the two ends of the device's button up to the collector/emitter leads of the transistor.

I'm concerned that I've screwed up this circuit somehow, and will fry either the device or the Arduino or something else when I try and run it, otherwise I'd just test it right away.

Could anyone give me feedback if I'm on the right track here? I couldn't find other answers which dealt with quite this setup, where you are pressing a button on another device, though this question seemed related.

Yes, you have screwed the circuit up slightly.

You want to lose the red wire between the collector and +5V otherwise when you turn the output pin HIGH the transistor will explode.

Also you need to make sure that the ground of the Arduino (emitter of the transistor) is connected to the - of the target circuit and that the button you are "pressing" is an active-low system with internal pullup. If it's not then you will have to come up with another way.

An opto-isolator is a better choice than a transistor when you don't know the internal circuitry of the target device:


Previous and updated releases of Arduino IDE are not be able to start on Win 8.1 x64 I have tried to install many versions of IDE, but non of them has started successfully. There is just the logo of the program shows up and then nothing happens.
My laptop: Toshiba Satellite C50-A630
The releases I have installed: 1.6.12 , 1.6.13, 1.0.6

I had the same problem with various IDE versions. Deleting the preferences.txt solved the problem for me.


SOLVED: Strange phenomenon with avrdude: stk500v2_ReceiveMessage(): timeout only with ATmega250 on windows 7x64 I know this problem has been reported multiple times but in my case I think there is a different light on it.
My desktop is a w7x64 box and I also have a notebook with w10.
Both system have the arduino IDE 1.8.5 with the latest updates.
The desktop though has more boards and drivers as it is my main development system.
I have at ATmega2560 clone with CH340 which used to work on my desktop about half a year ago when I tried to get an LCD touch shield to work.
Yesterday I tried to resume on it and I got the ubiquitous timeout error.

So I removed the shield and tried the basic blink sketch but no change.
I tried an arduino nano and there was no problem to upload the blink sketch.
Then I tried different USB cables and ports but the timeout problem with the ATmega persisted.

So I went to the notebook and the ATmega worked like a charm.
Now I know that the board is ok as well as the cable.
The port is also ok as the nano worked on it smoothly.
I also tried the upload from an elevated command prompt with the verbose option but it gave me no further clue.

The output is below:

C:\Users\Pete\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/bin/avrdude -vvvv -CC:\Users\Pete\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/etc/avrdude.conf -v -patmega2560 -cstk500v2 -PCOM34 -b57600 -D -Uflash:w:T:\TMP\arduino_build_330193/Blink.ino.hex:i

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\Pete\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0 -arduino14/etc/avrdude.conf"

         Using Port                    : COM34
         Using Programmer              : stk500v2
         Overriding Baud Rate          : 57600
STK500V2: stk500v2_open()
STK500V2: stk500v2_getsync()
STK500V2: stk500v2_send(0x1b 0x01 0x00 0x01 0x0e 0x01 0x14 , 7)
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]
STK500V2: stk500v2_recv(): avrdude: ser_recv(): programmer is not responding
avrdude: stk500v2_ReceiveMessage(): timeout

Does anybody have an idea how to further tackle the problem?

I found the problem coming from a mismatch of the port speed setting and the baudrate in the avrdude command.
It seems that the ATmega is very sensitive to timing issues.
After I did set everything to 115200 it works on my w7 box like on the notebook.


Digispark Attiny85 draws more power for digital input than expected I'm trying to figure out why my attiny85 (on a digistump developer board) draws around 3mA at 3V when setting up a pin as INPUT and connecting it straight to ground. The current is measured with a multimeter between said pin and ground (thus only the current sunk by that pin is measured). I would assume that without a pullup resistor it would consume a lot less but it seems, regardless if I configure the button as INPUT or INPUT_PULLUP the current is the same.

Sketch:

void setup() {
  pinMode(3, INPUT);
  //According to datasheet pin needs to be low to disable internal pullup
  digitalWrite(3, LOW);
}

void loop() {
  digitalRead(3);
  delay(100);
}

I would like to design a circuit that can detect a normally closed switch being opened, but the idle power consumption is way to high at the moment. I was planing on using a very high external pullup but it seems I can't disable the internal one...

The schematics of the digistump developer board shows that PB3 is connected to +5V over two resistors (1.5 k + 66.5) Ohms. That's the reason for the high current (5V / 1560 Ohm = 0.0032051 A). See the schematics https://s3.amazonaws.com/digistump-resources/files/97a1bb28_DigisparkSchematic.pdf

As you mentioned in a reply on my comment above, using PB2 shows the expected behavior of an AT85 IO pin.


I am trying to combine a button's coding and servo's coding. But it is still cannot be verified. What have I done wrong? include

Servo myservo;

void setup(){
  myservo.attach(8);
   pinMode(buttonPin, INPUT);
}

void loop()
{
  myservo.write(0);
  delay(3);
  myservo.write(90);
  delay(3);
}
 const int inPin=8;
 const int outPin = 9;
 int currentState = LOW;
  currentState = digitalRead (inPin);
  if (currentState== HIGH)
    digitalWrite (outPin,HIGH);
   else
    digitalWrite (outPin,HIGH);
   delay(10);
 }

Do NOT use two loop() and setup() function.

You can refer to a similar combination between Servo Motor code and Potentiometer code here.


Reset I2C connection with arduino as slave I am currently using I2C serial communications with arduino as slave and raspberry pi as the master. I am sending sensor data from arduino to raspberry pi. I need to reset the I2C connection once the sensor readings cross a threshold. I tried setting the TWCR =0 but it throws a Error 121 Remote I/O error on the raspberry pi when I do that. I also read that one way is to set TWCR =0, but for this I need to execute the Wire.begin(), Wire.onRequest(), and Wire.onReceive() again. Can you please tell me how to run these again since they are put in setup function. Does it mean I need to restart the Arduino program again? Or can I put these in void loop()? Thanks for the help.

You have a misconception about how I2C works. Unlike Serial (UART) I2C is a strictly master-slave interface. The slave cannot do anything without the master, since only the master controls the clock. Thus you don't need to reset the I2C interface to stop the transmission from the slave to the master.

When the master requests data from the slave the following happens: First the master sends the address of the targeted slave, including the direction bit set for "reading from slave". The slave with this address reacts with an acknowledgement (ACK) and start to transmit one byte. This byte get's acknowledged by the master. When the master decides, that it has received enough data, it does not acknowledge (NACK), which let's the slave stop it's transmission. Then the master sends a STOP condition to stop the I2C transmission.

I don't know, how you implemented the I2C communication on the Pi. Normally, when you initiate a read transaction from the master, you provide a number of bytes, that you want to request from the slave. The I2C module/library will then request data from the slave, until is has received all the requested bytes.

Thus you don't need to reset the I2C connection on the Arduino. The master totally controls the communication. When you end the transmission on the master, the slave cannot send further data.

Setting TWCR to zero in the middle of transaction will disrupt the I2C communication protocol. Thus you get an error on the Pi, that states an error in the I2C communication protocol. Just use the correct implementation of the I2C protocol to end the transmission correctly.


What is the best way to init wifi communication between two devices (get IP address)? what is the best way to init wifi communication between two devices without knowing IP of second device, let's say Raspberry Pi and ESP8266?
I want to build simple home automation system for my purpose. There will be Raspberry Pi, as heart of system and ESP8266 as controlled devices. What is best way to get them communicate? I think, the hardest think is how to get their IP address. Then it will be easy to communicate via sockets.
In next text, by RPi I mean Raspberry Pi and program in RPi will be in python (but using call of terminal commands when needed).
My idea is this: On ESP8266 will be running program, which will create WiFi Acces Point at start (on first run in network). Name (SSID) of that AP will be specific (let's say starting with ESP-AUTOMATION prefix), so Raspberry Pi will know, when new ESP device will be turned on (Raspberry Pi will repeatedly search for accesible networks). When new ESP appear, RPi will save own IP to variable and connect to newly searched network (let's say ESP-AUTOMATION-abcd). Then will RPi send to AP (ESP) it's (RPi's) IP address and local network SSID and password. Then it will disconnect, and connect back to local network (and gain it's "old" IP, which it previously saved to variable). Then ESP connect to local network with static IP and after succesfull connect, it will send to RPi it's IP address via socket (because IP addr of RPi it will already known, because RPi have send it when it served as AP). Then RPi will save that IP address. And because IP addresses (of RPi and also ESP) will be configured as static, it shouldn't change over time.
Is this good idea? Or is something of that unreal (I am at beginning of that all)?
PS: I really want completely autonomous system, so for me is not solution something like connect ESP to PC and print it's IP to serial and then it write to RPi...
Thanks for every advice/opinion.

One is a server and the other is a client.
The server do not need to know IP of the client, but the client need to know IP address of the server. See more in communication between two Arduino


Convert serial value into hex using in Genuino zero hello there my code is here.

/* Simple Serial ECHO script : Written by ScottC 03/07/2012 */

/* Use a variable called byteRead to temporarily store
   the data coming from the computer */
byte byteRead;

void setup() {
// Turn the Serial Protocol ON
  Serial.begin(9600);
}

void loop() {
   char a[8];
    int b;
   /*  check if data has been sent from the computer: */
  if (Serial.available())
  {
    /* read the most recent byte */
    byteRead = Serial.read();
    Serial.print(byteRead,HEX);
  }

now when i send '12' from terminal, it prints 3132. means it is ASCII value. but i want to print 12. can you help me?? how to do it??

There are several issues with your sketch. The most important is the lack of understanding for the difference between internal and external representation.

The sketch reads a single character from Serial and prints the value as a hexadecimal number. The character is ASCII; a number that represents symbols in our alphabet.

Your goal is to read characters into a string and then convert the string to a number assuming that the string represents a hexadecimal number ('0'..'9' and 'a'..'f' or 'A'..'F').

The sketch should be 1) scan string, 2) parse and convert string to number, 3) print the number.

Scanning the string requires skipping whitespace and then collecting characters until a whitespace.

The sketch could look something like this:

void setup() {
  Serial.begin(57600);
  while (!Serial);
  Serial.println(F("Serial started..."));
}

void loop() {
  const size_t BUF_MAX = 16;
  char buf[BUF_MAX];
  char* bp = buf;
  char c;

  // Skip whitespace
  do {
    while (!Serial.available());
    c = Serial.read();
  } while (c <= ' ');

  // Scan token until whitespace
  *bp = c;
  do {
    while (!Serial.available());
    c = Serial.read();
    *++bp = c;
  } while (c > ' ');
  *bp = 0;

  // Print scanned token
  Serial.println(buf);

  // Convert to number and print
  const int BASE = 16;
  long val = strtol(buf, &bp, BASE);
  if (*bp == 0)
    Serial.println(val);
  else
    Serial.println(F("not a number"));
}

This allows scan of hexadecimal numbers with possible sign (as defined by strtol). By changing the BASE to zero strtol will use the notations for base definitions (prefix '0' for octal, '0x' for hexadecimal). Last, please observe the parse error handling provided by strtol(*bp != 0).

Cheers!


Arduino Uno "MEM CHECK FAIL" error Just followed a tutorial on how to set up ESP8266 with my Arduino Uno R3. I have a serial connection and get a response of the Arduino but I'm stuck now at chapter "first commands".

I have successfully issued the AT command and also the AT+RST command and got a response. BUT, the response return was "invalid" at its end instead of "ready". Also theres an output "MEM CHECK FAIL!!!"

AT

OK
AT+RST

OK

 ets Jan  8 2013,rst cause:2, boot mode:(3,4)

load 0x40100000, len 1396, room 16
tail 4
chksum 0x89
load 0x3ffe8000, len 776, room 4
tail 4
chksum 0xe8
load 0x3ffe8308, len 540, room 4
tail 8
chksum 0xc0
csum 0xc0

2nd boot version : 1.4(b1)
  SPI Speed      : 40MHz
  SPI Mode       : QIO
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

ÃÕMEM CHECK FAIL!!! <<----------------------------- ???
äslrô
Ai-Thinker Technology Co. Ltd.

invalid <<----------------------------------------- should be "ready"

Can anyone explain me what that means? Do I have to (re)flash the firmware? And also - are the instructions all the same? I have bought mine from China but it was sold at the same ESP8266 module on Amazon.

http://www.agcross.com/2015/09/the-esp8266-wifi-chip-part-1-up-and-running/

According to the tutorial it's an undocumented bug with no fix.

If you change the name, baud, and set up the wifi and password you should be good to go


How to wire and use a B10K linear LED potentiometer? I've bought some nice looking LED potentiometers from Ebay. They look like this.
I'm very new to low level electronics/hardware and I don't know how to wire it. It has 4+2 pins.
Also, how to use it in the Arduino?

The Taiwan Alpha spec sheet page 2 for this type of pot shows a little information about the pinout.  Refer to the second “P.C.B. MOUNTING HOLE DETAIL” diagram, which apparently shows the top side PCB layout.  The LED's anode is at lower right, marked B; its cathode is lower left, marked E.  It doesn't say what L (the pin next to E) is.  The three numbered pins most probably are: 1 and 3, ends of the resistive element.  2, wiper.

If that is correct, you could attach pin 1 to 5V, pin 3 to ground, and pin 2 to an analog input.  Before hooking it up like that, however, take ohmmeter readings from pin 1 to pin 2 as you move the slider from one end to the other and see if readings change proportionately to position.

Note, the phrase “Center Dent” on the ebay page probably should instead be “Center Detent” or  “Center Click”.


Reading ADS1232 with Arduino I'm a newbie and I'm trying to read an ADS1232 with an Arduino for a Weight Scale Project.

I read data through the SPI interface, but i don't receive the result.

#include <SPI.h>

#define MISOPIN  50  //DATA
#define SCLKPIN  52  //SCLK
#define PDWN     53  // SS
#define SPEED       5
#define GAIN0       7
#define GAIN1       6
#define CLKIN       10
#define A0          9
#define TEMP        8

uint32_t byte1;
uint32_t byte2;
uint32_t byte3;
uint32_t finaladc = 0;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);

  pinMode(PDWN, OUTPUT);
  pinMode(MISOPIN, INPUT);
  pinMode(SCLKPIN, OUTPUT);
  pinMode(SPEED, OUTPUT);
  pinMode(GAIN0, OUTPUT);
  pinMode(GAIN1, OUTPUT);
  pinMode(A0, OUTPUT);
  pinMode(TEMP, OUTPUT);

  digitalWrite(GAIN0, HIGH);
  digitalWrite(GAIN1, HIGH);
  digitalWrite(SCLKPIN, LOW);
  digitalWrite(A0, LOW);
  digitalWrite(TEMP, LOW);
  digitalWrite(SPEED, HIGH);//0-->  10SPS ,1-->80SPS
  digitalWrite(PDWN, HIGH);  //0-->  POWERDOWN(SLEEPING -NO CONVERSION) ,1-->WORKING MODE

  reset_adc();

  SPI.begin();
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE1);

  digitalWrite(SCLKPIN,LOW);

}

void loop() {
  // put your main code here, to run repeatedly:
  if (digitalRead(MISOPIN)== LOW) read_adc();

  delay(1000);

}

void reset_adc()  {
  digitalWrite(SCLKPIN,HIGH);
  delayMicroseconds(1400);

}

void read_adc()  {
  drdy_wait();
  uint8_t i;
  finaladc = SPI.transfer(0xff);
  finaladc |= (uint32_t)SPI.transfer(0xff) << 8;
  finaladc |= (uint32_t)SPI.transfer(0xff) << 16;
  Serial.print ("ADC_value:  ");
  Serial.println(finaladc,DEC);
  Serial.println();

}

void drdy_wait()
{
  delayMicroseconds(30);
}

Has anyone worked with this? Can you help me?  Thank you

I fished out some code I wrote a while back while evaluating the 1232.  SPI is a headache because of the need toggle the clock signal to prevent the last data bit from 'sticking', which will botch repeated reads when the last data bit is high.

If you are absolutely required to use SPI stop reading this answer.

Everything you need to know is on pages 18 and 19 of the ADS1232 datasheet.  Note this is strictly demo material, for example it doesn't take into account settle time when switching channels.

int32_t read_adc(const uint16_t wait_millis) {
   int32_t data = 0;
   // reset ADC
   digitalWrite(ADS1232_PDWN, LOW);
   delayMicroseconds(10);
   digitalWrite(ADS1232_PDWN, HIGH);
   delayMicroseconds(10);

   for (; data < wait_millis && digitalRead(ADS1232_DRDY_DOUT) != LOW;
        delay(1),
        data++);

    if (data == wait_millis) {
        // timeout
        return -1;
    }

   // read in 24 bits, see Page 19 of the datasheet

   data = 0;
   for (uint8_t i = 0; i < 24; i++) {
        digitalWrite(ADS1232_CLK, HIGH); // clock out next data bit
        data <<= 1;
        data |= digitalRead(ADS1232_DRDY_DOUT);
        digitalWrite(ADS1232_CLK, LOW);
    }
    // adjust for sign. See page 18 of datasheet
    if (data & 0x00800000)
        data |= 0xFF000000;
    // avoid having DRDY/DOUT remain in the state of the last bit
    // see page 19 of datasheet
    digitalWrite(ADS1232_CLK, HIGH);
    delayMicroseconds(10);
    digitalWrite(ADS1232_CLK, LOW);

    return data;
}


Generating random pattern on startup I'm trying to get an arduino to generate a random pattern in a neopixel grid every time you restart it. But I only get the same number sequence generated each time. What I'm doing wrong?

Here's the sequence that keeps happening: 1110 0000 1101 0011

Here's the code I have so far:

/* ========================== INCLUDES ================================= */
#include "RGB.h"

#include <Adafruit_NeoPixel.h>
#include <Adafruit_NeoMatrix.h>
#include <Adafruit_GFX.h>
#ifndef PSTR
 #define PSTR // Make Arduino Due happy
#endif

/* ========================== NEOPIXELS SETTINGS ================================= */
#define NEOPIN 6
#define MATRIX_W 4
#define MATRIX_H 4

Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(MATRIX_W, MATRIX_H, NEOPIN,
  NEO_MATRIX_BOTTOM + NEO_MATRIX_LEFT +
  NEO_MATRIX_ROWS + NEO_MATRIX_ZIGZAG,
  NEO_GRB + NEO_KHZ800);

/* ========================== BOARD / GRID STUFF ================================= */

/* coordinates for a 4 x 4 grid
00,10,20,30
01,11,21,31
02,12,22,32
03,13,23,33,
04,14,24,34
*/

int land[4][4] = {};

/* ========================== SETUP AND LOOP ================================= */

void setup(){

  Serial.begin(9600);

  matrix.begin();
  matrix.setBrightness(60);
  matrix.fillScreen(matrix.Color(off.r,off.g,off.b));
  crossFade(off, white, 50, 5);
  drawLand();
}

void loop(){
  matrix.show();
}

/* ========================== FUNCTIONS ================================= */

  void drawLand() {
  for(int row = 0; row < MATRIX_W; row++) {
    for(int column = 0; column < MATRIX_H; column++) {

     land[row][column] = random(0,2);

     Serial.println(land[row][column]);
     if(land[row][column] == 1) {
       matrix.drawPixel(column, row, matrix.Color(red.r,red.g,red.b));
     }
   }
  }
}

randomSeed(analogRead(A0)); does the trick well

Better yet, use the lsb of analogreads to seed the random number generator. No repeat patterns any more.


Arduino Uno and Leonardo SPI clock can't be measured I want to measure the SPI clock (pin 13) using the Arduino example code for the SPI library (very simple example). Basically independent from the loop function, the clock should be fired continuously.

I deployed the Arduino SPI example code on the board and measured pin 13 on an oscilloscope, but nothing was found, always zero volt.

Please note the SPI clock will only be active while it is shifting data. So simply put the spi.transfer in a hard loop

#include <SPI.h>

void setup() {
  SPI.begin();
  while (1) {
    SPI.transfer(0x00);
  }
}


Global memory reduction when using SPI/SD I want to use an SD card and when including the library both SPI.h and SD.h are included. Also later I want to use an external SRAM chip (probably using SPI.h as well). However, without the SRAM chip my sketch uses around 849 bytes of global memory, where I expect most of it taken by the SD.h / SPI.h combination. Without these includes only 9 bytes are used.

How can I reduce the amount of global memory (still I want to use the SD and SPI interface)?

Edit:

According to a remark below 512 bytes are used for the SD so that explains mostly of the 849 bytes. And some additional questions:

Is it possible to reduce the 512 bytes for the SD card to much less like 16 bytes ...I only need to read a file (128 KB) and copy it to an SRAM (external). And I don't mind if it will be transferred in 16 byte blocks. Actually, I could get rid of the buffer at all after the SD to SRAM copy.

My ultimate goal is to leave 1KB + some dynamic memory (for function call stacks/local variables). However, finally I need to move to the Arduina Mega anyway, but was hoping I could already start the project with my Arduino Uno.

Is it possible to reduce the 512 bytes for the SD card to much less like 16 bytes

The Arduino SD library uses an internal file block caching (512 bytes) to improve performance. It is possible to read directly from a file block on the SD but that would be very slow. Every 16 bytes read would require reading from file block, discharging all preceding bytes (as the file block is read serially), reading the 16 bytes, and then stopping the block read.

There are a few tiny SD libraries that actually use this technique. See for instance Petit FAT File System http://elm-chan.org/fsw/ff/00index_p.html

Another technique is to block copy from the SD directly to the external SRAM without going through additional buffers. This requires a refactoring of the SD library so that it uses a callback instead of the internal buffer.

Cheers!


Code flow for precission applications This is a question about programming. Mainly about the loop() function

As an example
Consider code where you get data from an accelerometer, and if the Gs are high enough you do something.

Consider the following pseudocode:

void setup()
{
pinMode(1, INPUT);
bool flag = false;
}

void loop
{
int x= analogRead(1);
if (x>2)   //if the Gs we get from accelerometer
  flag = true;
if (button)  // if user hits the emergency button
  flag = true;

if (flag == true)
{
//GET SERIAL DATA (EG GPS COORDINATES)
//DO SOME HEAVY PROCESSING
}
}

Now loop runs repeatedly
That means all the commands are executed in a continuous/serial style

Since that happens, what will happen if the accelerometer reading where (x>2), which is what we look for, happen in the REAL world, at a time where in the CPU, the cpu is at that time processing or checking following commands in the program flow, like

if (button)  // if user hits the emergency button
      flag = true;

    if (flag == true)
    {
    //GET SERIAL DATA (EG GPS COORDINATES)
    //DO SOME HEAVY PROCESSING
    }
    }

Is there any chance that the cpu will miss real world events, because at that time the real world event occured, the cpu was processing other code. Or rather, not checking for that at that time. For our example, when the event occured, it wasnt checking the analogread() at that time, but was processing following code.

Should i worry about that?

Yes, in theory you can always miss events if you use a polling approach like that. Whether or not that's a problem depends on how accurate/frequent your data collection needs to be.

You can often mitigate the issue to an acceptable level if you are able to poll fast enough. That's determined largely by what else your main loop is doing. The more work it has to do elsewhere, the longer it will take between calls to analogRead() (and the more likely it is to miss something). Optimising your code can help.

You may also find that you can compensate sufficiently by interpolating between samples. Linear interpolation is very easy, although more complex options may also be possible, especially if you're processing the data offline afterwards.

If polling isn't working for you, then interrupts are the obvious alternative. Since you're reading an analog signal, you'd probably need some external circuitry which does a voltage comparison. You can get dedicated comparator IC's from all sorts of vendors, or use an op-amp circuit if you prefer.

If the signal goes over a pre-determined threshold, the comparator would have to pulse or assert a digital line. That could trigger an external interrupt pin on your microcontroller, which will execute custom handler code. See attachInterrupt() for more information.