Arduino components for smartening my current doorbell I would like to modernize my current (dumb) doorbell with arduino but as this is my first project, I need some advice on what I need to accomplish this :)

So, currently I own only Raspberry Pi 3 and I plan on using openHAB on it. My current doorbell is actually an intercom so it has two different bells (one for the call and second for the bell), it has a door opener button and thats about it. My intention is to be able to mute both bells (every bell its own switch), be able to receive some kind of notification (sms/email/whatever) in case  the bell event happens, and finally, to be able to simulate a door open button via mobile.

As my RasberryPi is dislocated from the location of the intercom where this project should be placed, I would need to have some kind of wireless communication (do I need a wifi that should be connected to my router or I could be using some other kind of wireless connection [radio, bluetooth]?).

What would you reccomend for this project (components should be as small as possible and its resources should only be sufficient for this purpose).

Because you asked for recommendations I would like to recomment the solution I have at home for some years:

Auerswald doorbell speaker sorry for german product description - the a/b is important so that you could use it as analoge phone on 2! You also need a transformator as you should already have for your doorbell.
AVM Fritzbox router
Doorbell or not ....
Two Sipgate (or similar) VOIP accounts

After configuring your fritzbox router and your android phone, your phone will ring and you could talk to the person in front of your door werever you are on this planet ;-)

Just my recommendation....


How to detect if the arduino wire is still connected I have hall sensors connected to an arduino, because of mechanical movements there is some possibility that the input wire may accidentally slip out of the arduino analogin sockets. Is there any way I can detect if the wire is still connected to hall sensor  ? I don't want to solder the cables yet.

You can maybe try to see if the value on analog pins when sensors are connected (while not sensing anything) is different when not connected.
Depending on your sensors and schematic, if analog input is fluctuating, you can use this command to use pull resistor to avoid this fluctuation.

digitalWrite(Ax, INPUT_PULLUP);

If the above gets true, then you can set up a threshold for detection. Below or beside threshold value, sensor is unplugged.

Otherwise, use some vinyl duct tape.... this would securize the thing a bit!


Attempt stacking 'CAN-BUS' and 'USB Host' Shields on Mega 2560 I've run into a case of 'In theory it works, but in reality'....

I'm using the CAN-BUS Shield V1.2 from Seeed studio. Many things are written in broken english, so I'm starting to wonder if I can trust all of the information. http://wiki.seeed.cc/CAN-BUS_Shield_V1.2/

The USB Host Shield is a discontinued official Arduino model. https://www.arduino.cc/en/Main/ArduinoUSBHostShield

(I would link to the libraries, but I am unable to post more than 2 links)

CAN-BUS Pins:

AREF
ICSP (SCK, MISO, MOSI)
P9 - CS (SS)
P2 - INT
NC
IOREF
RST
3.3V
5V
Vin

USB Host Pins:

ICSP (SCK, MISO, MOSI)
P10 - SS
P7 - GPX
P8 - INT (actually RES?)
P9 - RES (actually INT?)

The only conflict I see is Pin 9 (CS on CAN, RES on USB). This is where it gets hazy... While the documentation on the bottom of the USBHost page implies that Pin 9 is RES, in the code Pin 9 is actually INT.

So, assuming Pin 9 is actually INT, I re-routed it to Pin 45 on on the Mega and changed it in the UsbCore.h file:

//typedef MAX3421e<P10, P9> MAX3421E; // old
typedef MAX3421e<P10, P45> MAX3421E; // new

Here is a snippet of the code I am running:

#include <PS3BT.h>
#include <usbhub.h>

#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

#include <Bounce2.h>
#include <Time.h>
#include <TimeLib.h>
#include <SPI.h>
#include "mcp_can.h"

const int SPI_CS_PIN = 9;

MCP_CAN CAN(SPI_CS_PIN); // Set CS pin

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

    // THIS WORKS
    if (Usb.Init() == -1) {
        Serial.print(F("\r\nOSC did not start"));
    }
    Serial.print(F("\r\nPS3 Bluetooth Library Started"));

    // THIS FAILS
    while (CAN_OK != CAN.begin(CAN_500KBPS))
    {
        Serial.println("CAN BUS Shield init fail");
        Serial.println(" Init CAN BUS Shield again");
        delay(100);
    }
    Serial.println("CAN BUS Shield init ok!");
}

The CAN-BUS Fails to init until I physically remove the USB Host Shield.

If I remove the CAN-BUS code, The USB Host Shield functions normally.

If I remove the USB Host code, the CAN-BUS Shield still DOES NOT init.

I tried to sift through the CAN-BUS init code a little, and I can only assume it's failing to communicate via SPI. What am I missing here?

I think that there is an hardware bug on the USB Master shield:
IC3, the 3-state buffer which converts MISO to 5V, is always active...
The enable pin of this 74LVC1G125 (pin 1) should be connected to the pin ss_3V3.
Then you can stack this shield with another one.


Can we use serial communication in arduino only for RX pin Can we use serial communication in arduino only for RX pin, so that I am free to use pin 1(TX) as digital I/O:

Serial.write('a');
pinMode(1,OUTPUT);
digitalWrite(1,LOW);

HardwareSerial takes over the Tx and Rx pins. However you can use SoftwareSerial.

Arduino forum user whiteglint143 made an adaptation of SoftwareSerial that does read-only.

http://gammon.com.au/Arduino/ReceiveOnlySoftwareSerial.zip

See Receive Only Software Serial  - Arduino Forum

  You can regain control over the TX or RX pins by unsetting the TXENn or RXENn bit in the UCSRnB register.

Like this?

const byte LED = 1;

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  UCSR0B &= ~bit (TXEN0);  // disable transmit
  Serial.println ("Testing");
  pinMode (LED, OUTPUT);
  }  // end of setup

void loop ()
  {
  digitalWrite (LED, HIGH);
  delay (500);
  digitalWrite (LED, LOW);
  delay (500);
  }  // end of loop

Gerben's suggestion works, in a sense. The pin flashes, but rather disconcertingly, the Tx LED on the board also flashes, out of sync with pin 1. Clearly the signal is making its way to the ATmega16U2 chip, which then flashes the indicator LED. This may not be desirable if you have something connected to the serial port, as it may be interpreted as low-speed serial communications.


Dimmer on Due: digitalWrite on one pin affects digital value of another I'm trying to make dimmer for heater using Arduino Due. I'm using a variant of this very common scheme:

My scheme has MOC3043 with zero-crossing detection.

I use two pins to control the dimmer: detectorPin to analyse input voltage wave and controlPin to drive optocoupler. The program is very simple thanks to zero-crossing MOC.

I attached an interrupt to the input detectorPin on CHANGE event. And controlPin is used as digital output. When I test detection with controlPin unplugged everything works fine. But when controlPin is connected, value which is read inside the interrupt becomes wrong! So my dimmer cannot detect any half-wave and reports errors. This happens at the moment when controlPin value is set to HIGH with help of digitalWrite() func. After nearly 40-50 milliseconds detected values go back to normal, so most of time my dimmer work as expected.

I measured current on the controlPin, it's only 3.2mA, which is lower than maximum possible current for Arduino Due.

I tested this with detectorPin = 51, and different controlPins: 52, 36, 31.

So, how do you think, what is the problem? Is my Arduino broken?

There are a few issues with your circuit.

First, you need to add a diode to your 4N25 circuit.  See EDIT below.     You should still put a diode across your 4N25 LED.  Right now, your 4N25 diode (LED) gets a high voltage across it 1/2 of the time.  Because you have 60K (30K+30K) in the circuit, the LED is likely not damaged, however the LED isn't really designed to handle reverse voltage more than 6 volts. Depending upon the reverse characteristics of the Bridge diodes (leakage current), your 4N25 LED could be experiencing greater than 6 volts.  Using devices beyond their "maximum specification" can produce unusual side effects.

Place the new diode (1N4007 is good, almost any diode will work) across the LED on your 4N25. Wire the new diode with new diode anode to the LEd cathode. Now, the LED will turn on during 1/2 cycle of the AC,  and be protected against overvoltage during the other half of the cycle.

Second,  rearrange your circuit for the Triac.  The data sheet for your MOC3043 triac driver shows a typical schematic.

Notice the 39 ohm resistor and the 0.01 uf capacitor in the circuit.  This is called a snubber and will reduce interference and voltage spikes. This type of interference is famous for disrupting low voltage circuits such as micro-controllers.

Without seeing your code, I can't say much on that.  However, I presume that you are trying to detect the zero cross, and then waiting a certain amount of time AFTER the zero cross to turn on the Triac.

  I measured current on the controlPin, it's only 3.2mA

Your 3.2mA may not be enough to drive the LED in your dimmer circuit. You will likely need 10mA to assure proper operation.  You can reduce the resistor to achieve higher current to the MOC3043.

EDIT  :  I just realized that your bridge rectifier protects the LED (4N25) from reverse voltage.


Value keeps incrementing even though loop has terminated, why? I use a double called delta and use that to turn off an LCD if delta is larger than the timeout threshold. Once that happens, delta is supposed to set to 0 and then other parts of the program run. However, delta continues to increment and I'm not sure why.
This is causing a problem because delta is used to determine if the device should "sleep". So when I try to wake up the device via button click, delta is always way past the timeout threshold and the device immediately goes back to sleep.
Any thoughts as to why? Thanks in advance.
#include <M5StickC.h>

double BUTTON_PRESS_NEXT_PRESS_TIME= .5; //Time in seconds
double MINIMUM_BUTTON_PRESS_TIME = .05; //Time in seconds
int BUTTON_PRESS_SLEEP = 3; //Time in seconds
int SCREEN_TIMEOUT = 5;
int count;

static int pressCount = 1;
static int nextPress= 1;

static bool buttonIsPressed;

void setup(void) {
  buttonIsPressed = false;
  M5.begin();
  M5.Lcd.setRotation(0);
  M5.Lcd.fillScreen(TFT_BLACK);
  M5.Lcd.setTextColor(TFT_WHITE, TFT_BLACK);

  // Datum is middle centre
  M5.Lcd.setTextDatum(MC_DATUM);
  M5.Axp.ScreenBreath(100);

  updateScreen();
}

void updateScreen() {
   char tmp[12];

  // Datum is middle centre
  M5.Lcd.setTextDatum(MC_DATUM);
  M5.Lcd.drawString(dtostrf(pressCount,4,0,tmp), 80,60,6);
  M5.Lcd.drawString(dtostrf(nextPress,3,0,tmp), 80,100,6);
}

static void evaluatePress(double d) {
   // Evaluate press
  if (d >= BUTTON_PRESS_NEXT_PRESS_TIME) {
    nextPress++;
    pressCount = 1;

    if (nextPress == 19) {
      nextPress= 1;
    }
  }
  else if (d >= MINIMUM_BUTTON_PRESS_TIME && d < BUTTON_PRESS_NEXT_PRESS_TIME) {
    pressCount++;
  }

  updateScreen();
}

void sleepLoop() {
  bool bIsPressed = false;
  Serial.println("Sleep 1");
  while(1) {
    Serial.println("Sleep 2");
    if (digitalRead(M5_BUTTON_HOME) == LOW && !bIsPressed) {
      bIsPressed = true;
    }

    if (digitalRead(M5_BUTTON_HOME) == HIGH && bIsPressed){
      Serial.println("BREAKY BREAKY");
      M5.Axp.ScreenBreath(100);

      break;
    }
  }
}

void awakeLoop() {
  double delta;
  double old_time;
  double current_time;

  Serial.println("Awake 1");

  while(1) {
    Serial.println("Awake 2");
     //Calculate delta time
    old_time = current_time;
    current_time =  millis();
    delta = delta + (current_time - old_time)/1000;

    if (digitalRead(M5_BUTTON_HOME) == LOW && !buttonIsPressed) {
      buttonIsPressed = true;
      delta = 0;
    }

    if(digitalRead(M5_BUTTON_HOME) == HIGH && buttonIsPressed) {
      buttonIsPressed = false;
      evaluatePress(delta);
      delta=0;
    }

    if(delta > SCREEN_TIMEOUT && !buttonIsPressed) {
      Serial.println(delta);
      Serial.print("BREAK AWAKE");
      Serial.println(M5.Axp.ScreenBreath(0));
      count = 0;
      break;
    }
    else {
      count++;
    }
  }

  delta = 0;
}

void loop() {
  awakeLoop();
  sleepLoop();
}

Here:
void awakeLoop(){
  double delta;
  // The rest of the function body...
  delta = 0;
}

delta is being defined as a variable local to the function awakeLoop()
and with automatic storage. This means the variable is created whenever
the program enters the function, is not implicitly initialized, and is
destroyed when the function returns.
The last statement delta = 0; has no effect, as it is setting a
variable that is going to be destroyed right away. The compiler most
likely got rid of it.
You most likely want the variable to retain its value across invocations
of the function. For this to be the case, it has to be either global
(defined outside the function) or local with the static qualifier. In
both cases, it will have static storage, i.e. its lifetime will be the
whole program run. Also, if you fail to explicitly initialize it, the
compiler will implicitly initialize it to zero.


Where can I find the source codes for the various classes and methods used in Arduino Primo? I am new to Arduino development. I am trying to connect a BLE device (Arduino Primo) with my iOS app. From the Arduino BLE examples, I understand how to initialize the BLEperipheral class and then call the setValue method to pass value to be transmitted. However I do not want to be dependent on example codes, rather I want read the source code and definitions to know about the available classes and their methods, what argument types passed etc.(not precompiled libraries with .o extension).

For my current issue, I want to know what type of arguments does the setValue take in the BLEperipheral class. Can I pass an int value(4 bytes) or it has to be a char only? These questions can be answered by reading the source code of these inbuilt libraries.

Any direction would not only help me with the current project, it would also help to tackle and understand any projects in the future, where I might use inbuilt library calls.

I have searched the internet, however not much information is available for newcomers like me.
Below is a similar question link but outdated and does not solve what I am looking for.

How can I get the source files for Arduino libraries?

Thank you for any suggestions.

The Arduino Primo is supported by Arduino nRF52 boards package. The boards packages can contain libraries special for boards handled by the package. The BLE library for Arduino Primo is included in the board package.

The location of boards packages on Windows is in hidden folder AppData in user's home directory. On my Windows computer it is

C:\Users\andrassy\AppData\Local\Arduino15\packages\arduino\hardware\nrf52\1.0.2\libraries\BLE

On Linux the 'Arduino 1.5' folder is .arduino15 in users home folder.


What phone carriers are available in the USA that are compatible with a sim900 breakout board I was wondering what carriers are compatible with a sim900 breakout board. I know it needs a GSM network (AT&T,T-mobile,?) but what networks can I use?

It needs a 850/ 900/ 1800/ 1900 MHz frequency to work but who offers that frequency? I personally could not find what frequency cell phone companies offered. From how I understand it is that T-Mobile definitely will work.I have heard several different answers about companies like AT&T and I have seen discussion about sprint (which I don't understand because they are a CDMA carrier).

I have also heard that there are other carriers (Vondafone, nextel,Ting) that might be more cost effective for people like me who are only going to be using the text messaging.

Can someone please set me straight on who I can use.

SIM900 should be compatible with both AT&T and T-Mobile. T-Mobile uses 1900Mhz for 2G and AT&T uses 850Mhz and 1900Mhz. Although both carriers are upgrading to 4G, they still support 2G devices. My personal experience is that most quadband 2G devices still work with AT&T and T-Mobile and there is no technical reason why SIM900 shouldn't work. However, there can be issues with incompatible data plans that are compatible only with their own devices. You need to be careful when selecting the contract and buying the sim card.

Nextel and Ting uses Sprint's network which is CDMA and thus wouldn't work. However Vodafone seems to be using T-Mobile's network and may work.


Is there a way to remove the 8.3 filename limitation on the SD.h library? I need to be able to create text files on my SD card that are with names longer than 8 characters (which is what the SD.h currently limits me to). A choice would be to move to the SDFat library but before considering that option, is there a way to just remove the limit on the SD.h (because my code already implements the good-old SD.h)? What would be the best way to go about this issue?

The 8.3 "limit" is not a "limit" that can be removed. It is how FAT filesystems work.  Longer filenames are a "fudge" extension overlaid on top of that fileststem structure. To be able to use them you would need to implement that extension.

Simpler to switch to a more modern implementation.  FatFS is your friend:

LFN support, including UTF
Faster device access
More efficient
Can handle more devices than just SD cards
Can handle multiple devices at once

There is an implementation here though I don't know how good it is (I use it on chipKIT where it is bundled by default).

If you can't get FatFs then basically anything is better than the SD library to be brutally honest.


Controlling a sliding tray - beginners project I have a small light metal platform about 30 cm square mounted on horizontal rails. It is well lubricated and slides easily from side to side. I would like to build a device to connect to the underside of the platform that will allow me to programatically move the platform left or right by a defined distance at the touch of a button.

While I've never used an Arduino, I've been aware of its existence for a while and felt this might be a good project to begin experimenting with it. For context, I'm a computer programmer by trade, but have limited exposure to electronics in general.

Where would be a good place to start?  Are there books that are considered the "bible" of Arduino development? Are there existing projects that  basically do what I'm hoping to achieve? Am I barking up the wrong tree and shouldn't be attempting to find a solution for this with an Arduino? Any input would be greatly appreciated.

Am I barking up the wrong tree and shouldn't be attempting to find a solution for this with an Arduino?

Not at all. For example see Reprap - a 3D printer using an Atmega1280 as the controller. As it says here:

  Arduino is an open source project that has created an easy and powerful microcontroller board based on the Atmel ATmega168. It is the brain of the RepRap electronics.

If you can make a 3D printer with an Arduino, then you can make your sliding platform gadget, which sounds simpler if anything.

  Are there existing projects that basically do what I'm hoping to achieve?

Reprap, for one.

  Are there books that are considered the "bible" of Arduino development?

This is a broad question, and your original question already has a couple of "flags" that it is too broad. I suggest you narrow it down a bit.

There are a number of books about learning Arduino. My advice is to start doing some simple projects (simpler than the platform initially) to get the hang of compiling, uploading, and generally working with microcontrollers.

Also try Google and YouTube. There are a lot of Arduino projects out there.


74HC595N in series error I want have 2 74HC595N shift registers in series.

I built this schematic

When I send a value to the first register, it is sent to the second one. I have same value on both. I change them (master/slave) but the result is the same.

I connected pin 9 on the first SR first with pin 14 on the second. I am using Johnny Five on Galileo Gen 1 with shiftRegister.send(25) to send the data.

What am I doing wrong because several days ago I made it and it worked?

If you had it working and it has changed, I would suggest trying a few changes to track down the issue. The schematic seems OK so assuming that all connections are sound, I would look towards proving the code. Maybe try a simple pure Arduino sketch designed for the 74HC595N and see if the results are the same. If not, the culprit is almost certainly Johnny Five.

Perhaps try this sketch which should work with your schematic (remap the I/O though to your 2,3,4 configuration). If the problem persists, throughly examine your connections because there is very little else which would prevent it from working - especially given that it did work a few days ago. Also, have you got another Leonardo to test with?

Finally, the schematic for the Arduino-only example shows a cap on the latch line - presumably for debouncing - which is missing from your schematic. I don't think you've damaged your registers but I wouldn't rule it out.


Ramping a stepper motor I at the moment trying smoothly move a stepper motor. The problem with the stepper motor, is that it makes a high pitch noise while it moves, or sometime a crackling noise from the motor.

So i tried ramping up the frequency of the step signal, which seemed to help a bit but not perfect. Then I tried micro stepping rather than  full stepping, which also helped a bit but still, the noise is very clear.

The motor I am using is a PK244-01A
And the driver it is connected to is this one

I am not at all sure if the ramping I do is either too steep, or completely  incorrect, but here is the code that controls the motor.

void stepper_motor::step_pwm()
{

    digitalWrite(en_pin,HIGH);

    delay(0.005);

    digitalWrite(dir_pin,HIGH);
    //LOW  - Move towards the sensor
    //HIGH -  Move away from the sensor

    delay(0.005);
    int increment = 0;
    int step_count = 0;
    while(step_count <= max_step)
    {
      digitalWrite(step_pin,LOW);
      delayMicroseconds(2000);
      digitalWrite(step_pin,HIGH);
      delayMicroseconds(2000-increment);
      step_count++;

      if(step_count >= 1)
      {
        increment++;
        step_count = 0;
      }
    }

}

Anything I could do to make the noise of the motor less significant?

I had a similar issue once before. It actually matters a lot to properly ramp up your stepper motor. Especially under load if you ramp up too steep you can loose steps.

Since you are already using the arduino environment I suggest you could use the AccelStepper library.

I lets you set the acceleration and max. speed parameters nicely and uses a properly calculated ramp.


Arduino Serial.readString() trouble Hello everyone I write my code and have some troubles.
When I write on in my serial monitor my buzzer condition wasn't changed.
Can you help me realize the reason. I wrote code with int type and it works with Serial.parseInt() function properly.
String ask="Please enter buzzer condition";
int buzzerPin=2;
String state;
void setup() {
  pinMode(buzzerPin,OUTPUT);
  Serial.begin(115200);

}

void loop() {
 Serial.println(ask);
 state=Serial.readString();
 Serial.println(state);
 while(Serial.available()==0){

 }
 if(state=="on"){
  digitalWrite(buzzerPin,HIGH);
 }
 if(state=="off"){
  digitalWrite(buzzerPin,LOW);
}
}

You need to use Serial.readStringUntil('\n') instead of Serial.readString if you use the Arduino IDE's serial monitor (where a \n is added as termination character when you press enter).
Also remove that while(Serial.available()==0). It will wait as long as there are any bytes in the serial buffer and as you don't Serial.read() within the loop, the buffer will not be emptied. So, if anything is received while Serial.println(state) is called or if you send two termination characters, the program will be stuck in that loop.


How to get location of the hand indoors I made a glove that tracks the positions of the fingers, but I don't know how to get the location of the hand relative to the person using them. Any suggestions? It should be quite accurate but I would really like to make even a rough prototype of it.

Ps. I'm using a Arduino Nano (atmega328p) to send and process the positions of the finger to a Java application through serial if you wanted to know.

The only way to check the relative position is, first to define, what is the absolute position of a person, is it his other hand, his heart, his head, his foot?

When you defined the absolute position of the person, then you need to use a sensor at that absolute position that can measure the current position, e.g. GPS (if outside), but this is not accurate.

You also can use a gyroscope or device similar to what you use for the glove. When you initially keep them together you now the relative position (around 0.0). Than you can track movement differences of both the glove and the absolute position, send it to the glove (or vice versa) and calculate the difference. There might be calibration issues.

Another way is to use a camera and continueously check for a line of sight signal (IR, led), but this also can have issues (like distance measurement, what if there is no line of sight etc).


Increasing number of iterations not increasing time I am using Arduino Uno with Atmel Atmega328. I am using micros() function in Arduino IDE to measure time taken for execution. Here is my code:

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

void loop() {
    unsigned long a = micros();
    for (unsigned long j = 0; j < 100; ++j);
    Serial.println ((micros() - a));
    delay(1000);
}

The output comes as 4. But if I increase the number of iterations in the for loop to say around 1000000000 it still shows that for loop takes same time of 4. Is there a function which I can use to measure time properly in arduino?

The compiler has realized that your loop doesn't do anything useful and therefore optimized the whole thing away. Thus you are just timing how long it takes to do nothing. (You didn't get a result of zero, because calling micros will itself take time).

BTW, the granularity of micros is 4 µs, so you won't get a reading of 1 or 2. The code actually probably only took a couple of microseconds.

You need to do something that the compiler thinks "does something", like this:

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

volatile byte b;

void loop() {
    unsigned long a = micros();
    for (unsigned long j = 0; j < 100; ++j)
      b++;
    Serial.println ((micros() - a));
    delay(1000);
}

By making b volatile the compiler cannot decide that b isn't doing anything useful, so now the timings make sense.

I got 72 for 100 iterations and 144 for 200 iterations.

  Is there a function which I can use to measure time properly in arduino?

Your time measurement is fine. Your interpretation of the results indicates you didn't realize how smart the compiler is. :)

You can see what the compiler did if you examine the generated code:

    unsigned long a = micros();
  d8:   0e 94 d2 00     call    0x1a4   ; 0x1a4 <micros>
  dc:   6b 01           movw    r12, r22
  de:   7c 01           movw    r14, r24
    for (unsigned long j = 0; j < 100; ++j);
    Serial.println ((micros() - a));
  e0:   0e 94 d2 00     call    0x1a4   ; 0x1a4 <micros>
  e4:   ab 01           movw    r20, r22
  e6:   bc 01           movw    r22, r24

As you can see, between the two calls to micros there isn't any sort of loop.

To find the assembled code you can follow the steps documented here.

Basically, turn on "verbose compiling" which will show near the end of the verbose output the full pathname of the ".elf" file. Then use a command (terminal) window to enter this command:

avr-objdump -S xxx.elf

You may want to redirect the output to a file:

avr-objdump -S xxx.elf > myfile.txt

Depending on how the Arduino IDE was installed you may have to find the pull pathname of avr-objdump and use that instead of just the program name.


put_index = (put_index + 1) % 100; Can someone interpret the code in the Title line for me?  Specifically the function of the "%" sign?  It is a line having to do with a 100 element circular buffer.

The % is the modulo operator in C/C++, which basically means:

Divide the value to the left of the % by the value to the right of it
Discard the quotient and keep only the remainder.

For instance, 10 % 5 = 0, because 10/5 = 2 with no remainder. Whereas 11 % 5 = 1, because the remainder of the division is 1.

In your case, the modulo operator is likely being used to keep the value of put_index less than 100 at all times. If it became 100 because of the operation put_index = put_index + 1, then the modulo operation would make the 100 into 0, so put_index will keep incrementing 0–99 repeatedly.


Is it possible to transmit Longitude and Latitude via RF433MHz? I want to make a drone project, and to that I will use arduino as the platform. My plane is to use a Play Station controller to control the Drone in the air. In addition to that I want to connect a GPS-module. My question goes, is it possible to transmit the longitude and latitude from the GPS via the RF 433MHz to the receiver? When received the longitude and latitude how can I transmit them further to the Smartphone and display the data on google maps? I suggest it could be possible through the Xbee, but I am not sure.

I would like if someone can confirm my idea, if not bring me a better way to do that.

In the image below, you can see the diagram of my design.

If you are using Xbee modules in your project, why add 433MHz RF, just for the sole purpose of transmitting the location?  With the 433Mhz, you will have to implement error-correction yourself.


Can't stop SG90 spinning I have a SG90. I just want it to spin 360° and stop, that's about it. This seems impossible.
I have tried the sweep example:
 by BARRAGAN <http://barraganstudio.com>
 This example code is in the public domain.

 modified 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

This works fine.
I read somewhere that for 360 motors the variable in myservo.write() is actually just the speed. So I tried:
void loop() {
    myservo.write(0);              // tell servo to go to position in variable 'pos'
    delay(2000);                       // waits 15ms for the servo to reach the position
    myservo.write(180);              // tell servo to go to position in variable 'pos'
    delay(2000);
    myservo.write(0);              // tell servo to go to position in variable 'pos'
}

The motor rotates several times then spins the other direction and repeats doing this.
What do I need to do to make it complete 1 rotation and stop?

TL;DR: Can't be done.
On a servo modified for continuous rotation, the signal you send sets direction and speed, not rotation angle. You can stop it, but you can't set an angle.
The sweep example will turn a continuous rotation servo in both directions, but I doubt it hits the angles you send it; it will just adjust speed and direction.
Without external hardware and feedback, like a limit switch, or a rotary encoder, there is no way of knowing what angle the servo is at, and no way to rotate to exactly 360° other than experimenting and "guessing" based on time and rotation speed.
You can then stop it by setting it to the PWM value for 90° or center position, which should set the rotation speed to 0.
On a servo, you can't have both continuous rotation with a set speed, and a set angle of rotation, without extra hardware.
Maybe a stepper motor would be a better choice for your application, or a "normal" servo with a gear that gives you the required rotation range.


Pressure Sensor and Arduino I am currently working on reading pressure values using a tekscan a201 sensor. The sensors I have are limited to 25lbs.

My plan is to use eight on these sensors of them with a arduino Mega. Since I am measuring the resistance, I am thinking of making a 8 similar voltage divider circuits and grabbing the voltage reading via arduinos analog pins.

At the moment, I am not sure how to convert these readings to engineering units. Any ideas?

I have not previously met the Flexscan sensors but from the datasheet it appears that there are versions of the A201 rated at 100 pounds are you committed to the 25 lbf version?

A201 datasheet here

Here is a 15 page user manual thatexplains how to produce a voltage output using a single opamp per sensor - bottom of page 9.

Many idea starters here

What is your application and why do you wish to use these sensors. These seem to be a low accuracy alternative to eg load cells and seem to be expensive for what you get. If you need 8 for your task a loadcell based solution may e cheaper.


Precise rotation (steering direction to a given angle) on obstacle avoidance robot Forgive my lack of knowledge of some robotic related terms, but the way my two wheel drive robot steers is simply by having each wheel move at different speeds; for left, for example, the left wheel moves while the right one stays stationary for a given delay of time and vice versa.
but I want to make my obstacle detection a little more sophisticated with the following logic:

As the robot moves, scan the environment using an ultrasonic sensor(60 degrees to left and 60 degrees to the right) and using a simple max finding algorithm find the optimal angle i.e. angle at which the ultrasonic reading was highest. and then I want to find a way, using the same system of vehicle rotation if possible, turn to that specific angle proceed to move forward and scan simultaneously.

what I aim to achieve in the end is smoother obstacle avoidance as compared to the most common stop when close to obstacle -> turn left or right -> move and loop

The only way you can know how far you have turned, with any form of accuracy and, more importantly, repeatability, is by employing some form of feedback.

In other words, to work out how far you have turned you need, first, to know how far you have turned.

The simplest method is probably to use some form of monitoring on the wheels themselves. That could be an optical encoder to give a nice high resolution "number of degrees the wheel has turned", which can be coupled with the circumference of the wheel to calculate the distance travelled (which can then be used with some simple trigonometry to work out the angle you have turned through) or a more coarse "magnet on the wheel + hall effect sensor" to give you the number of revolutions the wheel has gone through (not very accurate and only really any use at higher speeds when there will be lots of revolutions. Maybe this method would be better on the motor before the gearbox that drives the wheel?)

However, do you really care that much anyway? Are you over thinking things a little too much?

Surely a simpler method would be to first turn left an arbitrary amount (somewhere around 60-degrees-ish, you're not really worried) then sweep from left to right (a distance of somewhere around 120 degrees in total) looking for the furthest distance. Once you have completed your sweep you then just reverse your turn direction until you read the same (or within a certain tolerance) distance at which point you will be facing your longest space.

All that can be done just with spinning the wheels either for a pre-defined period, or until a specific reading has been obtained. No need to worry about precise angles or anything fancy like that.


Uploading... forever This is my code:

const int trigPin = 4;
const int echoPin = 2;
const int trigPin2 = 6;
int incomingByte;
int val, val2;
const int echoPin2 = 7;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  pinMode(trigPin2, OUTPUT);
  digitalWrite(trigPin2, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin2, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin2, LOW);

  pinMode(echoPin, INPUT);
  pinMode(echoPin2, INPUT);

  val = digitalRead(echoPin);
  val2 = digitalRead(echoPin2);

  if (val && val2 == HIGH) {
    Serial.println("Elephant on tracks");
  }

  if (Serial.available() > 0) {  // if the data came
    incomingByte = Serial.read();
  }
  // read byte
  if(incomingByte == '0') {
     digitalWrite(trigPin, LOW);
     digitalWrite(trigPin2, LOW);
     Serial.println("The system is OFF.");  // print message
  }
}

Anyhow, I click upload, and as the title of this question says, have to wait forever.
Not only this code, nothing gets uploaded. It was working just fine a week ago.
I run a Windows 7 64-bit system, and have an Arduino Uno R3.
Does anyone have any suggestions?

From your code, I assume that the bluetooth module is connected to pins 0 & 1 on the arduino. These pins are to be kept free/floating/not connected to anything if you need to upload code to your board.

Use software serial in such cases reduces the headache


how to set the delay on for 7 hours? For my application I need to simulate the sunlight including the rising and setting of the sun.

I have a program that will light up some LEDs slowly over a period of time but I need to know what to type in the (delay on) to keep the lights on for 7 hours?

Will it work if I just replace delay(1000) with delay(25200000UL) ?
I don't want to run anything else at the same time and don't want to use or understand millis().
Thanks for any help.

Yes, absolutely, it should work. But your code will be easier to read if
you use some constants, like:

const unsigned long SECOND = 1000;
const unsigned long HOUR = 3600*SECOND;

delay(7*HOUR);


Use Arduino's PWM to control motor direction? I'm looking for a way to allow Arduino to control a motor using PWM.

So far what I have gathered is that using Arduino's PWM sets the digital value of 255 to 5v and 0 to 0v.

However what I am looking to do is to set the motors to stop at 2.5v, move forward as it approaches 5v and move backwards as it approaches 0v.

Any suggestion on how I would go about accomplishing this will be highly appreciated.

You seem to have misunderstood PWM here. It's actually a digital signal which is constantly pulsing on and off very quickly (several hundred times per second). You don't actually change the output voltage at all -- it's only ever HIGH or LOW (+5v or +0v). The thing you change is how long the signal is HIGH for on each pulse.

This page gives a deeper explanation: http://arduino.cc/en/Tutorial/PWM

When you're controlling a DC motor, this approach is actually better than varying the voltage. The constant pulses still make the motor turn at an adjustable speed, but without losing torque. PWM is also useful for controlling the brightness of LEDs, which don't respond so well to changes in current/voltage.

To address your original motor control question, there's no sensible way to change the motor's direction using the PWM value. You will need some additional circuitry which is able to reverse the polarity of the connections to the motor (meaning your PWM value just controls speed, and doesn't care about direction).

An H-bridge is the usual approach for this. Here's a fairly good tutorial which covers the basic principles: http://www.instructables.com/id/H-Bridge-on-a-Breadboard

Obviously you'd need to modify it for use with your Arduino project. The push switches could easily be replaced by digital signals from a couple of Arduino pins. The motor's power supply would be controlled by the PWM signal. You'll need an extra transistor for that, because you can't safely power the motor directly from an Arduino pin.


How would I establish a serial connection with python without using the serial monitor? How would I establish a serial connection with python without using the serial monitor?

What I want to do is give my python script some input and have the arduino do something (blink for example)

I also want to be able to read in data with the arduino to give it to my python script.

What modules for python would be useful? I'm just starting out and don't have much of an idea for this one.

I am using a windows7 machine with python 2.7.6 and have an UNO board and a Leonardo board that I want to be able to use.

This question is about Python not Arduino... Before asking here please ask GOOGLE

Anyway...

This is the answer Arduino and Python

Python code:

## import the serial library
import serial

## Boolean variable that will represent
## whether or not the arduino is connected
connected = False

## open the serial port that your ardiono
## is connected to.
ser = serial.Serial("COM11", 9600)

## loop until the arduino tells us it is ready
while not connected:
    serin = ser.read()
    connected = True

## Tell the arduino to blink!
ser.write("1")

## Wait until the arduino tells us it
## is finished blinking
while ser.read() == '1':
    ser.read()

## close the port and end the program
ser.close()

Arduino code:

// Open a serial connection and flash LED when input is received

void setup(){
  // Open serial connection.
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  Serial.write('1');
}

void loop(){
  if(Serial.available() > 0){      // if data present, blink
    digitalWrite(13, HIGH);
    delay(500);
    digitalWrite(13, LOW);
    delay(500);
    digitalWrite(13, HIGH);
    delay(500);
    digitalWrite(13, LOW);
    Serial.write('0');
  }
}


Drop alpha character from serial input I receive strings over the serial port like so:

VLT=53.0, AMP=-30.2, AHR=-10, SOC=98, TMP=136, STS=192

I want to reduce the use of string functions with the idea of dropping all non-digits, keeping numbers dot and comma, to get this:

53.0,-30.2,-10,98,136,192

in an array and simple read [0], [1], etc.

Regular expressions would be idea, but do not exist like in PERL.
Any hint would be much appreciated.

Relevant code used:

    char inByte = SerialPortOne.read(); // read byte
    strRecordIn.concat(inByte);         // add byte to receive buffer
    for (int i = 0; i <= 3; i++) {    // VLT, AMP, AHR, SOC
    strWord = getValue(strRecordIn, ',', i);  // get data item from RecordIn array
      strWord.remove(0, 4);           // remove field identifier (1st 3 char plus =)
      strRecordOut += ',';            // add delimiter
      strRecordOut += strWord;        // add value
      strWord = "";                   // reset strWord
    }

Ideally:

    char inByte = SerialPortOne.read(); // read byte
    if (inByte = [%d.,]+) {
      strRecordIn.concat(inByte);       // add byte to receive buffer
    }

If you just want to remove the letters:

#include <ctype.h>

char inByte = SerialPortOne.read();  // read byte
if (!isalpha(inByte)) {              // not letter
    strRecordIn.concat(inByte);      // add byte to receive buffer
}

Or you may test it for isdigit() and explicitly compare to ',' and
'.':

if (isdigit(inByte) || inByte == '.' || inByte == ',') {
    strRecordIn.concat(inByte);      // add byte to receive buffer
}

C.f. the documentation of
<ctype.h>.


Arduino as Slave | SPI | Answers too late I hope you can help me :)

I am communicating between Raspberry Pi 3 and Arduino Uno with SPI. I am using the Arduino as slave and it works pretty fine. The only problem that i have, is the following:

For receiving data from the Arduino, my Raspi sends a byte. But i always have to send 2 bytes for the correct response. Is it even possible for the Arduino to response on the first byte?

Sorry for my english

Because of the way SPI works, the slave cannot respond to the first byte in a meaningful way. It can send something (eg. 0x00) but not a response.

See my page about SPI. During an SPI transfer each bit is sent, and a bit received, simultaneously, as in this graphic:

You can see that as the first bit is received by the slave, it also has to send a response. There is no way that this response can react to the 8 bits, 7 of which haven't been received yet, by the time it has to send the first bit of response.

  But i always have to send 2 bytes for the correct response.

You don't have to send 2 bytes all the time. For example, you can send one byte (eg. "send me the temperature") and then send zeroes after that, while you read back a (say) 4-byte temperature. So in this case you send 5 bytes to get a 4-byte response.


Changing parameters in Arduino without the IDE I’m installing Arduino-based well monitors in my local community.  Each well is different and has slightly different parameters and several hardware variations.  Currently, when I need to make a program change I have to uninstall the Arduino, bring it back to my computer, reprogram it, then reinstall it.  I’m developing these units as I go so there are various refinements that arise as well. I’d love to be able to reprogram a unit in place.  It seems like it could be done with another Arduino but I don’t currently have the skills for that.  The second, less flexible, method would be to use dip switches to select various options.  This option is attractive but would limit me to only the options that I know of at programming time.  Is there a third option I haven’t thought of?  Has anyone else tried programming one Arduino from the other?
Edit: I’m primarily using Unos but I’m working on a low power version that will use a Mini Pro. The units are accessible as far as USB cables and such. However I don’t own a laptop.

Sounds like you need a Standalone programmer. I offer one, it loads the target device from a program you select on SD card.  Up to 256 programs can be stored on 1 card.
Check it out here  www.crossroadsfencing.com/BobuinoRev17/Programmer.html


Arduino - manually ceate objects (e.g. WiFi library) By default, if i include the WiFi library, the object WiFi will be registered globally. How can i disable this behavior without changing the library file itself? (removing the definition "extern ...")
Or is there a way to delete the objects right after the inclusion? I just want to create the object manually when needed to save memory.

I am not sure, if it would save enought memory to be worth the problems (it is just few bytes, buffers are created anyway), but lets say so.
Then you need modify the library to not creating the object, as it is allocated statically and cannot be removed later (and reclaim its memory). To protect all other projects it would be probably best to use special #define to disable it only in memory critical projects - so the Wire.h should contain something like

#ifndef EXCLUDE_WIRE
extern TwoWire Wire;
#endif

and your program (critical.ino) should start with

#define EXCLUDE_WIRE
#include <Wire.h>

and then somewhere in loop / other function use

TwoWire Wire;

as local variable. If you need to call other functions with it, then you have to send its address as a parameter.

Anyway you will not save nearly any memory, as nearly all variables in TwoWire ((and namely buffers) are static and so class variables and so are common for all instacies of TwoWire and allocated automatically if there is (possibly used) any instance of TwoWire anywhere in your program.

So it would be better to create your own library to use the same functionality, but make sure, that all such variables are instance variables and properly created and released at the right time. This would also allowe for changing the buffer sizes, if needed.

As it is under LGPL 2.0+ you are legally allowed to do that (provided you fullfill all licence conditions).


Communication between two arduinos over wifi esp8266 I have two arduinos one is Arduino Mega while other is Arduino UNO and I want to send data from UNO to Mega and vice versa over wifi using two ESP8266 wifi modules without use of any router in between, so what is the simplest procedure I can use to do this? Moreover how can I do this with a router in between?

The simplest solution is to turn on Access Point Mode on one of Wifi modules. and the other one has to be set to Station Mode in order to connect to the first one.

In case you want to add a router, just set both ESP8266 modules to Station Mode and connect them to the router.

Also, I would recommend replacing the Original Firware (AT firmware) of ESP8266 with NodeMCU Firmware. It uses lua language to write programs directly to ESP8266 which means that you can even make 2 ESP8266 modules talk with each other without even using Arduino.


Securing ESP8266 connections In my setup, I've got a number of ESP8266 devices around my home controlling various devices like my boiler and some lights.

They're all controlled by a central smart hub on a Raspberry Pi with a static's IP address.

This works great, but I'm increasingly concerned of the security implications of this. Communication between the Pi and the various ESP8266s is currently done over HTTP, with all the commands simply in the URL the Pi requests from the web servers.

As such, anyone on my network could theoretically control these smart devices using a simple curl request.

Whilst I have a strong Wi-Fi password, and am using WPA2 encryption, I would feel much more comfortable if communication with the ESP8266s was controlled in some way. E.g. in the same sort of way you can only connect to an SSH server using public key encryption if you have the right private key.

Is something like this possible to implement on an ESP8266? I've done some searching and only found articles about HTTPS which doesn't seem like it would solve my problem.

Thanks in advance,
Rocco

The simplest method is to encrypt your communication channel using some secret key.  You could use the built-in AES encryption functionality, which would mean that only people that know the key could encrypt a request in such a way that the device at the other end could decrypt it.

You would think that SSL (HTTPS) would do the job, but that only provides interception security, not authentication. Of course for even more security you can combine both HTTPS and AES encryption.  One for overall encryption, and the other for encryption-based authentication.


millis and micros always returns 0 (or other constant) On an Arduino Uno, I have a sketch akin to this:

void setup()
{
    // Generate some PWM signal on Pin 5, using Timer 0.
    pinMode(5, OUTPUT);
    TCCR0A = 0b00110011;
    TCCR0B = 0b00001000;
    OCR0A = 0x80;
    OCR0B = 0x20;
    TIMSK0 = 0b00000100;

    Serial.begin(115200);
}
void loop()
{
    // Just write the result of millis to the terminal.
    unsigned long ms = millis();
    char s[100];
    sprintf(s, "%lu\r\n", ms);
    Serial.print(s);
}

Setup timer 0 to generate a PWM signal, setup the serial port, constantly print the result of millis() to the terminal.

The numbers printed to the console do not increase as expected, but stay "0".
Similarly, if I use micros, "4" is printed constantly.

How's that?

millis and micros appear to use timer 0 internally. Using that timer to also generate a PWM signal messes with their ability to function properly.
The solution is to either use a different timer to generate the PWM signal, or to roll a custom equivalent of those functions.

Why does the official arduino documentation not specify that millis and micros occupy timer 0?
Why are there no Google results mentioning timer 0 when searching for "arduino millis returns 0", "arduino millis constant", "arduino millis not counting" and the like? (There are results with the same symptoms, but for different reasons.)
Who knows.


I want a couple of servos to listen for P.C. input (data from OSC protocol), can I bypass having to use an Arduino? ...and whack a stripped usb cable straight into a prototype board?

by bypass having to use an arduino I mean any kind of sheild? polulu would be perfect but im trying to avoid needing any of this.

My issue for finding tutorials and documentation on the subject is not quite knowing what keywords to search for, could someone point me in the right direction?

If I understand your question correctly you're asking if you can control servos with OSC and no microcontroller.
OSC is a protocol used for networking and communication between synthesizers, similar to midi in that, but totally different in the way OSC sends data which looks a bit like XML.
There's a couple of problems here:
1. Servos will not respond to OSC-signals. You could use MAX/MSP to generate servo-pulses from the OSC. The problem arises whan you are going to send this to the servos using usb.
2. USB, a fast data-transmission technology, is not suitable to be connected straight into a servomotor.

Arduino uses an atmega16u to transform the data from usb to serial (called a usb to serial programmer) for programming and communication. Then the microcontroller (atmega168/328) takes this and creates a pulse and a signal for the servo-motors.

To control servos without a micro-controller using USB is impossible.

It is be possible to control electronics using the serial-port and low-level coding. Used to do stuff like that on a Commodore 64 a time ago. Before these affordable, stable, reliable avr, arm and pic programming cards came out.

A tip: It is possible to load a program onto an atmega168/328 using a Arduino UNO or similar. Take the chip off of the programming card(ie. the Arduino UNO) and create a stripped down version, containing the micro-controller chip, 16kHz crystal, some capacitors and an usb to serial converter/ftdi-cable.

Regards
Krister Borge


Is setup and loop provided for convenience? Arduino sketches usually feature a setup and loop function. Are these functions only provided for convenience or do they actually have special purposes? (e.g.: are some operations disallowed or allowed in setup and loop)

Are these two pieces of code equivalent:

Classic

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

void loop() {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(1000);
    digitalWrite(LED_BUILTIN, LOW);
    delay(1000);
}

Without loop

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

    while(true) {
        digitalWrite(LED_BUILTIN, HIGH);
        delay(1000);
        digitalWrite(LED_BUILTIN, LOW);
        delay(1000);
    }
}

void loop() {
}

Is it possible to write code without either setup or loop, providing, for example, a main method or other entry point?

Those pieces of code are pretty much the same.

If you look at the Arduino source code you'll see:

setup();

for (;;) {
  loop();
  if (serialEventRun) serialEventRun();
}

(I'm not sure what serialEventRun() does.)

I don't think you can 'overload' the main function declaration. Also note that the main function calls init, which e.g. configures the timers, so millis() etc. will work.


Diffrence between running once and infinite const int ledPin = 12;

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

void loop(){
    if (Serial.available()) {
        light(Serial.read() – '0');
    }
    delay(500);
}

void light(int n){
    for (int i = 0; i < n; i++) {
        digitalWrite(ledPin, HIGH);
        delay(100);
        digitalWrite(ledPin, LOW);
        delay(100);
    }
}

by Oscar Liang

awesome little piece of code which taught me how to setup connection by serial. yet one part I don't understand fully. Why does this line:

  light(Serial.read() – '0');

make the code run once,
and this line an infinite times.

  light(Serial.read());

has this something to do with binary? I don't get why subtracting the string 0 would run the code once.

Thanks in Advance!

Serial.read() -'0'

Such code is often used to convert a character to a digit (e.g. int).

Like if the character is '2', than '2' - '0' = ascii 50 - ascii 48 = 2

However, if you use

Serial.read()

the value will be 50 instead of 2.... maybe looping 50 times (or 48 to 58, for values 0 to 9) will give you the impression it runs infinite?


string.indexOf() always returns a non-zero value I am developing a hardware project which contains a facility to change the stored password by any user, if he/she knows the current password.The new password is stored in arduino eeprom. In the main screen, if the user enters the current password, door is unlocked from inside. . The issue faced here is that the point where current password is entered by user, it works fine, but I want to check that '#' is not entered by user in the new password which is not performed properly.

Because in the main screen, when user presses '#' key, change password function is called up, where user is asked to enter current password.

Here is the screenshot of the circuit prepared from fritzing.

The code snippet for entering new password is as under.

lcd.clear();
lcd.print("New Passkey:");
lcd.setCursor(0, 1);
while (j < 4)
{
  char key = keypad4x4.getKey();

  if (key)
  {
    new_password[j++] = key;
    lcd.print(key);
    tone(buzzer, 1000, 50);

    if (j == 4)
    {
      lcd.print("4 reached");
      delay(1000);
      new_password[5] = '\0';
      String str = String(new_password);
      if (str.indexOf('#'))    /** this condition comes out to be true always i.e. always returns a non-zero value**/
      {
        tone(buzzer, 200, 700);
        lcd.clear();
        lcd.print("Invalid Entry");  /** It is printed everytime on lcd**/
        delay(2000);
        key = 0;
        changePass();
        break;
      }
      else  /** this block is not entered, so new password is not saved in EEPROM **/
      {
        for (int i = 0; i < 4; i++)
        {
          EEPROM.write(i, new_password[i]);
        }
        lcd.print(" Done......");
        delay(1000);
        break;
      }
    }
  }
}

and

new_password[5] is used to store new password entered by user.

Now, I am using a string variable to store this new password.

I am using  string.indexof() function to identify whether this new password contains a '#' character anywhere in it.But it seems that when I put this in an if block in code, it becomes true everytime.I have added comments at respective positions to highlight the problem faced by me. I have tested this code in Proteus simulator, and actual project too.

So, my issue is this one, even if correct password is entered by user,without '#', then also, string.indexOf('#') condition becomes true(returns a non-zero value everytime) and thus even valid password is not saved in EEPROM.
I guess I was able to explain my query accurately, please go through the code, and tell me where I am wrong, because I have gone through it many times and could not find the exact issue. Thanks in advance

The problem here is that indexOf returns the position of the character in the string, or -1 if it's not found.

In C 0 is false and everything else is true. That includes -1.

However, your usage if String here to just check for one character is incredibly wasteful and should be avoided. Instead, use strchr:

if (strchr(new_password, '#') != NULL) {
    ... contains # ...
}


LED fade with LDR sensor depending on the light I need help on a project. I just started to experiment with arduino 2 weeks ago and I am building a lamp that react to movement and interactions.
So the idea is; when there is nobody in the room, the light stay white.
And when there is someone, it turns orange and I want it to « breathe » (fade function).

I am using a LDR sensor to make it happen and so far my code looks like:

int LDRvalue = 1;
int RedLED = 9;
int GreenLED=10;
int BlueLED=11;
int pinLDR = A0;

void setup()
{
pinMode(RedLED, OUTPUT);
pinMode(GreenLED, OUTPUT);
pinMode(BlueLED, OUTPUT);
Serial.begin(9600);

}
void loop()
{
LDRvalue = analogRead(pinLDR);
Serial.print("valeur ldr: ");
Serial.println(LDRvalue);

int colour = map(LDRvalue, 0, 1023, 0, 255);
Serial.print("valeur mappe: ");
Serial.println(colour);

if(LDRvalue >= 1023)
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 255);
analogWrite(BlueLED, 255);
delay(1000);
}

else if((LDRvalue >= 800) & (LDRvalue < 1023))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 255);
analogWrite(BlueLED, 255);
delay(1000);

}

else if((LDRvalue >= 600) & (LDRvalue < 800))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 105);
analogWrite(BlueLED, 0);
delay(1000);

}
else if((LDRvalue >= 300) & (LDRvalue < 600))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 35);
analogWrite(BlueLED, 0);
delay(1000);
}

else if((LDRvalue >= 150) & (LDRvalue < 300))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 15);
analogWrite(BlueLED, 0);
delay(1000);

}

else if((LDRvalue >= 0) & (LDRvalue < 150))
{
analogWrite(RedLED, 255);
analogWrite(GreenLED, 0);
analogWrite(BlueLED, 0);
delay(1000);
}

delay(1);

}
void color(int red, int green, int blue)

{
analogWrite(RedLED, red);
analogWrite(GreenLED, green);
analogWrite(BlueLED, blue);
}

The code is working for the light changes depending on the human presence.
But I don’t know how to make it fade and breathe when it turns orange.

Could you help me to make it happen ?

While some parts of your code don't make much sense to me, the breathing led code is easily searchable on the internet, with one of the first results being:

#include <math.h>
#define ledPin 11
int i=0;
int breathe_delay = 15;   // delay between loops
unsigned long breathe_time = millis();
void setup() { }
void loop() {
  nonBlockingBreath();  // call the nonblocking function
  // yourOtherCodeHere();
}

void nonBlockingBreath() {
  if( (breathe_time + breathe_delay) < millis() ){
    breathe_time = millis();
    float val = (exp(sin(i/2000.0*PI*10)) - 0.36787944)*108.0;
    // this is the math function recreating the effect
    analogWrite(ledPin, val);  // PWM
    i=i+1;
  }
}

As you can see the code above works for monochromatic LEDs only, so my advise is to combine the code above with a conversion from HSL to RGB, like RGBConverter library, specifically the hsvToRgb function.

This way your version of the nonBlockingBreath function will become:

byte[3] rgb;
void nonBlockingBreath() {
  if( (breathe_time + breathe_delay) < millis() ){
    breathe_time = millis();
    float value= (exp(sin(i/2000.0*PI*10)) - 0.36787944)*108.0;
    hsvToRgb(hue, saturation, value, rgb);
    analogWrite(RedLED, rgb[0]);  // PWM
    analogWrite(GreenLED, rgb[1]);  // PWM
    analogWrite(BlueLED, rgb[2]);  // PWM
    i=i+1;
  }
}

Obviously you will have to set the hue and saturation variables accordingly to the tonality of orange you wish to breath.


Problem in bootloading 328p using Arduino as ISP. Please help me in figuring out the problem.I have uploaded the verbose below Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Uno"

C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM8 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xFD:m -Uhfuse:w:0xDE:m -Ulfuse:w:0xFF:m

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM8
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Error while burning bootloader.

there is great community called avrfreaks.net great with anything with AVR.

There is thread going with exactly same issue. follow it.

one quick thing try different 328p chip if it works mostly this one is bricked.
still want o experiment try changing crystal, fuse-bit , ISP , external clock generator.


CHSV arguments with FastLED I'm trying to use CHSV with FastLED library and as I understand hue, value and saturation in the CHSV type are of type uint8_t, or 1 byte.

My problem is with using variables:

CHSV led = (hue, sat, val);

with:

uint8_t hue;
uint8_t sat;
uint8_t val;

Is there a difference between uint8_t and byte data types? what is it and how does one use it with the context of arduino and FastLED library?
Am I getting the syntax wrong?
I get an error - convertion from 'uint8_t' to non scalar type 'CHSV' requasted.
I thought the library does that on its own, do I need to add more code? If yes, what code?

Thank you

Is there a difference between uint8_t and byte data types?

There is no difference in the datatype. byte is defined in Arduino.h:

typedef uint8_t byte;

So, uint8_t and byte are exactly the same. The uintX_t types and their siblings are specifically meant for having the same size on every platform (in difference to for example double which is only 16 bits on Arduino Uno, but can be 32 bits on bigger chips). But byte will also be 8 bits on every platform, so there is really no difference.

  Am I getting the syntax wrong? I get an error - convertion from 'uint8_t' to non scalar type 'CHSV' requasted. I thought the library does that on its own, do I need to add more code? If yes, what code?

You get the error, because you use the wrong syntax here. A CHSV color is not just 3 byte values, it is a class with member variables and methods. So you cannot simply assign 3 byte values directly to the object. You need to actually create the object, using the values as parameters for the constructor:

CHSV led = CHSV( hue, sat, val);

This creates a CHSV object, executes it's constructor, which uses the values from the parameters to set the internal values. That is the context, how this is used in the FastLED library. You can also find such lines in the examples of the library (I found such use in line 15 of the example ColorPalette, but there might be more). Also this is the same principle, as with the other color classes, like CRGB.


How to make ultrasonic and light sensors detect whether a person moving in or out I am trying to make a circuit that will be used for turning on a light whenever there are 1 or more people in a room. I need to add to a variable counter when someone enters and subtract when someone leaves. However, I do not know how to use the ultrasonic sensor for this purpose. What can I do?

See this tutorial on the Arduino Projecthub, that project was already made. Here is a tutorial how to use a Ultrasonic sensor.


Program button to switch between two values There is a function on one of my programs I want to be switch on and off by pressing a button. The button is unbiased otherwise I would set the function to read the button's status of HIGH or LOW.

So I need to create variable named "switch" with an initial value of 0. Then I would create a function would read if buttonPin is HIGH change the value of "switch" by +1. Next time the buttonPin is HIGH change the value by -1 so that every time the button is pressed the value of "switch" alternates between 1 and 0. Now before my loop calls the function I want on or off it can compare the value of "switch" and run or not run the function.

I don't know how to express this in the Arduino sketch. I'm am also open to alternate ways of achieving the same result.

Pseudocode:

value = 0
if button is pressed:
  value = 1 - value


How esp8266 gets response from server..? #include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200);
  delay(2000);
}

void printResponse() {
  String s="";
  while (ESP8266.available()) {
    s+=ESP8266.readStringUntil('\n');
  }

  Serial.println(s);
  // now here you can parse and look for "+IPD" look for another line ending (if there is) and then extract the numeric value.
}

void loop() {

  ESP8266.println("AT+CIPMUX=1");
  delay(1000);
  printResponse();

  ESP8266.println("AT+CIPSTART=4,\"TCP\",\"www.tcpss.000webhostapp.com\",80");
  delay(1000);
  printResponse();

  String cmd = "GET /test.html HTTP/1.1";
  ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
  delay(1000);

  ESP8266.println(cmd);
  delay(1000);
  ESP8266.println();
  delay(1000);
  printResponse();

  delay(5000);
}

i have run this code and i am able to get this  response from server like "+ipd 4,41".... what does it mean?
here is the response after run the code in arduino......
WIFI GOT IP
AT+CIPLUX=1

OK
AT+CHPSTART=4,"TCP","www.tcpss.000webhostapp.com",80

4,CONNEC
AR)CR5NB⸮b⸮⸮k

j⸮L⸮⸮
Recv 27 bytes

SEND OK

+IPD,4,41

Thanks in advance.....

There's two things to know here:

You're seeing corruption in your output because SoftwareSerial is not capable of working reliably at 115200 baud. You need to reconfigure your ESP8266 to operate at a lower baud rate (such as 9600) to be able to use it with an Arduino that doesn't have enough physical UARTs.
The response +IPD,4,41 is telling you about the response. It's not itself the response.

It means "IP Data on channel 4 of length 41". It is then your responsibility to request that data from the ESP8266 using whatever AT command the ESP8266 requires.
Personally I would scrap the AT firmware and program the ESP8266 directly. That way you solve both problems: you can choose what baud rate to communicate at (if you even need to communicate to an Arduino at all), and you have no AT commands to parse or craft. It is a far more efficient way of working with the ESP8266 that trying to fudge things with the AT firmware and an Arduino.


Detect if laptop is on or not? How would I safely connect an Arduino so that it can detect if a laptop is on or off?

The Arduino would be powered separately by a normal USB charger, since it needs to be turned on even when the laptop is turned off. So I'm thinking I can connect an input on the Arduino to one of the USB ports on the laptop somehow, but how do I do this safely?

Even if I play it safe and connect a current-limiting resistor between the USB voltage and input pin, and perhaps a voltage divider, is there still a problem with connecting one device to another like this? I'm thinking that since each has its own power supply from mains, could there potentially be a problem if I connect the USB port of the laptop to a pin on the Arduino?

Do need to use an optocoupler or relay between them? Or is there an even better way of doing this that I didn't think of?

If your chosen power supply is of a good quality and provides proper ground isolation then it shouldn't be a problem to connect the grounds of the two systems together.

However, since there are so many bad power supplies available on the internet (and even some "good" power supplies are somewhat iffy when it comes to grounding) it is safest to hedge your bets and add your own galvanic isolation.

The simplest method is to use an opto-isolator.  Use the +5V and GND from your computer's USB port (assuming it's not an always-on charging port - look for a lightning bolt symbol) along with a resistor (470Ω - 1kΩ is good) to drive the LED side of the opto-isolator. The other side then acts as a button to the Arduino:

simulate this circuit – Schematic created using CircuitLab

In this arrangement your input will be LOW when the PC is on. Also R2 could be replaced by the internal pullup of the GPIO pin (pinMode(PIN, INPUT_PULLUP);)

As I say, this most likely won't be strictly necessary, but for the minimal cost of an opto-isolator it's silly not to add that extra layer of protection. After all, an opto-isolator is cheaper than a new Arduino or (heaven forbid) a new laptop.


Uno to NodeMCU Serial Connection Problem This is my first project with any sort of development board and it has been a blast so far.

I am running into some issues, however, while trying to send serial data from my Uno to a NodeMCU board.

I have the following connections:

Uno Rx to NMcu Tx

Uno Tx to NMcu Rx

Uno GND to NMcu GND

microUSB from computer to power NMcu

usb from computer to power Uno

EDIT: after some suggestions, I have also tried the following.

Uno DigitalPin 5 to NMcu D6

Uno DigitalPin 6 to NMcu D5

Uno GND to NMcu GND

microUSB from computer to power NMcu

usb from computer to power Uno

With the following code:

// UNO sender Code
#include <SoftwareSerial.h>
SoftwareSerial toESP(0, 1); //Rx, Tx (also tried 5,6)

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

void loop()
{
  Serial.println("sending");
  toESP.println("message from Nano");
  delay(1000);
}

// NodeMCU receiver code
#include <SoftwareSerial.h>
SoftwareSerial fromNano(3, 2); //Rx, Tx (also tried D5, D6)

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

void loop()
{
  if (fromNano.available())
  {
    char inChar = fromNano.read();
    Serial.print(inChar);
  }
  else {
    Serial.println("not available");
  }
  delay(2000);
}

I can pull up a serial monitor from both and see the UNO sending data (the TX led also blinks on the uno).

The NodeMCU code never satisfies the fromNano.available condition.

Is there anything I am overlooking that is causing this not to work? I've attached a picture of my connections as well.

Any help is much appreciated.

Arduino UNO is using pin 0 and pin 1 to have serial with USB serial Communication. You can not use them to softserial. Change softserial to other pins.  /Mikael


Choose the correct solar panel and battery for solar use I am planning to build a weather station powered by solar power. I want to use an Arduino Nano because it's low power requirement. I want to connect some basic sensors to it (temperature, humidity…) as well as an anemometer, a wind vane and a rain gauge. The weather data should be sent wireless via 433 mhz to a raspberry pi, which acts as a web server. I do not have power cable access to the Arduino so solar is the only option.

Which solar panel should I use? I was planning to use 2 2.5W 5.5V panels which charge a Lithium-Ion battery which powers the Arduino using a step up converter. Assuming I have 2-4h of direct sunlight per day and I want to query the sensors every 5 minutes, how big of a battery should i choose? I don't want it to go out of power and want it to last a couple of days without sun.

I won't be able to tell you which solar panel or battery to use, but I can tell you how to figure that out.

Battery

For the battery there are a few different ways to figure this out:

The most common way to do this at the professional level is to build the device and run it attached to an energy meter and measure it for an hour or two performing its usage, and use that to calculate how much it will use over a 48 hour period. That being said that type of test equipment is not really a hobbyist piece of equipment and probably not something you are wanting to obtain for this project.
You can try and use the datasheets for all of your components to determine their idle and active current draw is, add them up for idle and active, adjust the values based upon the efficiency of your step up converter (so if it only 75% efficient, divide them by .75), guesstimate how long your sensor read process will take, multiply your active current draw times the voltage and times the time it will take (in hours, so if this is a few seconds, it will be a really small decimal), multiply your idle current draw times the voltage and times .083 hours (5 minutes), add those two together multiply it times 12 (12 - 5 minute periods per hour) and then by 48 (two days) and that will be an estimate of your energy usage for two days. Now this will be a very rough estimate as the datasheets only provide nominal values, and their actual usage in practice may be different, which leads me to the final option...
A hybrid between the two above solutions. Set up your device and have it read the sensors and transmit continuously. Then use a multi-meter to measure the current usage of it actively being used. Repeat the measurement again but this time with it running on an indefinite timer to simulate being idle. Then take those two numbers and use the above formula substituting the datasheet estimates with your actual measurements to get a much more accurate picture of what your energy usage will be.

Once you have your energy usage (this will be in milli-Watt-Hours or mWH) pick a battery voltage you will be using (this is based on the charge circuit you are using, typically, single cell lithium ion batteries are 3.7 or 4.2, with multi-cell batteries being multiples of those), divide your energy by the voltage to get the power (in milli-Amp-Hours or mAH) and you'll want to pick a battery greater than that. You'll also want to double check the data sheet of your step up converter and see what the drop out voltage is, and then compare that to the datasheet for the battery and see at what capacity it hits that voltage. You'll want to make sure that it is at least 80%. Otherwise you'll have to pick a different battery with a larger capacity, or a different step up converter with a lower dropout voltage.

Solar Panel

For the solar panel, what you will want to do is get a battery charger designed specifically for use with solar panels. This is because when it says 5.5v solar panel, that is it's nominal voltage in full sunlight, however, it most often will not be that and will vary greatly throughout the day. What this means is that solar panels are basically on unregulated power supply, and most battery chargers require a regulated power source. With a solar specific batter charger, it is designed such that it can handle voltage variation and sudden dropouts. Usually these chargers come with a recommendation as far as voltage and current requirements and those specifications should form the basis of your solar panel selection.

So for example, if you have a battery, on the datasheet it will list what its charge current is, and you'll want to make sure you have a charger circuit that can supply that amount of current. Then you'll want to take a look at the datasheet for the charger circuit, see what current it requires and then make sure that the solar panel can provide that current.


Concatenate string constants Please take a look at following example (I have Java background):

const char* BT_ADDRESS = "abcd,ef,ghijkl";

void bar(const char* string) {
  ...
}

void foo() {
   bar("AT+BIND=" + BT_ADDRESS);
   bar("AT+LINK=" + BT_ADDRESS);
}

How to achieve this with "Arduino-C++" so BT_ADDRESS only has to be entered at one location?

There is, as you may expect with C, many different ways of doing this.

The simplest is probably to use, instead of a const variable, a preprocessor macro.

In C you can concatenate string literals like this:

print("AT+BIND=" "abcd,ef,ghijkl");

Note the lack of anything but spaces between the strings - they are concatenated together. You can even do it on separate lines - it's a technique that is great for incredibly long strings.

Now you can, of course, replace one of those with a preprocessor macro:

#define BT_ADDRESS "abcd,ef,ghijkl"
print("AT+BIND=" BT_ADDRESS);
print("AT+LINK=" BT_ADDRESS);

The preprocessing replaces BT_ADDRESS with the string literal "abcd,ef,ghijkl" and all is well.

Other options, depending on what print does, is to expand it to take two const char * parameters and deal with them both separately.  For instance, you might have:

void print(const char *command, const char *data) {
    Serial.print(command);
    Serial.println(data);
}

print("AT+BIND=", BT_ADDRESS);

If you don't know how many parameters you may want to pass you could use variadic arguments:

#include <stdarg.h>

void print(int count, ...) {
    va_list args;
    va_start args, count);

    for (int i = 0; i < count; i++) {
        const char *arg = va_arg(args, const char *);
        Serial.print(arg);
    }
    va_end(args);
}

print(2, "AT+BIND=", BT_ADDRESS);

Yet another option is to pre-format the data into a single string using the various string operators.  For example:

int len = strlen("AT+BIND=") + strlen(BT_ADDRESS);
char temp[len + 1]; // Be sure to keep space for the terminating NULL.
strcpy(temp, "AT+BIND=");
strcat(BT_ADDRESS);
print(temp);

I could go on all night with different options...  The first one using the preprocessor is probably easiest though.


How do I know the size of the bootloader of ATtiny? Is it the same as ATMega328P? I burned the bootloader in ATtiny45 with the Arduino tool.

I want to know how much memory it has taken.
Is this bootloader the same code of a bootloader used in the 328P or other chips?
Can I see this code in any way, to know how it works?

1) I want to know how much memory it has taken

Look to see how big the bootloader is. If it's a HEX file you will either want to load it into a HEX (Intel HEX, not hexadecimal representation) file editor, or convert it to binary with avr-objcopy.

$ avr-objcopy -I ihex <hex file> -O binary <bin file>

  2) and if this bootloader is the same code of a bootloader used in the 328P or other chips

No, each chip requires its own special bootloader - simply because all chips are different: that's why they exist.  If they were all the same there would only be one chip.

  3) Can I see this code in any way, to know how it works ?

If it's open source and you download the bootloader from wherever it's stored (probably Github somewhere), then yes, you can. Of course, that also assumes that you would understand what you are seeing which, judging by this question, is not that likely.


Which (Official) Arduino IDE to use? I have bought an Arduino UNO that turned out to be the Italian version (Arduino SRL) not the American one (Arduino LLC).

Now when I go to arduino.org and arduino.cc, they both have different versions of the IDE!

So, which one should I use (if they are even different) ?

You can use both IDEs no matter of the origin of the UNO even fake ones runs with the IDEs.
The arduino.org IDE is just a fork of the arduino.cc.
But arduino.org has many Board which are only run with the .org IDE.


Arduino coding of producing frequency Im new here. Anyone that could give a code or sample that would generate I wanted to use a frequency in range of 35k-43kHz. Please help me.

The code below generates 38 kHz and modulates its duty cycle.

// Example of modulating a 38 kHz frequency duty cycle by reading a potentiometer
// Author: Nick Gammon
// Date: 24 September 2012

const byte POTENTIOMETER = A0;
const byte LED = 10;  // Timer 1 "B" output: OC1B

// Clock frequency divided by 38 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 38000L;

void setup()
 {
  pinMode (LED, OUTPUT);

  // set up Timer 1 - gives us 38.005 kHz
  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11) | bit (COM1B1); // fast PWM, clear OC1B on compare
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
  OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
  }  // end of setup

void loop()
  {
  // alter Timer 1 duty cycle in accordance with pot reading
  OCR1B = (((long) (analogRead (POTENTIOMETER) + 1) * timer1_OCR1A_Setting) / 1024L) - 1;

  // do other stuff here
  }


SPI Connections to DAC I'm hoping to construct a feedback loop for a laser using an Chipkit UC32 and an analog-digitial converter ( the one of I have is an AD5780 evaluation board). I've been reading through Digilint's  SPI library but I admit I am pretty lost.

( I believe this is on topic to Arduino because I am using an Arduino API. The micro-controller I use is basically an Arduino so I see no difference. )

I'd like to output something simple like a digital AC voltage to the DAC and have it convert it, but as I understand it from here, I am just using the digitalWritecommand which is basically binary. How do transfer something more complicated to have the DAC convert it?

Likewise, how do I get the DAC to do the reverse, ADC, where it reads in a voltage and sends the Arduino a digital signal through SPI pins?

I'd like to output something simple like a digital AC voltage to the DAC and have it convert it, but as I understand it from here, I am just using the digitalWritecommand which is basically binary. How do transfer something more complicated to have the DAC convert it?

SPI is a communication protocol.  It uses digital signals, coupled with time, to transfer information.

To use DSPI you need to first define an SPI object

DSPI0 SPI;

From then on it's the same as using the Arduino SPI library.

Start it

SPI.begin();

Then transfer the correct commands (found in the DAC datasheet) to set the voltage of the output

digitalWrite(10, LOW);
SPI.transfer(0x43);
SPI.transfer(0x1A);
digitalWrite(10, HIGH);

The values there are just examples. The 10 is the chip select pin for the DAC, and the values used in the transfers (however many are needed) need to be found in the datasheet.

If you only want to use the pins associated with DSPI0 you can use the SPI library instead (which only supports one SPI channel - the uC32 has two), in which case it is identical to working with the Arduino SPI library.

  Likewise, how do I get the DAC to do the reverse, ADC, where it reads in a voltage and sends the Arduino a digital signal through SPI pins?

You don't. DACs are DACs and ADCs are ADCs. They aren't interchangeable.

For ADC functionality just use any of pins A0 through A11 and the analogRead() function.


Arduino SPI - MOSI not writing any data but clock works I am trying to iterate over an int array and writing those values to a chip. Here is my code.

#include <SPI.h>

int sine[] = {0x7fc ,0x868 ,0x8d4 ,0x93c ,0x9a8 ,0xa10 ,0xa78 ,0xadc
,0xb3c ,0xba0 ,0xbfc ,0xc58 ,0xcb0 ,0xd04 ,0xd58 ,0xda4 ,0xdf0 ,0xe34 ,0xe74
,0xeb0 ,0xee8 ,0xf1c ,0xf4c ,0xf74 ,0xf98 ,0xfb8 ,0xfd0 ,0xfe4 ,0xff0 ,0xff8
,0xffc ,0xff8 ,0xff0 ,0xfe4 ,0xfd0 ,0xfb8 ,0xf98 ,0xf74 ,0xf4c ,0xf1c ,0xee8
,0xeb0 ,0xe74 ,0xe34 ,0xdf0 ,0xda4 ,0xd58 ,0xd04 ,0xcb0 ,0xc58 ,0xbfc ,0xba0
,0xb3c ,0xadc ,0xa78 ,0xa10 ,0x9a8 ,0x93c ,0x8d4 ,0x868 ,0x7fc ,0x794 ,0x728
,0x6bc ,0x654 ,0x5ec ,0x584 ,0x520 ,0x4bc ,0x45c ,0x400 ,0x3a4 ,0x34c ,0x2f4
,0x2a4 ,0x258 ,0x20c ,0x1c8 ,0x188 ,0x148 ,0x110 ,0xe0 ,0xb0 ,0x88 ,0x64 ,0x44
,0x2c ,0x18 ,0xc ,0x0 ,0x0 ,0x0 ,0xc ,0x18 ,0x2c ,0x44 ,0x64 ,0x88 ,0xb0 ,0xe0
,0x110 ,0x148 ,0x188 ,0x1c8 ,0x20c ,0x258 ,0x2a4 ,0x2f4 ,0x34c ,0x3a4 ,0x400
,0x45c ,0x4bc ,0x520 ,0x584 ,0x5ec ,0x654 ,0x6bc ,0x728 ,0x794};

#define samples 120

const int cs = 9;

int counter = 0;

const int chipSelectPin = 10;

void setup()
{
  pinMode(cs,OUTPUT);
  pinMode(chipSelectPin, OUTPUT);

 SPI.beginTransaction(SPISettings(20000,LSBFIRST,SPI_MODE3));
}

void loop()
{

  digitalWrite(cs,LOW);

  SPI.transfer(sine[counter]);

  digitalWrite(cs,HIGH);

  counter += 1;

  if(counter >= samples)
  {
    counter = 0;
  }

}

Very simple, I am using an Arduino nano and according to this reference the clock pin is 13 and MOSI is 11. I am seeing the clock signal for pin 13 but pin 11 is inactive.

In addition to @Talk2's answer SPI.transfer(...) transfers one byte of data. Your array is made of int which means each entry is 2 bytes long.

Instead you should use SPI.transfer16(...) to transfer 16-bit values.


Arduino continuously reading ADC value using interrupt I have a mono jack audio act as analog input for arduino UNO. The microphone outputs voltage that varies in terms of amplitude (volume) and frequency. In order to get the high sampling rate, I use prescaler 16 and set high baudrate for serial communication to print the value. I save the analog read from that jack audio to buffer array with maximum value is 256 (8-bit). This is my code (I modify from the Nick Gammon's blog about ADC here) :

const byte adcPin = 0;  // A0

const int MAX_RESULTS = 256;

volatile int results [MAX_RESULTS];
volatile int resultNumber;

void setup ()
  {
  Serial.begin (230400);
  Serial.println ();

  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  TCCR1B = bit (CS11) | bit (WGM12);  // CTC, prescaler of 8
  TIMSK1 = bit (OCIE1B);
  OCR1A = 39;
  OCR1B = 39;   // 20 uS - sampling frequency 50 kHz

  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF);   // turn ADC on, want interrupt on completion
  ADCSRA |= bit (ADPS2);  // Prescaler of 16
//  ADCSRA |= (1 << ADPS1) | (1 << ADPS0);    // 8 prescaler for 153.8 KHz
  ADMUX = bit (REFS0) | (adcPin & 7);
  ADCSRB = bit (ADTS0) | bit (ADTS2);  // Timer/Counter1 Compare Match B
  ADCSRA |= bit (ADATE);   // turn on automatic triggering

}

// ADC complete ISR
ISR (ADC_vect)
{
    results[resultNumber++] = ADC;
    if(resultNumber == MAX_RESULTS)
    {
      ADCSRA = 0;  // turn off ADC
    }
}

EMPTY_INTERRUPT (TIMER1_COMPB_vect);

void loop () {

  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
  {
    Serial.println (results [i]);
  }
}

With that code, I got a nice result of sinusoidal graph represented audio value up to 4000 Hz like this :

But one thing that didn't work is if I change the volume or frequency (while displaying data) of analog input (jack audio), the graph I print and display via serial plot audio won't change. So I had to close it and open again to see the change. The question is how can I achieve the continuous and real time reading of this ? Thank you very much.

reset the resultNumber to 0 after you have written it to serial. and turn interrupts back on

void loop () {

  while (resultNumber < MAX_RESULTS)
    { }

  for (int i = 0; i < MAX_RESULTS; i++)
  {
    Serial.println (results [i]);
  }
  resultNumber = 0;
  ADCSRA =  bit (ADEN) | bit (ADIE) | bit (ADIF)| bit (ADPS2) | bit (ADATE);
   // turn ADC back on
}


Tiny RTC I2C module not working I bought a Tiny RTC I2C module and it doesn't work.
When i run the TimeRTCSet from TIME library all i get is:

Unable to sync with the RTC
0:00:00 0 0 1970
0:00:01 1 1 1970
0:00:02 1 1 1970
0:00:03 1 1 1970
0:00:04 1 1 1970
0:00:05 1 1 1970
0:00:06 1 1 1970
0:00:07 1 1 1970

The module is connected like this:

Vin -> 5V
Gnd -> Gnd
SCL -> A5
SDA -> A4

I'm using arduino uno.

I tried with a simple i2c scanner, but it returned two devices!

Scanning...
I2C device found at address 0x50  !
I2C device found at address 0x68  !
done

Only the clock is connected. I tried removing the battery for night to reset it, but it didn't fix it.

Could you help me?

Try using the example code from the MD_DS1307 library to find the settings on your RTC, when I first wired mine up the clock was not running and I couldn't set the time on it. After I enabled it, it worked just fine.


Using Atmel Studio with Arduino Starter Kit (Uno MCU) Can someone tell me if it's possible AND safe to use Atmel Studio with Arduino Starter Kit?  I'm a newbie to firmware in general and I don't want to "brick" my Arduino Uno Microcontroller.  I don't quite know if the micro controller has been programmed in read only or special memory to make it Arduino compatible and me messing with Atmel Studio could mess it up.  In other words, I want to know I can get back to programming through the Arduino IDE and continue working on the projects in the starter kit book.  I've done about half of them.

1)  Can someone tell me if it's doable, safe and WHY?
2)  Any hints or gotchas or examples on how to do it?

My motivation is that I'm taking a job as a C# Windows programmer but will be exposed (I believe) to AVR and Atmel Studio and wanted to get familiar with it by just playing a little bit.  Arduino libraries seems to hide a lot of the messy details (such as setting a pin output) which is fine, but it would probably be good to do those messy details myself and be familiar with the actual tools they will use at work.

I have searched for a "tutorial for dummies" that says what settings to pick, etc. to no avail.

Thanks Dave

P.S.  If the answer is NO WAY is it safe or desirable, perhaps a recommendation for an AVR development kit (cheaper is better!).  Actually, this is probably not a bad idea anyhow.
Many Thanks!

There are many tutorials on programming Arduino boards (or any other AVR MCU) with Atmel Studio:

Creating new project:
https://asensar.com/blog/2013/how-to-setup-atmel-studio-for-arduino-development/

Configuring Avrdude for firmware upload:
https://asensar.com/blog/2013/how-to-integrate-avrdude-with-atmel-studio/
http://www.instructables.com/id/How-to-Load-Programs-to-an-Arduino-UNO-From-Atmel-/

Please see this post too:
Atmel studio 7 - my own libraries

Nothing to afraid of, just don't mess with lock fuses (relevant only if you decide to play with ISP programmer and arvdude/avrdudess). Use Arduino USB virtual COM port connection for firmware uploading, just like in Arduino IDE.

With Atmel Studio you don't have rich libraries available like in Arduino platform, instead you will have to program MCU, its peripherals (and other devices connected, if any) by directly accessing MCU registers. This requires some knowledge on MCU hardware (but it is a natural choice if you want to learn that). Eventually you can build your own wrapper libraries similar to one in Arduino.

Check Procyon AVR library too - much better choice than digging Arduino library sources (a bit old but still relevant, I always recommend it as a starting point for AVR library development:)
http://www.procyonengineering.com/embedded/avr/avrlib/


Sending mouseX and mouseY from Processing to Arduino I'm new to serial communication and trying to send mouseX and mouseY from Processing to Arduino. Serial monitor doesn't show anything.

Processing code:

import processing.serial.*;
Serial port;
void setup() {
  size(500,300);
  port = new Serial(this , Serial.list()[0], 9600);
}

void draw() {
   text("X Y mouse",250,50);
   if (port.available() > 0) {
    port.write(str(mouseX)+' '+str(mouseY));
   }
}

Arduino code:

int x = 0;
void setup() {
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    x = Serial.read();
    Serial.print("I received: ");
    Serial.println(x);
  }
}

when I close Processing window and enter "ok" in Arduino serial monitor I see:

Since you can't use the serial monitor to "see" the incoming data from Processing, here are 2 test sketches that may help you determine if data is received on the Arduino.

Upload the Arduino sketch first. Leave the serial monitor closed. Now run the Processing sketch.

I'm using frameRate(1) in the Processing sketch to send the data once per second, so the mouse X/Y values in the Processing window will be slow to update.

You should see the LED on the Arduino flash on then off quickly as the data is received. If you have a I2C LCD available, you could connect it to the Arduino and print out the incoming data.

As chrisl mentions in the comments, there is still much work to be done to get the raw data in the format you require.

Arduino

int x = 0;
const byte ledPin = 2;

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

void loop(){
  if(Serial.available() > 0){
    x = Serial.read();
    digitalWrite(ledPin, HIGH);
  }
  else{
    digitalWrite(ledPin, LOW);
  }
}

Processing

import processing.serial.*;
Serial port;
void setup() {
  size(500,300);
  background(148);
  try{
    port = new Serial(this , Serial.list()[0], 9600);
  }
  catch(Exception e){
    System.err.println(e);
    e.printStackTrace();
  }
  frameRate(1);
}

void draw() {
  background(148);
  //@chrisl comment: Finish your data, that you send with \n (newline).
  port.write(str(mouseX)+' '+str(mouseY) + "\n");
  text(mouseX,250,50);
  text(mouseY,250,70);
}

EDIT

Here is a second Arduino sketch that will display the mouse X/Y values sent from Processing on a LCD. You could change the Processing sketch's frameRate() value to 10.

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

char inputBuffer[32 + 1];

LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup(){
  Serial.begin(9600);
  lcd.init();
  lcd.backlight();
}

void loop(){
  if(Serial.available() > 0){
    lcd.print("                ");
    Serial.readBytesUntil('\n', inputBuffer, 32);
    lcd.setCursor(0, 0);
    lcd.print(inputBuffer);
    memset(inputBuffer, 0, sizeof(inputBuffer));
  }
}