wifi failled connection with yun and after upgrading openwrt I recently bought an arduino yun. When trying to connect to the router following the procedure in https://www.arduino.cc/en/Guide/ArduinoYun#toc14. After the Configure & Restart, the Arduino network shut down after a few moments but it wasn´t linked to my router.

After reading a bit about it in the internet, i upgraded it following https://www.arduino.cc/en/Tutorial/YunSysupgrade. As i found that the firmware version 1.5.3 was from 2014 https://github.com/arduino/openwrt-yun/blob/master/ChangeLog, and as Reflashing the OpenWrt-Yun image on the Yún would void warranty, i proceeded by http://nootrix.com/software/upgrade-arduino-yun-openwrt/. Everything occured as detailled there.

However now, when i turn on the yún, none network appear and the WLAN LED doesn't blink.

Thanks

Find out if the Linux system is running. Maybe you mistyped your WiFi password.
Try the Following:

connect via Ethernet check your router to see if the Yun request an IP via DHCP
If unsuccessful connect via USB and install this sketch to see if you get a command prompt maybe your network settings are messed up

Still no success?

Press the WiFi reset button for at least 30 seconds to do a reset to
factory defaults.


Using Capacitive Sensing Library with a 74HC4067 multiplexer I'm trying to use the Capacitive Sensing Library by Paul Badger in conjunction with one or more 74HC4067 multiplexers to achieve a lot of capacitive touch inputs. I came across this youtube video where the poster seems to have accomplished what I'm trying but I can't seem to replicate this.

Here is the setup I'm using with an arduino nano, some 1MΩ resistors and a CD74HC4067 breakout :

Here is my Arduino code :

#include <CapacitiveSensor.h>

#define muxS0Pin 7
#define muxS1Pin 6
#define muxS2Pin 5
#define muxS3Pin 4
#define muxSignalPin 3
#define muxEnPin 8
#define capSenseSendPin 2
#define sampleRate 5

int touch[4] = {};

CapacitiveSensor capSense = CapacitiveSensor( capSenseSendPin, muxSignalPin );

void setup() {
    digitalWrite( muxEnPin, LOW );
    Serial.begin( 115200 );
}

void loop(){
    byte touchIndex = 0;
    for ( byte channel = 0; channel < 4; ++channel ) {
        digitalWrite( muxS0Pin, ( channel & 1 ) >> 0 );
        digitalWrite( muxS1Pin, ( channel & 2 ) >> 1 );
        digitalWrite( muxS2Pin, ( channel & 4 ) >> 2 );
        digitalWrite( muxS3Pin, ( channel & 8 ) >> 3 );
        touch[touchIndex] = capSense.capacitiveSensor( sampleRate );
        ++touchIndex;
    }
    for ( byte i = 0; i < 10; ++i ) {
        Serial.print( touch[i] );
        Serial.print("\t");
    }
    Serial.println();
}

This example attempts only four capacitive touch pads but eventually I plan to use all 16 and then another multiplexer, but right now I'm stuck on getting anything, I seem to be getting some readings on touching the last pad but it's not what I expect to see, and it affects all the reading.

I've successfully got a version of this running without a multiplexer just on ten IO pins and it worked great. I also got the multiplexer running fine in a separate example with 16 push buttons.

Could the problem be due to pad charge times or the send-recieve capsense signals getting stopped in the multiplexer?

Any and all help would be appreciated.

This is way late, but for anyone who runs across this, here was my solution. The two main thing is explicitly using analog input pins (which could be quantized to digital values in the software, and making sure you have resitors on each channel being sensed. Also, ground the EN pin on the multiplexer

#include <CapacitiveSensor.h>

#define muxS0Pin 9  // I used these rather than 4-7
#define muxS1Pin 10
#define muxS2Pin 11
#define muxS3Pin 12

#define muxSignalPin A0      // explicitly set ro analog
#define capSenseSendPin A2   //

#define sampleRate 10
#define n_inputs 16

int touch[n_inputs] = {};

CapacitiveSensor capSense = CapacitiveSensor( capSenseSendPin, muxSignalPin );

int readMux(int channel) {
  int controlPin[] = {muxS0Pin, muxS1Pin, muxS2Pin, muxS3Pin};

  int muxChannel[16][4] = {
    {0, 0, 0, 0}, //channel 0
    {1, 0, 0, 0}, //channel 1
    {0, 1, 0, 0}, //channel 2
    {1, 1, 0, 0}, //channel 3
    {0, 0, 1, 0}, //channel 4
    {1, 0, 1, 0}, //channel 5
    {0, 1, 1, 0}, //channel 6
    {1, 1, 1, 0}, //channel 7
    {0, 0, 0, 1}, //channel 8
    {1, 0, 0, 1}, //channel 9
    {0, 1, 0, 1}, //channel 10
    {1, 1, 0, 1}, //channel 11
    {0, 0, 1, 1}, //channel 12
    {1, 0, 1, 1}, //channel 13
    {0, 1, 1, 1}, //channel 14
    {1, 1, 1, 1} //channel 15
  };

  //loop through the 4 contol pins
  for (int k = 0; k < 4; k ++) {
    digitalWrite(controlPin[k], muxChannel[channel][k]);
  }
  //read the value at the SIG pin
  return capSense.capacitiveSensor( sampleRate );
}

void setup() {
  // Very important to set control pins to output mode
  pinMode(muxS0Pin, OUTPUT);
  pinMode(muxS1Pin, OUTPUT);
  pinMode(muxS2Pin, OUTPUT);
  pinMode(muxS3Pin, OUTPUT);

  digitalWrite(muxS0Pin, LOW);
  digitalWrite(muxS1Pin, LOW);
  digitalWrite(muxS2Pin, LOW);
  digitalWrite(muxS3Pin, LOW);
  Serial.begin( 9600 );
}

void loop() {
  byte touchIndex = 0;
  for ( byte channel = 0; channel < n_inputs; ++channel ) {
    Serial.print( readMux(channel));
    Serial.print("\t");
  }
  Serial.println();
}


Can't run two separated DC Motors I'm trying to build Bluetooth RC car, but I can't run only one DC motor.. only both of them. Everything works fine, the bluetooth, the app but when i try to go forward/backward/left/right nothing happens, only when i run both of them. I'm running the Arduino Nano with usb cable. The bluetooth connection is stable, The DC motors are working. I don't know what I'm doing wrong. Thanks!

const int AIA = 2;
const int AIB = 3;
const int BIA = 4;
const int BIB = 5;
byte vSpeed = 255;
int state;

void setup() {
pinMode(AIA, OUTPUT);
pinMode(AIB, OUTPUT);
pinMode(BIA, OUTPUT);
pinMode(BIB, OUTPUT);

// Initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
}

void loop() {
  //Save income data to variable 'state'
    if(Serial.available() > 0){
      state = Serial.read();
    }

  /***********************Forward****************************/
  //If state is equal with letter 'F', car will go forward!
    if (state == 'F') {
      analogWrite(AIA, vSpeed);
      analogWrite(AIB, 0);
      analogWrite(BIA, 0);
      analogWrite(BIB, 0);
    }
  /**********************Forward Left************************/
  //If state is equal with letter 'G', car will go forward left
    else if (state == 'G') {
      analogWrite(AIA, vSpeed);
      analogWrite(AIB, 0);
      analogWrite(BIA, vSpeed);
      analogWrite(BIB, 0);
    }
  /**********************Forward Right************************/
  //If state is equal with letter 'I', car will go forward right
    else if (state == 'I') {
      analogWrite(AIA, vSpeed);
      analogWrite(AIB, 0);
      analogWrite(BIA, 0);
      analogWrite(BIB, vSpeed);
    }
  /***********************Backward****************************/
  //If state is equal with letter 'B', car will go backward
    else if (state == 'B') {
      analogWrite(AIA, 0);
      analogWrite(AIB, vSpeed);
    }
  /**********************Backward Left************************/
  //If state is equal with letter 'H', car will go backward left
    else if (state == 'H') {
      analogWrite(AIA, 0);
      analogWrite(AIB, vSpeed);
      analogWrite(BIA, vSpeed);
      analogWrite(BIB, 0);
    }
  /**********************Backward Right************************/
  //If state is equal with letter 'J', car will go backward right
    else if (state == 'J') {
      analogWrite(AIA, 0);
      analogWrite(AIB, vSpeed);
      analogWrite(BIA, 0);
      analogWrite(BIB, vSpeed);
    }
  /***************************Left*****************************/
  //If state is equal with letter 'L', wheels will turn left
    else if (state == 'L') {
      analogWrite(BIA, vSpeed);
      analogWrite(BIB, 0);
    }
  /***************************Right*****************************/
  //If state is equal with letter 'R', wheels will turn right
    else if (state == 'R') {
      analogWrite(BIA, 0);
      analogWrite(BIB, vSpeed);
    }
  /************************Stop*****************************/
  //If state is equal with letter 'S', stop the car
    else if (state == 'S'){
      analogWrite(AIA, 0);
      analogWrite(AIB, 0);
      analogWrite(BIA, 0);
      analogWrite(BIB, 0);
    }
}

Connect the Nano ground to the driver board ground.  Since they do not share a common ground, they can have odd behavior as their ground planes float.

You need only connect the grounds, the USB can still provide +5 to the Nano, and the +9 can still provide power to the driver.  The only energy that will flow through the black wire connecting the grounds is the energy that flows between pins 2,3,4,5 and the driver's AIA, AIB, BIA, BIB, for the logic signals, which I'd bet is in the sub-uA range.


Distinguishing between multiple Infra Red Transmitters I am working on an Arduino project where I use an infra red camera along with 4 transmitters placed each on a corner of a square platform to park a robot perfectly on this platform.
However, it is important for the camera to distinguish between the 4 transmitters.
(it should know the right transmitters from the left and the upper transmitters from the lower).
Can anyone please help me find a solution to this problem?

It's a symmetry problem, you can solve it breaking the simmetry.
Options:

use three transmitter instead of four, the plane and its center is
still determined.
move one transmitter in the middle of the side of the square.
use different duty cycle for one (or more) transmitter.
use linear polarizing filters on the transmitters and a rotating filter on the camera lense.
...

I guess that also SVD could be helpful to find the pattern's center, when the camera is not centered and perpendicular.


Speeding up Girino gives strange readouts I was reproducing the Girino (the Instructable by Caffeinomane) bundled with the Girinoscope (the Java GUI by Chatanga). The results worked well and I went on to see if the oscilloscope can go up to higher kS/s.

In short, originally only upto prescaler 8 works. I removed PWM pin and it works upto 4 but prescaler 2 strangely behaves. Here are the details:

I did a preliminary test on prescaler 32 (~38.5kHz). Settings as follows and the same in other tests.

The signal (the same hereafter) is generated by a 555 timer astable multivibrator running at 4.5V (3 AA batteries).
The circuitry was simply omitted. I just tied 3.3V of Arduino NANO / ATmega328 to digital pin 6 as the trigger level.
There is no +2.5V offset done by the original Girino. (The scale should be 0~5V and the signal is 0~4V)

So then I wanted to try if it can speed up more. The code optimization quoted by Chatanga allowed prescaler 8 and 16 (76.9kHz and 151.8 kHz).

In order to push it the poor Arduino to the limits, I disabled PWM pin in the original Girino which sets the trigger level with duty cycles (PWM from pin ~3 being fed into pin 6). It's because I simply used a fixed 3.3V trigger level.

Prescaler 4 is unlocked.

Ambitious I go on to test prescaler 2. The GUI did not provide this option so I simply set it in the Arduino code.

I thought it did not work. I noticed if the prescaler is exceeding the Arduino's capability, TXRX simply does not blink. But this time the TXRX is just blinking! To verify this, I shifted the wait duration.

In previous screenshots, the leftmost green line is dashed (probably because it's below fullscale deflection). But in the last two, be it offset or not, the line is solid.

The debug output is like this: (8bits 0~255 given by ADC)

many 0 then suddenly 255 thereafter. (matches the GUI output)

I suspect it's due to slow TXRX? How to solve this? Or anything I overlooked?

Hope that this overdetailed question does not sicken you.

From the ATmega328P datasheet, section 29.8, "ADC Characteristics":

  Clock Frequency — Min.: 50kHz, Max: 1000kHz

With a 16MHz system clock this means that a /16 prescaler is the most the ADC is considered reliable under for a reasonable 10 bit result (for a full 10 bit result the maximum frequency is 200kHz, which corresponds to a prescaler of /80).

As the frequency increases the sample-and-hold circuitry of the ADC gets less time to do the "sample" part before conversion begins. As such any correctness goes out the window, certainly at the lower bits. The fact that you got any sort of result that you did at /4 is luck.

TL;DR: The ADC is too slow.


No data from U-Blox Neo-6M I'm trying to get Neo-6M module to work with Arduino Uno, but it just isn't transmitting any data. It is getting 3.3V.
I've tried measuring the Amps and I got zero, so I'm afraid that the module could be broken.

Neo-6M wiring:

Arduino wiring (power):

Arduino wiring (data):

Arduino code:

#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
   This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
static const int RXPin = 4, TXPin = 3;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

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

  Serial.println(F("DeviceExample.ino"));
  Serial.println(F("A simple demonstration of TinyGPS++ with an attached GPS module"));
  Serial.print(F("Testing TinyGPS++ library v. "));     Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
}

void loop()
{
  // This sketch displays information every time a new sentence is correctly encoded.
  while (ss.available() > 0)
    if (gps.encode(ss.read()))
      displayInfo();

  if (millis() > 5000 && gps.charsProcessed() < 10)
  {
    Serial.println(F("No GPS detected: check wiring."));
    while(true);
  }
}

void displayInfo()
{
  Serial.print(F("Location: "));
  if (gps.location.isValid())
  {
    Serial.print(gps.location.lat(), 6);
    Serial.print(F(","));
    Serial.print(gps.location.lng(), 6);
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F("  Date/Time: "));
  if (gps.date.isValid())
  {
    Serial.print(gps.date.month());
    Serial.print(F("/"));
    Serial.print(gps.date.day());
    Serial.print(F("/"));
    Serial.print(gps.date.year());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F(" "));
  if (gps.time.isValid())
  {
    if (gps.time.hour() < 10) Serial.print(F("0"));
    Serial.print(gps.time.hour());
    Serial.print(F(":"));
    if (gps.time.minute() < 10) Serial.print(F("0"));
    Serial.print(gps.time.minute());
    Serial.print(F(":"));
    if (gps.time.second() < 10) Serial.print(F("0"));
    Serial.print(gps.time.second());
    Serial.print(F("."));
    if (gps.time.centisecond() < 10) Serial.print(F("0"));
    Serial.print(gps.time.centisecond());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.println();
}

It isn't enough to power the module with 3.3V. You also have to level-shift the Arduino's 5V TX signal to 3.3V that is acceptable by the GPS module's RX pin, using a 1:2 voltage divider.

You should also know that the Arduino's 3.3 V pin can't source more than 50 mA; your module's current draw may sometimes exceed this limit (max is 67 mA). Instead, connect the Arduino's 5 V pin (which can source up to 500 mA) to the VCC of the GPS module through an LM1117T 3.3 V regulator:

The input goes the Arduino 5V pin and the output goes to the NEO-6M VCC. Connect all GNDs together.

Then run a basic sketch like this:

#include "SoftwareSerial.h"

SoftwareSerial gps(4,3);

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

void loop(){
  while (gps.available())
    Serial.write(gps.read());
}

This will basically make the Arduino grab any NMEA data sent by the NEO-6M and forward it to your PC's serial monitor. If you receive legible data, it means you've established comms with the module. You can then upload your original sketch.


Handling arduino output current I need to power an actuator that requires 12 volts and consumes between 5 and 10 amperes depending on the weight it is charging. Therefore I bought a power supply of 12 volts and 10 amperes.

My intention is to send in the arduino output the 12 volts and the current provided by the power supply.

The options that I have thought are the following:

a) Connect the power supply to the arduino input pins and send the voltage and current from the power supply to the actuator through the arduino output (I know I could do it directly to the actuator, but I am interested in doing it through of arduino since it will involve programming code to put conditionals)

My doubt with this option is if I do not damage the arduino by connecting that power source with that amperage. If there is no problem, my question is if I could handle the current of the power supply at the output or the current could only be handled by what arduino gives that would not be much.

b) The other option that I think is simply to send a flag to the output and then this flag activates the power supply in some way and then I could use the 12 volts and the 10 amperes to connect them to the actuator.

I would like you to guide me on the alternatives I have thought about and tell me what would be the right thing to do, or if you know some other way in which you should do it.

Thank you very much in advance
Cheers

As others have said, an Arduino pin can't handle 12V, and can't handle anywhere near 10A of current directly. A digital pin on an Arduino is limited to 20mA, or 1/500 as much current as you need, at 5V, which is less than half the voltage you need.

If you try to connect 12V to a pin on an Arduino pin you will almost certainly destroy that pin, and may destroy the entire Arduino. If you try to source or sink even 1/100 of the current you are talking about through an Arduino pin, even at 5V, you will also probably destroy that pin and possibly the entire Arduino.

This sounds like a good application for a power MOSFET transistor. With that much current you'll need to put a heatsink on the transistor.

Here's one that would work:

https://www.sparkfun.com/products/10213

You'd use a logic pin from the Arduino to control the gate on the transistor, and the transistor would switch 12V at high current with very little resistance.

If the actuator is inductive, you'll need to protect the transistor with a suitably large "flyback diode" to protect it from the reverse current (or "back EMF") you get from an inductor when you remove power from it:

https://en.wikipedia.org/wiki/Flyback_diode


How to upload program to custom arduino board without USB FTDI and making it read only? If I was to mass produce a microcontroller board I have designed based around the atmega328 (very similar to an arduino uno) but for one embedded task where I want one program only to be stored on it. I want to make the program read only and impossible to access and impossible to overwrite. The board will not include a USB FTDI chip in order to prevent another program being uploaded via arduino IDE. How would I upload said program to the microcontroller?

Would I have to make use of ICSP pins (I dont know much about that) and if this is an impossible task and so a USB will have to be integrated to upload programs... How would i prevent other programs overwriting the main program and also prevent this program from being viewed?
[The main program is written in the arduino IDE]

I think you cannot prevent overwriting the firmware, neither prevent viewed by others.

However, you can detect that someone overwrites it (besides you), by reading some code from e.g. EEPROM based on the content of your firmware. If you read a different code, than you can act upon it.


Serial LCD has like a "rolling shutter" I've attached my LCD Display (AV1624YRB-SJ) to my Arduino Nano on the following pins:

#define LCD_RS 7
#define LCD_ENABLE 8
#define LCD_D4 9
#define LCD_D5 10
#define LCD_D6 11
#define LCD_D7 12
#define LCD_CONTRAST 6 //PWM Wave with capacitor for contrast

and im initializing it this way:

LiquidCrystal lcd(LCD_RS, LCD_ENABLE, LCD_D4, LCD_D5, LCD_D6, LCD_D7);

byte arrow[8] = {
    B00000, B00100, B00010, B11111, B00010, B00100, B00000,
};

void setup() {
  pinMode(LCD_CONTRAST, OUTPUT);
  pinMode(LCD_D4, OUTPUT);
  pinMode(LCD_D5, OUTPUT);
  pinMode(LCD_D6, OUTPUT);
  pinMode(LCD_D7, OUTPUT);
  analogWrite(LCD_CONTRAST, STARTCONTRAST); // Set LCD Contrast

  lcd.begin(16, 2);
  lcd.createChar(CHAR_ARROW, arrow);
  lcd.setCursor(3, 0);
  lcd.print("Welcome To");
  lcd.setCursor(1, 1);
  lcd.print("My Test");
  delay(2000);
}

The Problem is, that there is nothing to see on the display.
If i crank up the contrast slightly you can see something like a rolling shutter effect.

http://i.imgur.com/FOIEwVj.gif

The display worked just fine 3 days ago.
Where could be a mistake. I don't remember changing something, but i tried rewiring.

As I noted in a comment to the question  Arduino LCD is displaying gibberish, sometimes,  a PWM's sharp-cornered waveform might introduce a lot of noise into the LCD.  If you have to use PWM, you probably should put a good low-pass filter between PWM and LCD pin 3.

Check whether using a fixed voltage (from a voltage divider or pot) fixes the problem.  That fixed the problem in the case of the linked question.

If you need programmable control of contrast, and can't get PWM to work without heroic measures involving op-amp based filters, you could use a digital pot or a DAC.


FTDI and atmega328p-au I want to connect an Arduino Pro Mini with ATmega328P so as to drive a SI4463. But I don't know BLK, CTS, DTR should be connected to what pins of ATmega328P.

How do I connect this?

BLK is ground.
CTS is generally not used. I leave it unconnected on my boards.
DTR goes to the auto-reset circuit.

Update:

  Can I let DTR directly connect with RESET ?

Auto-reset circuits use a .1uf capacitor between the DTR (or RTS, depends on which one your cable supplies) and the reset pin. (The exact value probably isn't too important). Without it, the reset circuit is likely pick up noise and randomly reset the Arduino.


Start I2C communication at an external event I'm working on a Arduino Uno and a ADC ADS1115. Devices communicate by I2C where Arduino is the master.

I would like to use the ADC to the maximum of his possibility.

So i configure the ADC to set a pin when a conversion finish and use this pin as an external interrupt.
But i can't read the data because I2C interrupt can't work in a external interrupt handler.
I think to use a timer to have a fixed sampling rate too, but it's the same issue.

There is my code below, and if you have any idea of how i can doing my goal let's share it ;)

#include <QueueArray.h>
#include <ADS1115_Vibratec.h>

  Adafruit_ADS1115 ads;

  QueueArray <uint16_t> fifo;

  int i=0;

void setup() {

 Wire.begin();

 Serial.begin(115200);

 ads.Config( ADS1115_REG_CONFIG_OS_NOEFFECT,
          ADS1115_REG_CONFIG_MUX_DIFF_0_1,
          ADS1115_REG_CONFIG_PGA_6_144V,
          ADS1115_REG_CONFIG_MODE_CONTIN,
          ADS1115_REG_CONFIG_DR_860SPS,
          ADS1115_REG_CONFIG_CMODE_TRAD,
          ADS1115_REG_CONFIG_CPOL_ACTVLOW,
          ADS1115_REG_CONFIG_CLAT_NONLAT,
          ADS1115_REG_CONFIG_CQUE_1CONV);

 ads.Set_ConvReady_function();

 attachInterrupt(0,interrupt,RISING); //INT0 -> pin 2, fonction interrupt,    front montant

  }

  void loop() {

   while (!fifo.isEmpty ())
   {
      Serial.write(fifo.dequeue());
      Serial.println();

   }

  }
  void interrupt()
  {
    fifo.enqueue(ads.ReadConvert());
  }

You could set a 'volatile' flag in the interrupt routine. In the loop() you can check if the flag is set. That is how the i2dev uses the interrupt for the MPU-6050. See the MPU6050_DMP6.ino example.

First thing to do is set the I2C clock to 400 kHz. Keep the wires short and pullup resistors low.

Wire.begin();
Wire.setClock(400000L);   // 400 kHz I2C clock speed

You can let the MultiSpeed I2C Scanner run for a while to see if it is stable.

The ADS1115 has also I2C High-Speed Mode up to 3.4MHz. The Arduino can not do that. The Arduino has a fast SPI mode, but the ADS1115 has no SPI bus.

Using an interrupt adds extra overhead. A fixed software timer with millis might be just as fast.

Do you want the maximum of 860 Samples per second? The Arduino Uno or Mega or Leonardo are too slow for that. Do you want to continuously read data or just a burst and store it in ram ?


No Websockets Server for Arduino mkr1010? I've seen some interesting explanations on using websocket comms on mkr 1010 but it's always handling the mkr 1010 as the client and the server being always a computer or some other "non-arduino" server . I'm working on a system with several mkr 1010's in a master/slave setup and bidi comms i.e. i want to use one of the mkr's as a server (does the calculations etc.) and the other as clients (get result from calculations ans send back sensor info). I did not found any library or example of websocket server for mkr1010. I found it for ESP systems. Please help as i tried my bidi comms with webclient and webserver using http but not good enough for my applicaton (not realy bidi).
thanks a lot !

Most websocket libraries work over a Client. Client is base class for all EthernetClient and WiFiClient classes.

But why do you want to use a Websocket for communication of two MCU in the same LAN? Websockets are intended for communication over HTTP infrastructure (firewalls, proxies) to a web server in Internet or from browser to a web server.

Use a basic TCP socket over Arduino Client.

WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.

If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read only from the WiFiClient object on the other side.

client socket

if (client.connect(serverIP, PORT)) {
  client.print("request\n");
  String response = client.readStringUntil('\n');
  Serial.println(response);
  client.stop();
}

server side

WiFiClient client = server.available();
if (client && client.connected()) {
  String request = client.readStringUntil('\n');
  Serial.println(request);
  client.print("response\n");
  client.stop();
}


Cant's code against Yun Wireless Section Just got my Yun today.  Successfully connected to my home wireless, installed YunSysUpgrade_v1.5.1,
and divied up my Micro SD card for Linino and Windows file system with YunDiskSpaceExpander,
and got files serving on the native file server from the SD card.

But I can't seem to touch the wireless section from a sketch.

I'm running a mod of the example ScanNetworks sketch - here's the relevant part:

void loop() {
  delay(1000);
  String fv = WiFi.firmwareVersion();
  Serial.println("Version: ");
  Serial.println( fv );
  Serial.println("Status: ");
  Serial.println( WiFi.status() );
  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

Here is the ouptut: no version and a status of 255 (which I cannot find documentation on....)

  Version:

  Status:
  255
  Scanning available networks...
  ** Scan Networks **
  number of available networks:0

I looked at installing wifi_dnld.elf, but could not find jumper 3 on my Yun, so assumed it was for the 'true shield'.

What am I doing wrong, or do I need to return this to amazon?

WiFi library won't work with the Yun: it's meant to work only with the WiFi shield.

On the Yun, everything but the pins is connected to the linux cpu. For the microcontroller to use all the devices available to linux, including wifi, you need to use the Bridge library. Try running example WifiStatus (Examples -> Bridge -> WifiStatus)

A drop in replacement (almost) of both Ethernet and WiFi libraries is the YunClient/YunServer pair, part of the Bridge library. Check out the docs at http://arduino.cc/en/Reference/YunBridgeLibrary.


give a class's function name as a parameter I'm trying code using FastLed library to have a 3 state ( color or brightness ) led strip, using a physical input switch, while each press will change leds color, using a predefined list.

code below demonstrate  1) create a colorPallete of two colors 2) try to use it in loop with no success.

#include <FastLED.h>

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

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

// Define the array of leds
CRGB leds[NUM_LEDS];
int colorSelctor = 0;
int birughtSelector = 25;
int inputPin = 13;
char *colorPallete[2] = {"Red","Blue"};

void setup() {
  // FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS);
  // FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
  pinMode(inputPin, INPUT_PULLUP);
}

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

CRGB::Red, etc, are just numbers. You need to treat them as such.

uint32_t colorPallette[2] = { CRGB::Red, CRGB::Blue };

And then:

leds[0] = colorPallete[0];

From pixeltypes.h:

/// Predefined RGB colors
typedef enum {
    AliceBlue=0xF0F8FF,
    Amethyst=0x9966CC,
    AntiqueWhite=0xFAEBD7,
    Aqua=0x00FFFF,
    Aquamarine=0x7FFFD4,
    Azure=0xF0FFFF,
    Beige=0xF5F5DC,
    Bisque=0xFFE4C4,
    Black=0x000000,
      ... etc ...
} HTMLColorCode;


problem using std::map. Are there known obstructing macros? I have a header file, where I try to collect global variable declarations. When trying to typedef a map I get the following error:

n file included from Dis0_10.ino:7:
/var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build8295701509021940161.tmp/globals.h:23: error: expected initializer before '<' token

relevant code snippets from global.h are:

#ifndef GLOBALS
#define GLOBALS
#include <map>

...

typedef std::map<uint8_t,uint8_t> memmap_t;

I have no clue, why this statement should fail. I consider it rather straight forward. So I think there must be some problems of this kind here. Or am I missing another include?

The C++ standard library is not available for arduino.

Some implementations of similar containers or certain functions exist on the web, but for the most part the standard library is impractical on a device with such small amounts of both RAM and program memory.

An implementation of SGI STL for AVR has been documented here: http://andybrown.me.uk/wk/2011/01/15/the-standard-template-library-stl-for-avr-with-c-streams/

map is mentioned as being particularly impractical for anything less than an arduino mega(1280). An example of maps working is included on the page so it seems like a good lead if you really must use one, but I've never done this myself so I cant guarantee it still works.


What are the different types of high-speed serial data transfer protocols, and how do they work (ex: baudrate, synchronous vs asynchronous, etc)? Otherwise worded: How do I resolve my understanding about baud rates and high speed serial data transfer?

From what I understand, serial communication is relatively slow.  By slow, I mean that the fastest common rate of transmission of data is 115.2 kBaud.

However, also from what I understand there are fast ways of transferring data serially.  I know that some serial configurations through Firewire or Ethernet can transfer data at speeds that are orders of magnitude higher than 115.2 kBaud.  These data streams are able to be read on simple computers that you can buy from Staples.  I don't know how these systems receive data at such a high speed if common baud rates are so low.

I know something is wrong with my understanding of it all.  I am new to electrical engineering and I am trying to teach myself some basic ideas for my research project - with much frustration.  I know that I need to have a system that can receive a pulse train at a minimum speed of 10MHz (hopefully up to 500MHz).  I will then program it to process this data.  The system that I currently have to receive the data is an Arduino certified product:

http://store.arduino.cc/product/E000052

Programming in the Arduino language is not a problem, I already know how to do this.  I just want to understand what I can do to receive this data stream.  Do I need something faster than this?  Or will this suffice?  I'm more interested in the theory than the device; it is more valuable for me to bolster my education than for me to solve my problem (though it needs to be solved).

Basically there are two kinds of serial: Asynchronous and Synchronous.

With asynchronous, which is what serial as in UART and RS-232 are, it's all down to how accurate a system's clock is.  Both ends of the line have to agree on the same speed (baud rate) and any deviation from that causes transmission errors.  The more accurately the two ends can agree on their baud rates the faster you can transfer data.

Note that on many systems (Arduino included) when you ask for one baud rate you actually get a slightly different baud rate.  That's due to the way that the internal UART hardware works - it divides the system clock into finer and finer bits to get as close to the requested baud rate as possible.  Lower baud rates are easer to get close to, but higher ones are much harder.  So it's "safer" to use a lower baud rate which gives more reliable communication to a greater variety of devices.

http://en.wikipedia.org/wiki/Universal_asynchronous_receiver/transmitter

The other kind of serial, synchronous, uses an extra wire for the transmitting (or master) end of the connection to send the clock to the receiving (slave) end.  The receiver uses the incoming clock to know precisely when it should look at the data line to receive a bit of data.  This is how things like SPI and I²C work, and very high baud rates can be achieved.  Speeds in the tens of megahertz are common.

http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
http://en.wikipedia.org/wiki/I%C2%B2C

Some synchronous systems (such as Ethernet), instead of providing the clock as a discrete wire, encode the clock into the data stream.  This keeps the number of wires to a minimum yet allows high speed data transfer.  The down side is that this usually means the maximum speed you can run at is actually slightly lower since the effective size of the data being transmitted is increased.

http://en.wikipedia.org/wiki/Clock_recovery


Why does a pull down resistor configuration not destroy the pin it's connected to? I don't understand why a pull-down resistor connected to ground would prevent a pin connected to 5V through a button would not destroy the pin as the current does not need to go through the resistor to get to the pin. I've tried looking online but the question was never asked and I couldn't find any information that explained how it works.
I'm asking this in the context of something without internal resistors so it would have no protection against a short circuit/being connected straight to a source.

When you have a pin in INPUT mode it is high impedance. That means that to all intents and purposes, to the outside world, the pin is not connected to anything internally.
In reality it is, but that internal connection is of such a high impedance (i.e., resistance) that it is almost equivalent to an open circuit.
It's simplest to think of an input pin as a voltmeter.  A pulldown resistor and button would look like this:

simulate this circuit – Schematic created using CircuitLab
When the button is opened the voltmeter reads zero, because one end is connected to ground, and the other end is connected to ground through the resistor.
However when you press the button the voltmeter reads the voltage across the resistor - that is, 5V - because one end is connected to ground and the other to 5V, with a resistor across it.
If you don't have the resistor then the voltmeter can't measure anything when the button isn't pressed - it's just waving around in the air without a clue what it's doing - and a wire waving around in the air is called an antenna...
The Arduino is that voltmeter. All it does is detect the voltage at the pin, it doesn't conduct any (or only a very very tiny amount of leakage) current through the pin.
Now the possibility of a short circuit comes when you set the pin to OUTPUT. If you drive the pin LOW then the pin is essentially connected to GND, and pressing the button will connect the 5V straight to GND through the LOW-driven IO pin.


Temperature sensors TMP36 and LM35 have temperature diff. (offset) in the same circuit I am trying to use the two temperature sensors TMP36 (from Sparkfun Inventor's kit) and KEYES LM35.

In read TMP36 Sensor and I convert the result to Celsius using the following code:

// TMP36 input sensor -> degrees Celsius calculation
TM36reading = analogRead(TM36sensor);
TM36voltage = (TM36reading/1024.0)*5.0;
//converting from 10mv per degree with 500 mV offset
//             (TMP36 voltage - 500mV) times 100)
TM36degreesC = (TM36voltage - 0.5) * 100;

In read LM35 Sensor and I convert the result to Celsius using the following code:

// LM35 input sensor -> degrees Celsius calculation
LM35reading=analogRead(LM35sensor);    // reads the LM35 output
LM35voltage = (LM35reading/1024.0)*5.0;
LM35degreesC=LM35voltage*100.0;

I have connected also a LCD display to monitor visually the values of these two sensors. Here is my full code. I use also a serial log. Here is a sample from this serial log (as you can see there is a difference/offset between 0.5 to 0.9 Celsius).

TM36: 17.38, LM35: 16.60 diff -> 0.78
TM36: 16.89, LM35: 16.11 diff -> 0.78
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 17.87, LM35: 16.60 diff -> 1.27
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 16.89, LM35: 17.09 diff -> 0.20
TM36: 17.38, LM35: 17.09 diff -> 0.29
mean difference between sensors: 0.48
TM36: 17.38, LM35: 16.11 diff -> 1.27
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 17.38, LM35: 16.60 diff -> 0.78
TM36: 16.41, LM35: 17.58 diff -> 1.17
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 17.38, LM35: 16.11 diff -> 1.27
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 17.38, LM35: 16.11 diff -> 1.27
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 16.89, LM35: 17.09 diff -> 0.20
mean difference between sensors: 0.71
TM36: 17.38, LM35: 16.60 diff -> 0.78
TM36: 16.89, LM35: 16.60 diff -> 0.29
TM36: 17.38, LM35: 16.11 diff -> 1.27
TM36: 17.38, LM35: 16.11 diff -> 1.27
TM36: 17.38, LM35: 16.11 diff -> 1.27
TM36: 17.38, LM35: 16.60 diff -> 0.78
TM36: 17.38, LM35: 16.11 diff -> 1.27
TM36: 17.38, LM35: 16.11 diff -> 1.27
TM36: 17.38, LM35: 17.09 diff -> 0.29
TM36: 16.89, LM35: 16.11 diff -> 0.78
mean difference between sensors: 0.93

I power the Arduino from the computer using the USB cable. When the computer is ON we have the offset that I already demonstrated above. When the computer is turned off (after computer shutdown), immediately the sensor of TMP36 falls around 1 Celsius.. And then both sensors have similar temperature.

Why there is this temperature difference between TMP36 and LM35 sensors? How can we "fine tune" these sensors to monitor the real temperature?

The sensors have different accuracy, according to their datasheets.
The TMP36 has ±2°C typical accuracy, while the the LM35 has 0.5°C typical accuracy (over 25°C).
Read the datasheet carefully and pay attention to the characteristics, more specifically to the accuracy error graphs for each sensor. At your measured temperature (~17°C), you should expect the following error (the red line is not super accurate, but should give a general clue):

LM35:

TMP36:

In addition, as Michal stated, you might have noise in your circuit, and you are not connecting the TMP36 as per the datasheet suggests (note the capacitor between +V and Ground):


Making simple on/off IR servo movement. I'm new to Arduinos and programming. I'm getting into a project and one of my tasks was to learn how to incorporate servos into Arduino and learn about sensors. I wanted to combine both, but I'm having some problems in my syntax. Can I get some help?

This is my code:

// servo test
#include <Servo.h>
#include <IRremote.h>
#define START_BUTTON //place code for button // code recieved from start
button
#define STOP_BUTTON //place code for button // code recieved from stop
button

int servopin1 = 13; // first servo
int servopin2 = 12; // second servo

int pos = 0;

int receiver_pin = 4; // output pin
int vcc = 5; // vcc ir sensor
int gnd = 6; // gnd for ir sensor
IRrecv receiver(receiver_pin);
decode_results output;
Servo Servo1;
Servo Servo2;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  receiver.enableIRIn();
  pinMode(vcc, OUTPUT);
  pinMode(gnd, OUTPUT);
  digitalWrite(vcc, HIGH);

  Servo1.attach(servopin1);
  Servo2.attach(servopin2);
}

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

    if (receiver.decode(&output)) {
    unsigned int value = output.value;
    switch(value) {
      case START_BUTTON:
        if (pos <= 180){
           Servo1.write(pos);
           delay(500);
           pos = pos + 30;}
        else {
           pos=0;
             }
        if (pos <= 180){
          Servo2.write(pos);
          delay(500);
          pos = pos + 30;}
        else {
            pos=0;}
      break;
      case STOP_BUTTON:
           Servo1.write(0);
           delay(200);
           Servo2.write(0);
           delay(200);
           break;
            }
     }
  }

  //^servo 2 positions and delays
}

I'm trying to figure out why I'm getting a the following error:

C:\Users\Alex\Documents\Arduino\Servo_test2Library\Servo_test2Library.ino:
In function 'void loop()':

Servo_test2Library:38: error: expected primary-expression before ':' token

       case START_BUTTON:

                        ^

Servo_test2Library:53: error: expected primary-expression before ':' token

       case STOP_BUTTON:

                       ^

C:\Users\Alex\Documents\Arduino\Servo_test2Library\Servo_test2Library.ino:
At global scope:

Servo_test2Library:64: error: expected declaration before '}' token

 }

 ^

Multiple libraries were found for "IRremote.h"
 Used: C:\Users\Alex\Documents\Arduino\libraries\IRremote-2.2.3
 Not used: C:\Users\Alex\Documents\Arduino\libraries\Arduino-IRremote-master
Using library Servo at version 1.1.2 in folder: C:\Program Files
(x86)\Arduino\libraries\Servo
Using library IRremote-2.2.3 at version 2.2.3 in folder:
C:\Users\Alex\Documents\Arduino\libraries\IRremote-2.2.3
exit status 1
expected primary-expression before ':' token

Up at the top of your code, you have:

#define START_BUTTON //place code for button // code recieved from start
button
#define STOP_BUTTON //place code for button // code recieved from stop
button

A #define needs 2 parts after it. The first is the new name being created, and the 2nd is the definition of the new name.

You should put the value that you expect for the START_BUTTON condition after the name, such as:

#define START_BUTTON 0x48
#define STOP_BUTTON 0x49

Or whatever your IR remote is sending.

Also, you have one too many closing braces (}) at the end.

      [...]
      case STOP_BUTTON:
           Servo1.write(0);
           delay(200);
           Servo2.write(0);
           delay(200);
           break;
            }  // THIS CLOSES THE SWITCH
     }  // THIS CLOSES THE IF STATEMENT
  }  // THIS CLOSES loop()

  //^servo 2 positions and delays
} // THIS IS NOT CLOSING ANYTHING THAT WAS OPENED


USB to Arduino to bluetooth I have a piece of equipment that has a USB output, that a flash drive gets inserted into, to collect data as the equipment completes its cycles. I need to make a device that can replace the Flash Drive and take the data from the USB port and either save onto an SD Card, to re transmit when completed, or to transmit live as the cycles complete.
I was thinking about using a UNO, & a USB HOST Shield. to receive the data. Then transmit with a wireless or Bluetooth shield.
I have a "SANDISK WIRELSS FLASH DRIVE" which works as a flashdrive, and then you can connect it to other devices through wireless transmission, problem with it is, the wireless feature disables when plugged into the usb port. If the wireless stayed connected, then this would be exactly what I needed.
Any help or ideas, sample schematics would be welcomed.

There once was once something called an "Infinite USB Memory Drive" that acted as a thumb drive that read and wrote data to a networked share over wifi.
They aren't selling those anymore, but their approach might be what you need - network share to resolve the issue of multi- device connected to same drive.
In your shoes, I'd be looking at a Raspberry Pi Zero W (the one with wireless) instead of an arduino.  More computing options means more ways to solve your problems with the same hardware.


How to convert an hex string to an array of bytes? How to convert the char array to Byte array? I tried every method but it doesn't work.

char CardNumber[8] = "B763AB23"; // Length is 8, basically it's in Hex
                                 // B7 63 AB 23

I need to convert it into Byte array to byte CardNumberByte[4];
So basically, it should be like :

CardNumberByte[0] = B7;
CardNumberByte[1] = 63;
CardNumberByte[2] = AB;
CardNumberByte[3] = 23;

I am unable to find any solution for that.

There are indeed many methods (and they all work if done right).

Is it always a lenght of 8 ? That means it is 32-bit unsigned long number.
The strtoul can convert it to a long. Use '16' for the base. If you need the seperate numbers, you can shift the unsigned long and convert to bytes or use a union.

It is also possible to do with a for statement can convert each character of the input to a value: forum.arduino.cc: convert HEX (ASCII) to a DEC int

[ADDED]
Thank you @goddland_16 for providing a full sketch. I could not stay behind and wrote a sketch with strtoul.

char *CardNumber = "B763AB23";
byte CardNumberByte[4];

void setup()
{
  Serial.begin(9600);
  Serial.println("With strtoul");

  // Use 'nullptr' or 'NULL' for the second parameter.
  unsigned long number = strtoul( CardNumber, nullptr, 16);

  for(int i=3; i>=0; i--)    // start with lowest byte of number
  {
    CardNumberByte[i] = number & 0xFF;  // or: = byte( number);
    number >>= 8;            // get next byte into position
  }

  for(int i=0; i<4; i++)
  {
    Serial.print("0x");
    Serial.println(CardNumberByte[i], HEX);
  }
}

void loop()
{
}


Send HTTP request from Arduino Ethernet to server on PC I am simply trying to send a simple HTTP request from an Arduino Uno with w5500 Ethernet Shield to a local server running on my PC.

The two are connected via a crossover ethernet cable and I am able to host a server on the Arduino that is accessible from my PC browser. Now I am trying to use the PC as a server and the Arduino as the client.

Using the simple WebClient example, I can send a successful GET request to google.com from the Arduino.

Here is what I am trying that is failing:

1 - Start a local server via running http-server in my command prompt. That successfully starts a server at 192.168.56.1:8080 that I can access via my browser

2 - Change the Web Client example to use

IPAddress server(192,168,56,1);

and change the port to

if (client.connect(server, 8080))

3 - Run this Arduino sketch. The connection fails and I don't know why. I have allowed port 8080 full input access through the Windows firewall.

Any ideas?

The answer was simple. Instead of trying to connect to the IP address of the local server (192.168.56.1) I had to use the IP address of the ethernet connection between the Arduino and the PC (found using the ipconfig command on the command prompt).


Adjusting variables in code without reprogramming? I'm a teacher, working on eliminating some difficulties of Arduino in the name of getting to the fun stuff. Namely, I am building a small Arduino powered device that will collect simple data from sensors like a DHT11, or an accelerometer. That being said, I want to pass simple settings (sample rate, sensor type, etc.) into the device with out reprogramming the board out right. I'm worried I'm over thinking the challenge. Initially, I wanted to pass the settings over serial in Python script, then save the settings to EEPROM and read them when rebooting...but sending strings over serial from Python is proving to be challenging, let alone the EEPROM.

Long term, this will run on an ESP8266 and I'd try to make a simple interface for entering the SSID and password for the Wifi network we want to connect to. Simply plug in the board over USB, run some simple little Python app that asks for SSID, password, maybe sample rate, sensor type and hit configure.

Is there an easier way to build a user interface for adjusting variables in code already running on an Arduino?

If the number of choices is limited (device types, a few selections of sample rate), you might consider a bank or two of DIP switches.


My outputs are not outputting any current at only two of my pinmodes but work fine on the others My pinMode output 5 and 6 don't works with this code but will work when they are stand alone.

What is causing the Arduino to not output anything from these outputs within my code?

#include <SoftwareSerial.h>                    // use the software serial library
SoftwareSerial mySerial(3,4); // receive data at pin 3; transmit data at pin 2
int setpoint;
float val;
int roomtemp;
int UCL;
int LCL;

float salinity;
void setup()
{
    // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(5,OUTPUT);
    pinMode(6,OUTPUT);
    pinMode(3,OUTPUT);
    pinMode(2, OUTPUT);
    roomtemp=25;
    setpoint=7.0291*roomtemp+334.73;
    UCL=setpoint+6.12;
    LCL=setpoint-6.12;
    Serial.print("Setpoint =");
    Serial.print(setpoint);
    Serial.print("Degrees Celsius");
    Serial.print("UCL =");
    Serial.print(UCL);
    Serial.print("Degrees Celsius");
    Serial.print("LCL =");
    Serial.print(LCL);
    Serial.print("Degrees Celsius");
    mySerial.begin(9600);
    delay(500);           // set data rate to 9600 baud; wait for bootup
    mySerial.write(254);
    mySerial.write(128);
    mySerial.write(254);
    mySerial.write(1);    // clear screen & move to top left position
    mySerial.write(254);
    mySerial.write(132);
    mySerial.print("LCL");
    mySerial.write(254);
    mySerial.write(139);
    mySerial.print("SP");
    mySerial.write(254);
    mySerial.write(144);
    mySerial.print("UCL");
    mySerial.write(254);
    mySerial.write(192);
    mySerial.print("S:");
    mySerial.write(254);
    mySerial.write(195);
    mySerial.print(0.072,3);
    mySerial.write(254);
    mySerial.write(201);
    mySerial.print(0.100,3);
    mySerial.write(254);
    mySerial.write(207);
    mySerial.print(0.108,3);
    mySerial.write(254);
    mySerial.write(148);
    mySerial.print("T:");
    mySerial.write(254);
    mySerial.write(152);
    mySerial.print("24.1");
    mySerial.write(254);
    mySerial.write(158);
    mySerial.print("25.0");
    mySerial.write(254);
    mySerial.write(164);
    mySerial.print("25.9");
    mySerial.write(254);
    mySerial.write(212);
    mySerial.write(254);
    mySerial.write(212);
    mySerial.print("S=");
    mySerial.write(254);
    mySerial.write(220);
    mySerial.print("T=");
}

void loop()
{
    Serial.println();
    int val=analogRead(5);
    Serial.print("Analog Value =");
    Serial.print(val);
    Serial.print("Temperature =");
    Serial.println((0.14227*val)-47.621);

    if(val<LCL) { digitalWrite(3,HIGH); }
    else if(val>UCL) { digitalWrite(3,LOW); }

    mySerial.write(254);
    mySerial.write(227);

    if(val<LCL) { mySerial.write("H= ON"); }

    mySerial.write(254);
    mySerial.write(227);

    if(val>UCL) { mySerial.write("H=OFF"); }

    digitalWrite(2, HIGH);
    delay(100);
    int analogS=analogRead(4);
    digitalWrite(2, LOW);
    Serial.println(analogS);
    delay(1000);
    salinity = 2.0955*pow(10,-19)*pow(analogS,5.8106)*100.000;
    Serial.print("Salinity =");
    Serial.println(salinity);
    mySerial.write(254);
    mySerial.write(214);
    mySerial.print(salinity);
    mySerial.write(254);
    mySerial.write(222);
    mySerial.print((0.14227*val)-47.621,1);
    Serial.println("analog value");
    Serial.print(analogRead(4));
    float target= (salinity-(salinity-.1)*.60);
    float numer=((((target)*.08585-(salinity)*.08585)/(.1-(.1*.15+salinity*.85)))*60.0);
    float denom= ((.1));
    float valve= ((numer/denom)/10.00);

    if(.096<salinity>.104) {
        delay(5000);
    }

    if(salinity>.104) {
        Serial.print("Entering DIon Function");
        digitalWrite(6,HIGH);
        delay(valve);
        digitalWrite(6,LOW);
        delay(5000);
    }

    if(salinity<.096) {
        Serial.print("Entering Saltyon Function");
        digitalWrite(5,HIGH);
        delay(valve);
        digitalWrite(5,LOW);
        delay(5000);
    }

    Serial.print("time");
    Serial.println(valve);
}

I think the problem is not in the output pin (which you say works elsewhere) but in your calculations. I made a Minimal, Complete, and Verifiable example of the part of the code that does the calculations, testing every possible reading you might have got from analogRead(4) (mainly because I found the calculations code rather obscure). Here it is:

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

void loop()
  {
  for (int analogS=0; analogS < 1024; analogS++)
    {
    Serial.print ("analogS = ");
    Serial.print (analogS);
    salinity = 2.0955*pow(10,-19)*pow(analogS,5.8106)*100.000;
    Serial.print (", Salinity = ");
    Serial.print (salinity);
    float target= (salinity-(salinity-.1)*.60);
    float numer=((((target)*.08585-(salinity)*.08585)/(.1-(.1*.15+salinity*.85)))*60.0);
    float denom= ((.1));
    float valve= ((numer/denom)/10.00);
    Serial.print(",  valve = ");
    Serial.println(valve);
    }
   Serial.flush ();
   exit (1);
  }

Testing that reveals:

analogS = 0, Salinity = 0.00,  valve = 3.64
analogS = 1, Salinity = 0.00,  valve = 3.64
analogS = 2, Salinity = 0.00,  valve = 3.64
analogS = 3, Salinity = 0.00,  valve = 3.64
... some lines omitted ...
analogS = 1016, Salinity = 6.21,  valve = 3.64
analogS = 1017, Salinity = 6.25,  valve = 3.64
analogS = 1018, Salinity = 6.28,  valve = 3.64
analogS = 1019, Salinity = 6.32,  valve = 3.64
analogS = 1020, Salinity = 6.35,  valve = 3.64
analogS = 1021, Salinity = 6.39,  valve = 3.64
analogS = 1022, Salinity = 6.43,  valve = 3.64
analogS = 1023, Salinity = 6.46,  valve = 3.64

As you can see, valve is always 3.64, so you will be doing this:

    digitalWrite(6,HIGH);
    delay(3);
    digitalWrite(6,LOW);

In other words, port 6 will be HIGH for 3 milliseconds, probably too short a time for you to notice. Ditto for port 5.

Also this doesn't do what I suspect you think it does:

if(.096<salinity>.104) {
    delay(5000);
}

That will evaluate .096 < salinity to be 0 or 1. Then it will evaluate:

0 > 0.104
1 > 0.104

This is not what you are intending, I think. Try:

if(salinity < .096 || salinity > .104) {
    delay(5000);
}

If that is what you mean, I can't be sure - maybe you mean the opposite:

if(salinity > .096 && salinity < .104) {
    delay(5000);
}

If you write things out clearly, without trying to do shortcuts, it will be much more obvious what the test really is.


How to Read Voltage Level? I want to read voltage level by my Arduino board please help in this regard. I am using this syntax.

volts = analogRead(A3);    // read the input pin
Serial.println(volts)

First off you need to convert your signal's units from analog -> voltage. Do this by using the following equation. I've modified your code so you can copy and paste it into your IDE.

float volts = analogRead(A3) * ( 5.0 / 1024.0) ;

Hope this helps! Good luck!


Can I connect to WiFi with an Arduino, "wireless SD shield" and XBee I want to create a growhouse sensor system. I have an Arduino UNO, wireless SD shield and I have just ordered a series 2 XBee XB24.

Any info I find seems to revolve around having 2 Arduinos and 2 XBee modules, why is that?

I am presuming that once I connect the XBee to the shield that I can then connect to my Arduino on the network and send and receive data, am I wrong?

I'm a developer and sysadmin but a noob to Arduino so any help is much appreciated.

The xbee network and the wifi network are both wireless networks, but, they do not communicate with each other.

You have two options.

Attach a second XBEE to your computer using one of these
https://www.sparkfun.com/products/11812
Get a WIFI shield http://arduino.cc/en/Main/ArduinoWiFiShield


Arduino error in code i'm making a project and i came across the follwing error.
Whan i'm trying to compile and upload the code i'm getting those errors:

ShiftRegisterTest1.ino:In function 'int* return_pins(int)'
displays.ino:9: error: expected primary-expression before '{' token
displays.ino:9: error: expected `;' before '{' token
displays.ino:12: error: expected primary-expression before '{' token
displays.ino:12: error: expected `;' before '{' token
displays.ino:15: error: expected primary-expression before '{' token
displays.ino:15: error: expected `;' before '{' token
displays.ino:18: error: expected primary-expression before '{' token
displays.ino:18: error: expected `;' before '{' token
displays.ino:21: error: expected primary-expression before '{' token
displays.ino:21: error: expected `;' before '{' token
displays.ino:24: error: expected primary-expression before '{' token
displays.ino:24: error: expected `;' before '{' token
displays.ino:27: error: expected primary-expression before '{' token
displays.ino:27: error: expected `;' before '{' token
displays.ino:30: error: expected primary-expression before '{' token
displays.ino:30: error: expected `;' before '{' token
displays.ino:33: error: expected primary-expression before '{' token
displays.ino:33: error: expected `;' before '{' token
displays.ino:36: error: expected primary-expression before '{' token
displays.ino:36: error: expected `;' before '{' token
displays.ino:39: error: expected primary-expression before '{' token
displays.ino:39: error: expected `;' before '{' token
displays.ino:42: error: expected primary-expression before '{' token
displays.ino:42: error: expected `;' before '{' token
displays.ino:45: error: expected primary-expression before '{' token
displays.ino:45: error: expected `;' before '{' token
displays.ino:48: error: expected primary-expression before '{' token
displays.ino:48: error: expected `;' before '{' token
displays.ino:51: error: expected primary-expression before '{' token
displays.ino:51: error: expected `;' before '{' token
displays.ino:56: error: expected primary-expression before '{' token
displays.ino:56: error: expected `;' before '{' token
Error compiling

I don't really understand why since the code (see below) should be working.

int * return_pins(int get_number)
{
static int rp[8];
switch(get_number)
{
            //DP, A, B, C, D, E, F, G
    case 48: //0
        rp[8] = {0, 1, 1, 1, 1, 1, 1, 0};
        break;
    case 49: //1
        rp[8] = {0, 0, 1, 1, 0, 0, 0, 0};
        break;
    case 50: //2
        rp[8] = {0, 1, 1, 0, 1, 1, 0, 1};
        break;
    case 51: //3
        rp[8] = {0, 1, 1, 1, 1, 0, 0, 1};
        break;
    case 52: //4
        rp[8] = {0, 0, 1, 1, 0, 0, 1, 1};
        break;
    case 53: //5
        rp[8] = {0, 1, 0, 1, 1, 0, 1, 1};
        break;
    case 54: //6
        rp[8] = {0, 1, 0, 1, 1, 0, 1, 1};
        break;
    case 55: //7
        rp[8] = {0, 1, 1, 1, 0, 0, 0, 0};
        break;
    case 56: //8
        rp[8] = {0, 1, 1, 1, 1, 1, 1, 1};
        break;
    case 57: //9
        rp[8] = {0, 1, 1, 1, 1, 0, 1, 1};
        break;
    case 65: //A
        rp[8] = {0, 1, 1, 1, 0, 1, 1, 1};
        break;
    case 70: //F
        rp[8] = {0, 1, 0, 0, 0, 1, 1, 1};
        break;
    case 69: //E
        rp[8] = {0, 1, 0, 0, 1, 1, 1, 1};
        break;
    case 80: //P
        rp[8] = {0, 1, 1, 0, 0, 1, 1, 1};
        break;
    case 72: //H
        rp[8] = {0, 0, 1, 1, 0, 1, 1, 0};
        break;
            //DP, A, B, C, D, E, F, G
    case 45: //-
    default:
    rp[8] = {0, 0, 0, 0, 0, 0, 0, 1};
    break;
}
return rp;
}

What this code does is to basicaly get an int ad input and based on this number it returns an int array. It's a very simple code which is called inside the loop() method which is located on an other file.

Also i'm using Atmel Studio 6 instead of the original Arduino IDE but i dont think it has to do something with the problem :/

What you try here:

rp[8] = {0, 1, 1, 1, 1, 1, 1, 0};

is only valid in C++11. (Before that you can initialize an array like this only upon initialization.)

Besides, as pointed out by Pete Becker, you need to declare rp as an array rather than a single int.


What is "tws_delay" and how can I use it? (with an ATTiny85) EDIT: Alright I'm stupid, I had the 2012 library installed somehow, maybe when I downloaded it indirectly from another old tutorial site. Thanks a ton to Peter Freerick for pointing that out! It finally compiled now
So I'm currently doing a little project where I have an ATTiny85 controlling some (neopixel) RGB addressable LEDs, which is controlled over i2c from an Arduino UNO Master. The goal is to make an Attiny85 into an i2c slave that receives a simple command (such as a single digit int) and decide which premade LED display program to use.
I'm using ATTinyCore, TinyWireS, and Adafruit's tinyNeopixel library for the tiny, and programming it using an Arduino UNO as ISP.
My issue is this: The led code requires a delay to change the speed of the light show. But I see in the TinyWireS example here that I should be using tws_delay instead of the normal delay.
Various googling attempts have left me nowhere to learn how to use tws_delay, what it is, or how to even declare it. I get a declaration error when I try to use the delay with the TinyWireS library included.
I would like to find a resource for learning how to declare and use this delay. Thank you for reading this far
EDIT: I have now added my code and error below, you can find the tws_delay in void loop near the bottom
// NeoPixel Ring simple sketch (c) 2013 Shae Erisson
// released under the GPLv3 license to match the rest of the AdaFruit NeoPixel library

#if (F_CPU>7370000) //neopixel library required 7.37MHz minimum clock speed; this line is used to skip this sketch in internal testing. It is not needed in your sketches.
#include <tinyNeoPixel.h>
#include <TinyWireS.h>
// Which pin on the Arduino is connected to the NeoPixels?
#define PIN            3

// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS      8

// When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
// Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
// example for more information on possible values.
tinyNeoPixel pixels = tinyNeoPixel(NUMPIXELS, PIN, NEO_RGB + NEO_KHZ800);

int delayval = 500; // delay for half a second

void setup() {

  pixels.begin(); // This initializes the NeoPixel library.
}

void loop() {

  // For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.

  for(int i=0;i<NUMPIXELS;i++){

    // pixels.Color takes RGB values, from 0,0,0 up to 255,255,255
    pixels.setPixelColor(i, pixels.Color(0,150,0)); // Moderately bright green color.

    pixels.show(); // This sends the updated pixel color to the hardware.

    tws_delay(delayval); // Delay for a period of time (in milliseconds).

  }
}
#else //neopixel library required 7.37MHz minimum clock speed; these and following lines are used to skip this sketch in internal testing. It is not needed in your sketches.
#warning "Neopixel control requires F_CPU > 7.37MHz"
void setup() {}
void loop() {}
#endif

And the error:
C:\Users\Dean\AppData\Local\Temp\arduino_modified_sketch_145294\simple.ino: In function 'void loop()':

simple:36:5: error: 'tws_delay' was not declared in this scope

     tws_delay(delayval); // Delay for a period of time (in milliseconds).

     ^~~~~~~~~

C:\Users\Dean\AppData\Local\Temp\arduino_modified_sketch_145294\simple.ino:36:5: note: suggested alternative: 'delay'

     tws_delay(delayval); // Delay for a period of time (in milliseconds).

     ^~~~~~~~~

     delay

Multiple libraries were found for "tinyNeoPixel.h"
 Used: C:\Users\Dean\AppData\Local\Arduino15\packages\ATTinyCore\hardware\avr\1.3.2\libraries\tinyNeoPixel
Multiple libraries were found for "TinyWireS.h"
 Used: C:\Users\Dean\Documents\Arduino\libraries\TinyWireS
exit status 1
'tws_delay' was not declared in this scope

tws_delay() is a function provided by the TinyWireS library here. As you can see from the declaration - void tws_delay(unsigned long); - it accepts a parameter of unsigned long, just like delay() does.
In fact, the comment on the line above that declaration says...
// Implement a delay loop that checks for the stop bit (basically direct copy of the stock arduino implementation from wiring.c)
... so, it's safe to say that wherever you would have used delay(), you can use tws_delay().
So there should be no need to declare or define it. But to simply use it. If using tws_delay() in code that includes TinyWireS.h doesn't work, I would be checking that you have a version of the library that declares/defines it. Which you should, given the example you linked, as that repo has had the function since 2012!


What are the negative PINs for on the IndustrialShield M-Duino 58 Analog I am working as an internship on an Arduino based PLC. It is the M-Duino 58 Analog from IndustrialShields. I try to figure out how it works; Reverse Engineering. But i dont know why it has negative Digital Inputs like normal Digital Input I1.0 also has a connection -I1.0.
It is probably a simple question but i cant figure it out. Hope you guys can help me.

I guess i figured it out. Seems to be the GND connections. Should read the Manual better next time.

It looks like those inputs are opto-isolated. That means that the "input" goes through a resistor and the internal LED of an opto-isolator, which then comes back out of the "-" pin:

simulate this circuit – Schematic created using CircuitLab

So "-" connects to the ground of the remote device, and the "input" connects to the signal.


How to update a variable in an ISR using Timers I'm trying to check the frequency of Timer3 using a counter. The value of the counter, declared as volatile, is incremented in the ISR and every second the sum is shown in the main loop and the value reset to zero.

The timer has been set up correctly. (If I choose a 3Hz timer I can see the led blinking)

The problem

The counter isn't incremented. Here is the output:

Setup Completed
tick: 1
tick: 0
tick: 0
tick: 0

CODE

volatile int cont = 0;

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

  pinMode(13, OUTPUT);

  // Initialize Timer
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3B = 20; // 800Hz 5; // 3 Hz
  // turn on CTC mode:
  TCCR3B |= (1 << WGM12);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();

  Serial.println("Setup completed");
}

void loop()
{
  if (millis() % 1000 == 0)
  {
    Serial.print(" tick: ");
    Serial.println(cont);
    cont = 0;
  }
}

ISR(TIMER3_COMPB_vect)
{
  //digitalWrite(13, digitalRead(13) ^ 1);
  cont++;
}

EDIT
This timer is used to read an anlog value from an accelerometer and store it in an array of float. But at the moment I'm stuck on this update issue.

SOLUTION 1
Thanks to Gerben

volatile int cont = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);

  // Initialize Timer
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3A = 20; // 20; //800Hz 5; // 3 Hz
  // turn on CTC mode:
  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();
  Serial.println("Setup completed");
}

void loop()
{
  delay(1000);
  Serial.println(cont);
  cont = 0;
}

ISR(TIMER3_COMPB_vect)
{
  cont++;
}

SOLUTION 2
Thanks to BrettM

volatile int cont = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);

  // Initialize Timer
  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count: 800 Hz
  OCR3B =  20; //800Hz 5; // 3 Hz
  // turn on CTC mode:
  //TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();
  Serial.println("Setup completed");
}

void loop()
{
  Serial.println(cont);
  cont = 0;
  delay(1000);

}

ISR(TIMER3_COMPB_vect)
{
  TCNT3 = 0;
  cont++;
}

In CTC mode the top is OCR3A, not OCR3B!

After that TIMSK3 |= (1 << OCIE3B); should also be changed to TIMSK3 |= (1 << OCIE3A);, and ISR(TIMER3_COMPB_vect) to ISR(TIMER3_COMPA_vect)

For 3Hz, OCR3A should be 5208, not 20.

Technically TCCR3B |= (1 << WGM12); should be TCCR3B |= (1 << WGM32);


Digital Sound sensor I am having trouble with my digital sound sensor.  My goal: Clap 2 times and a led goes on. So I wrote this code. I don't know if it is correct or not. This happens: If I clap, from the serial monitor I don't get one HIGH, but a few (I tried changing the sensitivity of the soundsensor, but it doesn't help), but in my code I have some conditions where only 1 HIGH at a time is allowed. Thus, I don't know if my code is incorrect, or my sensor isn't working well.  Can you guys help me please? This is my code:

int soundPin = 13;             // Digital soundPin
int ledPin = 7;
int claps = 0;                 // The amount of times I clapped
int readingState ;             // The first reading from the soundPin
int readingState2 ;            // The second reading from the soundPin
int soundDetectionTime ;       // The time after the first clap
int soundDetectionTime2 ;      // The time after the second clap
int timeBetweenSounds = 1000;  // The time between the sounds I want. There
                                  is an If-statement further on.

void setup(){
  pinMode(soundPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  readingState = digitalRead(soundPin);    // The first reading form the
                                              soundPin (digital pin)

  Serial.println(readingState);

  if (readingState == HIGH){               // If the reading from the
                                             soundPin is HIGH, then start
                                             timing. Also claps value
                                             increased by 1 and the
                                             second reading is happening.
    soundDetectionTime = millis();
    claps++ ;
    readingState2 = digitalRead(soundPin);

      if (readingState2 == HIGH){          // If the above statement is
                                              true, then this if-statement
                                              is executed. If the second
                                              reading is HIGH,
                                              soundDetectionTime two will
                                              start counting
    soundDetectionTime2 = millis();    // Also the claps get increased by 1,
                                          so now claps = 2.
        claps++;
   }
   }

   if ((soundDetectionTime - soundDetectionTime2) > timeBetweenSounds &&
claps==2){                            // If there is 1 second between the
                                         two readings and if I clapped
                                         twice, then LED is HIGH.
    digitalWrite(ledPin, HIGH);
   }
   }

UPDATE: I managed to get two HIGHs seperate from each other and the led is now on. So the problem must be the sensor giving me too much HIGHs if I clap once, like: 0,0,0,0,1,1,1,0,0. What do you guys think?

Here is a "stripped down version" of a sketch I used to replicate the Clap On, Clap Off lamp switch we had in the 1980's.  It works with the KY-038 sound sensor module you currently have. You will need to install the VirtualDelay Library.
The sound sensor module is very sensitive. A quarter turn of the potentiometer around the "sweet spot" makes a huge difference. Too sensitive, and the digital output is constantly high. If it's not sensitive enough, then you have to physically "tap" the microphone to get a high/low transition out of it.
Please note: This sketch uses delay() which is "blocking code" and it's use is usually not recommended.
#include "avdweb_VirtualDelay.h"
byte clapCounter = 0;
const byte soundSensorPin = 2;
const unsigned long loopDelay = 1;
const unsigned long clapCounterDelay = 400;
unsigned long clapCounterTimerDuration = 1000;
unsigned long previousMillis = 0;

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

void loop(){

  // Timer object.
  static VirtualDelay clapCounterTimer;

  // Get the current time.
  unsigned long currentMillis = millis();

  // Check for a clapping sound (1 ms works good). If too much time
  // elapses here, you could miss the "beginning" of the clap.
  if(myTimer1(loopDelay, currentMillis) == 1){

    // Clap detected.
    if(digitalRead(soundSensorPin) == 1){

      clapCounter += 1;

      // When the first the clap is detected, start a timer
      // to reset the clap counter to 0 after 1 second.
      if(clapCounter == 1){
        clapCounterTimer.start(clapCounterTimerDuration);
      }

      // Delay execution of the loop. 400 ms works good.
      delay(clapCounterDelay);

      // If a second clap is detected, toggle the LED ON/OFF.
      if(clapCounter > 1){
        digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
      }

    }
  }

  // Reset the clap counter to 0 after 1 second. If
  // you don't do this, you could clap once, wait a
  // minute, then clap again and the LED will change state.
  if(clapCounterTimer.elapsed()){
    clapCounter = 0;
  }

}

// Clap loop timer.
byte myTimer1(unsigned long loopDelay, unsigned long currentMillis){
  if(currentMillis - previousMillis >= loopDelay){previousMillis += loopDelay;return 1;}
  else{return 0;}
}

EDIT: To answer your question regarding the multiple High to Low transitions from the module's digital output, you can use a DSO to look at the relationship between the analog and digital signals it produces.
In the following image, the digital signal (yellow trace) and the analog signal (blue trace) are superimposed over each other. The white dashed line (E), is set to 2.8 VDC which is approximately the analog output pin's voltage with ambient room noise. Once you clap in front of the microphone, this wave form is generated.

The entire clap lasts about 5.6 ms and the module gives you 18 High to Low transitions on it's digital output pin. When the analog voltage drops below a certain voltage, the digital output goes High. When the analog voltage goes above that voltage, the digital output goes Low.
The problem is, the sound of a person clapping generates a noisy signal and the sound sensor module does not know the difference between noise and the sound you want to trigger it.
Instead of using delay() like I did, you could increment a "clap counter"  to equal "1" on the first Low to High transition of the digital output pin. Next, start a non-blocking millis() timer that waits before you read the digital output pin again. If digital out is High after 400 ms, it's your second clap so change the LED state. A second millis() timer could reset the "clap counter" to 0 after 1 second.


No change in acs 712 readings after connection to load I would like to measure the amount of power used by a 3w bulb. I am using a 9v battery to power the bulb and an acs712 current sensor to get current usage. However, i get no change in values after i connect the load and it light up.
Is my current sensor faulty or? I'm confused.

For such light and low-voltage loads you wouldn't normally use a mains rated high current amplifier like this.

Instead you would just use a simple shunt resistor in the low-side of the circuit:

simulate this circuit – Schematic created using CircuitLab

The voltage dropped across the resistor (and hence the voltage you will read on A0) is proportional to the resistance of the resistor and the current flowing round the circuit.

You want the resistor to be small enough that it doesn't overly affect the operation of the circuit, yet large enough that it drops a voltage you are able to sense at enough resolution.

For example the 1Ω resistor above, with 333mA round the circuit (3W at 9V) would drop (V=IR) 0.3 * 1 = 0.3V.

While that's not a very high voltage it's small enough to not really affect the circuit, and you can increase the sensitivity of the Arduino by using the 1.1V internal reference instead of relying on the default 5V external Vcc voltage:

analogReference(INTERNAL);

Or on the Mega2560:

analogReference(INTERNAL1V1);


Arduino Digitalwrite for while loop set My question is simple. Does Arduino set the digitalwrite() the moment it is called or at the end of the while loop. E.G.

int ledPin = 13;
void setup()
{
  pinMode(ledPin, OUTPUT);
}

void loop()
{for(int i=0; i<10; i++){
if(i%2==0){
  digitalWrite(ledPin, HIGH);
  delay(1000);}else{
  digitalWrite(ledPin, LOW);
  delay(1000);      }
}

A key point of the Arduino 'language' is every statement is completed before the next one can begin.

A simple statement has a ';' at the end of it.
Or followed by ')' instead of ';' in for (...; ...; statement) loop.

So digitalWrite() will set the pin, HIGH or LOW, before it completes and allows the next statement, delay(...) to begin.

Side note:
Actually digitalWrite() takes a small amount of time to do its work, so it is not exactly 'the moment' it is called. digitalWrite() is pretty quick, a few millionths of a second, which is usually near enough to be practically 'the moment' for most applications.


Connect two or more modules sharing the same pins? I've found some separate instructions for connecting an SD reader/writer and also instructions for connecting a RFID reader and Piezo Buzzer.  I would like to use both modules and the piezo buzzer together on the same Arduino. See below for the pin wiring details from each instruction I found:

SD Reader/Writer

3.3v goes to 3.3v on the Arduino UNO (for power)
GND goes to Ground on Arduino UNO
D0 goes to pin 12 on Arduino UNO
D1 goes to pin 11 on Arduino UNO
CLK goes to pin 13 on Arduino UNO
D3 goes to pin 10 on Arduino UNO

RFID Reader

SDA - Digital 10
SCK - Digital 13
MOSI - Digital 11
MISO - Digital 12
IRQ - unconnected
GND - GND
RST - Digital 9
3.3V - 3.3V

Piezo Buzzer

Red - Pin 8
Black - GND

Is using the same pin for more that one module ok?

pins 11 MOSI, 12 MISO and 13 SCK are SPI bus. You can connect more devices to the bus. A 'slave select' ('cable select') pin determines which device will communicate. In your table both devices use pin 10 for this. You must change one.

I recommend to wire SD reader D3 to pin 4 and in sketch use SD.begin(4).

Note: some cheap SD card adapters block other devices on the bus and can be used only as single device on the bus


Can Arduino uno adjust input square wave duty, phase and frequency with just timer-counter? Requirement:

I have input 4KHz pulse input
Divide it's frequency in half
Arbitrarily adjust phase
Arbitrarily adjust duty
Out put the modified pulse

My solution (CPU):
uint8_t cnt = 0;
uint16_t t1 = 235;
uint16_t t2 = 5;
String cmd;

void setup() {
  pinMode(3, OUTPUT);
  pinMode(2, INPUT);

  Serial.begin(9600);
  delay(500);
  attachInterrupt(digitalPinToInterrupt(2), rising_edge, RISING);
  Serial.println("PWM init");
}

void loop() {
  if (Serial.available() > 0) {
    cmd = Serial.readString();

    if (cmd.substring(0,8) == "setdelay"){
      t1 = cmd.substring(9).toInt();
      Serial.print("setting delay to ");
      Serial.print(t1);
      Serial.println(" us");
    }
    else if (cmd.substring(0,7) == "sethigh"){
      t2 = cmd.substring(8).toInt();
      Serial.print("setting high time to ");
      Serial.print(t2);
      Serial.println(" us");
    }
  Serial.flush();
  }
}
void rising_edge() {
  cnt = cnt + 1;
  if (cnt >= 2) {                           //divide by 2
    delayMicroseconds(t1);
    digitalWrite(3,HIGH);
    delayMicroseconds(t2);
    digitalWrite(3,LOW);
    cnt = 0;
  }
}

However this makes heavy use of CPU, and I need to use CPU for something else.Is it possible to implement all this with TC ?
Thanks in Advance !

this makes heavy use of CPU, and I need to use CPU for something else

The issue with this code is that is heavily uses the CPU for busy
waiting rather than for doing useful work. You should try to get rid of
those waiting loops:

Serial.readString(): see Majenko's blog post Reading Serial on the
Arduino

delayMicroseconds(): for this, you can indeed use a timer.

For the pulse generation, you can keep roughly the same logic as your
existing code: output a single pulse every other time a rising edge is
sensed on the input. This pulse can be conveniently generated by
Timer 1 on pin 9 by using a PWM mode and stopping the timer
after a single cycle. I would use inverting PWM mode, with the timer
starting at zero on the input pulse:

at t1 microseconds, a compare match sets the output HIGH

at t1+t2 microseconds, the timer overflow sets the output LOW, and
the overflow interrupt stops and resets the timer

Here is a tentative, untested implementation:
// Set the pulse timings. To be called from loop() on user's request.
void set_timings(uint16_t t1, uint16_t t2)
{
    uint16_t ocr1a = t1 * 16 - 1;        // initial time in LOW state
    uint16_t icr1 = (t1 + t2) * 16 - 1;  // timer period
    noInterrupts();  // protect critical section
    OCR1A = ocr1a;
    ICR1 = icr1;
    interrupts();
}

// Configure Timer 1. To be called from setup().
void setup_timer() {
    DDRB  |= _BV(PB1);    // set pin digital 9 = PB1 = OC1A as output
    TCCR1A = _BV(COM1A0)  // PWM on OC1A, inverting mode
           | _BV(COM1A1)  // ditto
           | _BV(WGM11);  // mode 14: fast PWM, top = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | 0;           // stopped
    TCNT1  = 0;           // reset
    TIFR1  = _BV(TOV1);   // clear overflow flag
    TIMSK1 = _BV(TOIE1);  // enable overflow interrupt
    set_timings(235, 5);  // initial timings
}

// Interrupt triggered by a rising edge of the input.
void on_rising_edge() {
    static uint8_t count;
    if (++count % 2) return;   // divide by 2
    TCCR1B |= _BV(CS10);       // start timer, clock @ F_CPU
}

// Stop and reset the timer when it overflows.
ISR(TIMER1_OVF_vect) {
    TCCR1B = 0;  // stop
    TCNT1  = 0;  // reset
}


Is programming the ATTiny85 possible in 1.5? I upgraded to Arduino 1.5.7 in hopes of using the command line interface for a larger project. However, the old package I was using to program the ATTiny85 chip with the Sparkfun Tiny AVR Programmer no longer works. I'm getting the following error:

Third-party platform.txt does not define compiler.path. Please report this to the third-party hardware maintainer.
processing.app.debug.RunnerException
    at processing.app.debug.Compiler.getCommandCompilerCPP(Compiler.java:597)
    at processing.app.debug.Compiler.compileFiles(Compiler.java:275)
    at processing.app.debug.Compiler.compileSketch(Compiler.java:642)
    at processing.app.debug.Compiler.compile(Compiler.java:125)
    at processing.app.Sketch.build(Sketch.java:1589)
    at processing.app.Sketch.exportApplet(Sketch.java:1611)
    at processing.app.Sketch.exportApplet(Sketch.java:1597)
    at processing.app.Editor$DefaultExportHandler.run(Editor.java:2397)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
    at processing.app.helpers.StringReplacer.replaceFromMapping(StringReplacer.java:97)
    at processing.app.helpers.StringReplacer.replaceFromMapping(StringReplacer.java:89)
    at processing.app.helpers.StringReplacer.formatAndSplit(StringReplacer.java:37)
    at processing.app.debug.Compiler.getCommandCompilerCPP(Compiler.java:595)
    ... 8 more

Does a package exist that will allow me to program the chip in 1.5.7?

You can download a version of arduino-tiny for IDE 1.5.x from here.


Generate 5VDC signal when external sensor input changes from high to low I am new to arduino.  I have a project in which I need an arduino to generate a +5VDC  signal in response to a change of status, (high/5VDC To low/ground) from an external source.

The external source is a stand alone receiver/transmitter set which outputs +5VDC when the transmitter is out of range and ground when the transmitter is within range.

The goal is to have the arduino output +5VDC (triggering a series of events) only when the TX is within range of the RX (signal voltage is GRND vs. +5vDC).  The series of events are controlled via a stand alone event controller which is initiated by a +5VDC signal courtesy of the arduino.

I already have a RX/TX set which outputs +5VDC when the the TX is absent and GROUND when the TX is within range.  I also have the event controller.  I only need the arduino solution.

I have an arduino UNO but I am open to other option if needed.

Solution: give me +5VDC when signal voltage (from receiver) is low (ground).

If anyone could point me in the right direction it would be greatly appreciated.  This is my first arduino project so I have much to learn.

Best regards

This is literally the simplest Arduino program possible.  I can't believe you couldn't find an example of making one pin HIGH when another goes LOW.

void setup(){
  pinMode(yourInputPin, INPUT_PULLUP);
  pinMode(yourOutputPin, OUTPUT);
}

void loop(){
  if(digitalRead(yourInputPin) == LOW){
     digitalWrite(youOutputPin, HIGH);
  }
  else {
     digitalWrite(yourOutputPin, LOW);
  }
}

All you need to do is supply the appropriate pin numbers.


How to stop uno from running program when powered on? Does anyone know how to prevent the Uno from running the last program when it's powered on?
Many times I have changed hardware and wiring without clearing the program first.  Then when I power it on to upload the new program it will run the old program until it's uploaded.  This has many potential unwanted effects when the old program is running with the new hardware installed.

The simplest thing is to upload the new program before connecting the hardware.

If this isn't practical, connect a jumper wire from the Reset pin to ground (Gnd) before powering it on. This will hold in a reset state, and the program won't run.

Then, compile and upload your program. As it starts to upload remove the reset wire. That should upload it without running any existing program.


How can I stop my Servo rotating? I have a continuous servo motor connected to my Arduino UNO. I want it to react to the Hexadecimal code received by an Infrared remote. I want the motor to rotate once in one direction and then rotate once in the reverse direction and then stop until triggered by the remote again. At the moment, the remote will cause the the motor to rotate once in one way but then it rotates continuously in the reverse direction. Any help would be much appreciated!

#include "IRremote.h"
#include <Servo.h>

int receiver = 11; // Signal Pin of IR receiver to Arduino Digital Pin 11

Servo servoMain;
IRrecv irrecv(receiver);
decode_results results;

void setup()
{
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn(); // Start the receiver
  servoMain.attach(10);
}

void loop()
{
  if (irrecv.decode(&results)) // have we received an IR signal?

  {
    translateIR();
    irrecv.resume(); // receive the next value
  }
}

void translateIR() // takes action based on IR code received

// describing Remote IR codes
{

  switch (results.value)

  {

    case 551520375: servoMain.write(180); delay(1000); servoMain.write(0);     delay(1000); break;
    default: break;

  }

  delay(500); // Do not get immediate repeat

} //END translateIR

Unlike a normal servo motor where the argument of the Arduino's servo.write(angle) method represents a position, a continuous servo motor uses the argument for speed and direction.  Most continuous servo motors interpret stop to be approximately 90 degrees.  Full, say, reverse as 0 degrees.  And full, say, forward as 180 degrees.  As stated in the above link:

  On a continuous rotation servo, this will set the speed of the servo
  (with 0 being full-speed in one direction, 180 being full speed in the
  other, and a value near 90 being no movement).

Also of interest, most continuous servo motors have an adjustment to set the "90 degree position" (full stop).  That is to say, servo motor control signals are analog, not digital!  It follows that the processor's interpretation of the "90 degree position" may not be the same as the servos' interpretation of the "90 degree position".  Hence the ability to adjust the servos' interpretation.

This picture from the parallax servo tutorials web site shows how this is done:


arduino & drivers to control 5 brushed CIM motors independently? i am a complete newbie in electronics but i'm a bit familiar with C.
i am building a machine that requires 5 little engines (12V 2.5in brushed CIM motors) & motor drivers (i need to adjust each motor's speed).
i've got an arduino UNO which i think is too small to control that many motors.
i would like to know if the setup i want was feasible to your opinion and which ardunio would i need to do that ?
i guess an Arduino Mega ?

also, i came accross this tutorial : https://howtomechatronics.com/tutorials/arduino/arduino-dc-motor-control-tutorial-l298n-pwm-h-bridge/
it explains how to configure an arduino with a driver & two motors.

in fact i want to prepare the same kind of thing but with 5 motors that i can control independently.

which hardware would you recommend to do such a thing please ?

many thanks !
regards

You should have just enough I/O with UNO, so long as you don't want to connect any other hardware/sensors.  Since this is unlikely, it would be better to use another board like Mega, but I'll provide solutions anyway in case you want to try them out:

Option 1:  For 5 motors controlled with L298N boards you'll need 15 output pins, 5 of which should be PWM.  Fortunately, there are 5 PWM outputs on the Arduino UNO on PORTB and PORTD.  The remaining 10 outputs need only be digital (PORTB has 1 and PORTD has 5).  You can use DDRC and PORTC commands to change function of the analog inputs labeled A0-A5, making them digital output, thereby gaining 6 more digital output pins for a total of 12 (more than the minimum 10 needed).
Option 2:  It is possible to use other PWM motor drivers that reduce number of pins required.  Examples are DRV8838 (link to supplier) and DRV8833 (link to supplier) where 2 wires are needed per motor channel.  As a bonus, these drivers are also significantly more compact than L298N.


Arduino which library for led 4x20 I am having an Arduino Uno and I want to add a LCD to it. My LCD is a C2042A with I2C shield on it. I tried the LiquidCrystal_I2C library but it doesnt work. I am not getting any errors the LCD is just not showing the text. I just used the example code 'Hello World' from the library. I only changed the adress from 0x27 to 0x63 because I found that with the I2C scanner.

So all in all the LCD is connected right. It shows I2C mode which is also fine and it is find by the I2C Scanner code. Which library do I have to use that it will work? http://www.wentztech.com/filevault/Electronics/Arduino/

0x63 is the correct address - the module is at 0xC6 which is the 8-bit equivalent of 0x63 (0x63 shifted left once for the read/write bit to be added).

The LCD03 uses its own custom I2C protocol, not compatible with the "normal" I2C LCD library. Instead you have to use their own special commands.

The commands are detailed here: http://www.robot-electronics.co.uk/htm/Lcd03tech.htm

There may be a library available that wraps those commands, I don't know, but you can just use the Wire library to send the commands you need to send.


ESP8266 Software serial to ATmega 328 is not properly working Thanks in advance..

We are having esp8266-12E chip and Atmega328 connected as follows,
ESP 12 pin as Tx,13 pin as Rx && Atmega328 13pin as Rx, 12pin as Tx. Everything works fine, but while communicating via serial some low pulse is being generated. We couldn't find the issue with multimeter anyway but got it by oscilloscope signal.

When this false low pulse during communication happens Atmega328 connected pins also getting low for the same duration.

We tried using separated logic execution for ESP and Atmega and both were worked perfectly, but only during communicating via Software serial its flickers getting started.

Please help us getting this resolved.

Don't use SoftwareSerial in esp8266. Connect the 328p's SoftwareSerial pins to Serial interface pins of the esp8266. ESP8266 has second Serial interface named Serial1. It has only TX (io 2), but it is enough for debug prints.

To change the firmware or sketch in esp8266 you can use ArduinoOTA library, but you should be ready to disconnect the esp8266 Serial pins from the 328p and use them for Serial upload if the OTA upload fails.

You should use logic level converter from 5 V to 3.3 V to protect the esp8266 RX pin.


How to read Ultrasonic sensor value to use and drive servo motors I would like to know how i can use my ultrasonic value in an if else statement, so i can use the value that the servo motors stop running and go in another direction when the ultrasonic sensor gets close to an object.

/*
  Digital pin 2 is connected to a switch
  Digital pin 3 is connected to a switch
  Digital pin 7 is connected to the echo port of the ultrasonic sensor
  Digital pin 8 is connected to the trig port of the ultrasonic sensor
  Digital pin 9 is connected to a servo
  Digital pin 10 is connected to a servo
  Digital pin 13 is connected to a LED

 */

#include <Servo.h> // include a special file that is needed for servo motors, do this only once

Servo motor1; // create a servo object for each motor
Servo motor2;

int echo = 7; //declare echo from ultrasonic sensor
unsigned long duration;
void setup() {
  // initialize the LED pin as an output:
  pinMode(13, OUTPUT);
    // initialize the pushbutton pin as an input:
    pinMode(2, INPUT);
    // switch 2 initialize
    pinMode(3, INPUT);
  // initialize the servo on pin 9
  motor1.attach(9);
  // motor 2 initialize
  motor2.attach(10);
    // initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
    //echo pin of ultrasonic sensor
    pinMode(echo, INPUT);
    //trig pin of ultrasonic sensor
    pinMode(8, OUTPUT);

}

void loop() {
      // the trigger pin sends a pulse
       digitalWrite(8, LOW);
       delayMicroseconds(2);
       digitalWrite(8, HIGH);
       delayMicroseconds(10);
       digitalWrite(8, LOW);
       duration=pulseIn(echo, HIGH);
      // the echo pin measures how long it took for that pulse to come back
       Serial.println(duration);
      // delay in between reads for stability
       delay(50);
       duration=pulseIn(echo, HIGH);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if(duration <=400) {
    // turn LED on:
    digitalWrite(13, HIGH);
    // turn the motors off for 2 seconds
    motor1.write(90);
    motor2.write(90);
    delay(2000);
    //turn motor 1 on for 2 seconds to make a turn
    motor1.write(180);
    delay(2000);
  } else {
    digitalWrite(13, LOW);
    //motors run when vehicle is not near objects
    motor1.write(0);
    motor2.write(180);
  }
}

First, I would make sure I have continuous servo motors that can rotate 360 degrees. Your servos will just rotate to the degree you entered if they are not continuous. Additionally, it would be more helpful if you named your pins. For example:

int echo = 7;
void setup(){
    pinMode(echo, INPUT);
}

This will help us read the code better.

I also see that you have "pulseIn" in your if statement. You must save the value to a variable with the data type of unsigned long.

//before the setup
unsigned long duration;

//keep your setup as it is

void loop(){
   digitalWrite(8, LOW);
   delayMicroseconds(2);
   digitalWrite(8, HIGH);
   delayMicroseconds(10);
   digitalWrite(8, LOW);

   duration=pulseIn(echo, HIGH);

   if(duration<=400){//check for the value
       // turn LED on:
        digitalWrite(13, HIGH);
        // turn the motors off for 2 seconds
        motor1.write(90);
        motor2.write(90);
        delay(2000);
        //turn motor 1 on for 2 seconds to make a turn
        motor1.write(180);
        delay(2000);
   }else{
        digitalWrite(13, LOW);
        //motors run when vehicle is not near objects
         motor1.write(0);
         motor2.write(180);
       }
   }

Overall: check your servos and save the value of pulseIn to a variable. You might also want to convert to centimeters by dividing duration by 58.2.