UltraSonic sensor in rain? I am onto a simple project with Arduino, SR04 and a buzzer for "Car reverse parking assistance". The aim here is to make a buzz when the car gets too close to the objects.

I was thinking what if it's raining when a person is driving (assuming I somehow achieved to water proof the sensor) - will the buzzer make continuous sounds?

Is there any alternative solution for ultrasonic sensors?

will the buzzer make continuous sounds

If you mean the sensor will detect the rain drops in the air
Nop it's tiny to read it in the air
But if there is drops on the sensor your sensor will not gives you the right reading

There is a water proof ultrasonic sensors available.

I am working on water level devices, after long path of searching in different ultrasonic sensors and after I tried a lot of method like using water proof Cloth, I found the best way is using water proof sensors PLUS water proof cloth.

water proof sensors work perfectly in high humidity but at the same time if there is a water drop on the sensor the reading will be different, and for that some cars manufacturers used not only one sensor, to avoid the errors. and calculate the differences.

The left car used old technology with separate sensors, but that's make errors the only good thing was to detect more things, in the next generation they mix them together.

water proof cloth will make the water drops not stuck at the sensor, but you will need to replace it every 5-6 months. "in your case because the sun will destroy the cloth" in my case and because my sensor inside tanks that's will least more.

I tried to spray the sensor with a different material to make my sensor not catch any water drops, it dose not work too.

And to make my cheap sensor water proof, I tried to use ceramic layers, and that's not work too, they use it with ultrasonic fog maker, these layers not work with cheap ultrasonic sensors, it's need a lot of power to vibrate it and different frequency. and of course you need to replace the layers "depending on the environment"

If you find ultrasonic car sensor with special material for water drops just let me know, I am searching on that too.

NOTE These days car manufacturer use different ways, in the past the cover was vibrate itself and made from aluminum, now they cover it and make different filters to ignore the plastic cover, How?! maybe it's different plastic or material maybe they find away to vibrate the plastic! sorry I could not find the secret.


Write to EEPROM during power down I am making a counting device, and I would like to be ensure that the count is not lost if the power is lost.
As I need to count to many millions I cannot use EEPROM writes as I will trash the nvm after ripping through the 100,000 max write cycles. I also need to ensure the count is accurate, so can't update 'every-so-often' either.

I want to write to EEPROM when the Arduino detects power down. I am reading on an Analogue input pin and am then planning on using a capacitor to hold the power on to complete the write. I have this set up but am having issues testing as I have found that when Ground is connected to GND pins and then when 5v is supplied to any I/O pin the device powers up. I have now tested a Nano and Uno and have found the same thing on both.

I have looked through the arduino site and tried looking for forums where this has been discussed, but to no avail.

Is this damaging to the Arduino if powered in this way? Does this pass the sanity check as a way of achieving my main objective of not loosing the count on power down?

thanks in advance :)

A more sophisticated version of @MikaelPatel's techique is not to store the individual counts, but to store a derivative:

Reserve a block of storage with (say) 8 counters. Each counter has as many bits as necessary to store the largest value - but see below for what "largest" means.
Each time the count goes up, write into the next counter along (modulo the number of counters).
But don't write the value of the counter, write the value divided by the number of counters - counter/8.
Here's the trick: while that looks like you're losing precision, you're not - because the counter location is information too! In fact you're gaining size.

It's best shown with an example. For ease, I'll assume an 8-bit counter, and only 8 counters:

0000: 03 03 03 03 03 02 02 02

Assuming that everything started at 00, that means that it took 8 counts for them all to get to 01, a further 8 counts for them all to get to 02, and only 5 counts to get the first 5 to 03. That's a total of 8+8+5 or 21.

At boot time, look for where the number sequence goes down. That's your current buffer position for future updates, plus the information for the current value:

CurrentCount = [Smaller number] * [Number counters] + [Number of larger];

Once you've worked it out, keep the current value for incrementing, and the buffer pointer for where to store the next count.

Advantages:

A. You write as often as you would storing a counter - but in different locations, spreading the load.
B. Each location (8, 16 or 32 bits) can store a certain maximum - but the total maximum is a factor of Number of Counters larger than that!

Odometer manufacturers use this exact technique to store the current mileage in digital dashboards - they have a legal requirement to maintain the correct number. They only use 16-bit counters (which would overflow after 65,535 miles), but then they use 16 counters, for a total mileage maximum of over a million. Each location only gets written every 16 miles, and they don't need to use 32-bit locations.


Getting a binary string and convert it to decimal I have a 4 dipswitch to get a 1 or a 0, try to get that into a string and from that get a decimal, therefor if I get for example a 0011 a 3.

so, I know that from the variations of 0000 to 1111 is a decimal from 0 to 15, I already have my string but how do I convert the "binary string" to decimal?

to get the string I'm using this (the I is at 5because there is where is the dipswitch):

      for(int i = 5; i <= 9; i++){
           Serial.println(digitalRead(i));
           Dstate = Dstate + digitalRead(i);
      }

What you want are the bit-shifting operators << and >>, and the OR operator |:

for(int i = 0; i < 4; i++) {
    Serial.println(digitalRead(5 + i));
    Dstate = Dstate | (digitalRead(5 + i) << i);
}

You'll notice I changed the loop so it runs from 0 to 3 instead of 5 to 9 - it makes other parts easier if you start counting from 0.

Then the line:

Dstate = Dstate | (digitalRead(5 + i) << i);

is where all the magic happens.  Let's break it down:

digitalRead(5 + i)

That of course gives you a 0 or 1 for pins 5, 6, 7 and 8 in turn.

<< i

That shifts the value returned by digitalRead() left i bits.  For instance, if digitalRead() returns 1 and i is 0 then 1 is left shifted 0 times so remains as 0b0001.  If i is 1 then it left shifts one bit, so the value becomes 0b0010.  If i is 2 then it shifts two bits, so you get 0b0100.

Finally the result is combined with the current value of Dstate with OR, so the four values basically get laid over the top of each other.

So say you have the four switches in the positions ON-OFF-ON-OFF and Dstate starts off as 0, then the sequence would be:

i = 0, digitalRead = 1, shifted = 0b0001, OR = 0b0001
i = 1, digitalRead = 0, shifted = 0b0000, OR = 0b0001
i = 2, digitalRead = 1, shifted = 0b0100, OR = 0b0101
i = 3, digitalRead = 0, shifted = 0b0000, OR = 0b0101


Leonardo soft bricked I was uploading a sketch to my Arduino Leonardo and I pressed the reset button accidentally while it was still uploading. Now the board does not get recognized by my computer. Is there something that can be done to save it or should I get a new one?

You'll need to program it trough the ISP port with an AVR programmer if you can't program it through a reset or double reset anymore. This can be done using another arduino. A tutorial is on the arduino.cc website.


How to round up millis() when divided into minutes? unsigned long milliseconds=millis();
// if at time of reading the above milliseconds = 599999 ie 1 millisecond short of 600000 ie 10 minutes
unsigned long minutes = (milliseconds/1000)/60;
// this will return 9 instead of 10.

How do you round the result to 10 minutes? I don't mean adding 1 to final result. It has to be within the calculation.

To round to the nearest X in fixed point arithmetic: add 1/2 X (in the base units, msec, in this case) and divide by X (again, in the base units) so:
milliseconds = (milliseconds + (30*1000L))/(60*1000L);

The addition of 1/2 X causes a carry of one whole X if the fractional X in the original quantity was 1/2 X or greater. (Likewise, if the fractional X was less than 1/2 X, no carry will result).

Integer division naturally truncates any fractional amounts, so you'll be left with the rounded integer result.


arduino sketch on Win7 vs. MAC op system? I have a friend who is just getting started with Arduino UNO.  He downloaded a sketch and is using a UNO on Mac OS.  He loaded the sketch and verified.  it comes up with errors.  He sent me the same sketch and i opened it under Win7 arduino software.  verified, and it says it is fine.  i made an arduino file and emailed it back to him.  he is still getting the same errors.  can anyone help and let me know what is wrong?  i am not a MAC expert and wonder why  this works in win and not MAC????????  appreicate any help anyone can give me

I've had the same issue with Mac OSX 10.6.8 vs Windows XP SP3 using the same IDE version. I don't have a definitive answer for you, but I know that Microsoft has more frequent updates compared to Apple, which could be the reason. I suspect my issue and your friend's issue is the GCC compiler we're using. The compiler would be updated on OSX only when you update your entire OSX version. To get around that, there are third-party package managers: Homebrew and MacPorts that would allow you to just update the GCC compiler for example.


How can I setup a LED state change with push buttons? I'm doing a project using Arduino Uno R3 and I'm trying to use two buttons to change LED state between HIGH and LOW. I have already a code but someting its not right because the LED should be starting in LOW state but it's starting in HIGH state. I checked the circuit and its all good none of the components is connected in wrong place or not connected corretly and the resistors I used are the right ones.

Here is the code I'm using:

 int ledpin = 13;
 int pushbutton1 = 8;
 int pushbutton2 = 7;
 boolean lastbuttonstate1 = LOW;
 boolean lastbuttonstate2 = LOW;

void setup()
{
  pinMode(ledpin,OUTPUT);
  pinMode(pushbutton1,INPUT);
  pinMode(pushbutton2,INPUT);
}

void loop() {

static bool ledState = false; // LED is off by default
 if ((digitalRead(pushbutton1) == LOW) && !ledState) { // 1 pressed & led is off
    digitalWrite(ledpin, HIGH);
    ledState = true;
 }
  if ((digitalRead(pushbutton2) == LOW) && ledState) { // 2 pressed & led is on
    digitalWrite(ledpin, LOW);
    ledState = false;
  }
}

This is an excellent tutorial for exactly that:
http://www.instructables.com/id/How-to-use-a-Push-Button-Arduino-Tutorial/

Its a bit hard to give you a specific answer without seeing you circuit.
but as a start, i would set the ledPin to LOW in the setup routine.

void setup()
{
  pinMode(ledpin,OUTPUT);
  pinMode(pushbutton1,INPUT);
  pinMode(pushbutton2,INPUT);

  //initialize the pin to low
  digitalWrite(ledpin,LOW);

}


GSM library getIPaddress returns local network address 10.X.X.X I have a Mega board and a GSM shield. I'm using Arduino's example "TestWebServer". The serial monitor shows that the GSM is connected, and returns a IP.

However, the IP is always 10.X.X.X. Isn't that a internal network IP address? How should I get the SIM cards IP? Thanks!

The SIM card does not have an IP address. When the data connection is made to your GSM APN it is assigned an IP in a similar way to DHCP. Often the address is the same after the first connection as the service provider will link that to your SIM for audit purposes. If you setup a private APN then you can arrange to have specific range allocated to your SIM card(s). This is normally only done for security of volume reasons.


3.3 V Arduino Pro Mini and nRF24L01 issues I have a 3.3 V Pro Mini connected to nRF24l01 as xmtr. The nRF24L01 does not respond to the Pro Mini. Any help will be appreciated.

I have attached the print detail output:

Transmitter 2  Started
STATUS       = 0xff RX_DR=1 TX_DS=1 MAX_RT=1 RX_P_NO=7 TX_FULL=1
RX_ADDR_P0-1     = 0xffffffffff 0xffffffffff
RX_ADDR_P2-5     = 0xff 0xff 0xff 0xff
TX_ADDR      = 0xffffffffff
RX_PW_P0-6   = 0xff 0xff 0xff 0xff 0xff 0xff
EN_AA        = 0xff
EN_RXADDR    = 0xff
RF_CH        = 0xff
RF_SETUP     = 0xff
CONFIG       = 0xff
DYNPD/FEATURE    = 0xff 0xff
Data Rate    = 1MBPS
Model        = nRF24L01
CRC Length   = 16 bits
PA Power     = PA_MAX

Transmitter 2 Started
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0xe8e8f0f0e2 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe8e8f0f0e2
RX_PW_P0-6   = 0x20 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x03
RF_CH        = 0x73
RF_SETUP     = 0x07
CONFIG       = 0x0e
DYNPD/FEATURE    = 0x03 0x06
Data Rate    = 1MBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_MAX
voltage = 3.97 V
0
RSLT (1 = success) 0
Data Sent 3.00  0.00  3.97
voltage = 3.85 V
voltage = 3.79 V
voltage = 3.75 V
voltage = 3.73 V
0
RSLT (1 = success) 0
Data Sent 3.00  0.00  3.73
voltage = 3.70 V
voltage = 3.68 V
voltage = 3.65 V
voltage = 3.62 V
0
RSLT (1 = success) 0
Data Sent 3.00  0.00  3.62
voltage = 3.58 V
voltage = 3.54 V
voltage = 3.50 V
voltage = 3.45 V
0

The top transmitter output is before I changed the nRF24L01 module which appeared to be bad.
The second transmitter started output. Module is good but nRF24L01 would not connect to receiver with 3.3 V Pro Mini. It connects if I use a Nano.

voltage = 3.97 V 0 RSLT (1 = success) 0 Data Sent 3.00 0.00

nrf24l01 is a 3.3V device, Where'd that come from?


Infra Red Send Hex Code I am using an arduino nano with the standard arduino IR remote library. For now I am using the Irrecord sketch. However, I want to have some pre - programed codes for remotes I don't have. I found this site which apparently has the hex of an endless number of remotes. When I use the regular IR decode, the hex of any remote I use, is only a couple of characters.  However at this site the typical amount is at least 100.

This is the hex for a Toshiba model's sleep command:

0000 006c 0022 0002 0157 00ab 0016 0016 0016 0016 0016 0016 0016 0016 0016 0016 0016 0016 0016 0040 0016 0016 0016 0040 0016 0040 0016 0040 0016 0040 0016 0040 0016 0040 0016 0016 0016 0040 0016 0040 0016 0016 0016 0040 0016 0016 0016 0040 0016 0016 0016 0016 0016 0016 0016 0016 0016 0040 0016 0016 0016 0040 0016 0016 0016 0040 0016 0040 0016 0040 0016 05f0 0157 0055 0016 0e52

So, finally after all that if you are still with me my question is, how would I send that command with the IRRemote library.

That seems to be pronto hex format for codes. A quick google showed this explanation: http://www.remotecentral.com/features/irdisp2.htm and this sample code: https://gist.github.com/probonopd/5793692


How do I program an LCD screen and do I need an Arduino I am trying to create a small device with a screen that tells the date and time. I am thinking of using a UCTRONICS 0.96 Inch OLED Module (type that on Amazon). I am very new at coding, and I know more about electrical engineering, so I have a few questions.

Do I need an Arduino that big to power this screen or any screen? I am trying to put this in a compact housing

How do you set up the screen and code it to tell the time and date

Is there a better screen for me to pick that is easier to work with, or is there a screen that comes programmed telling the time and date

Can someone help, please?

OLED screen is really good looking for both indoor and outdoor and I think you have made a good choice.
You need the following things to complete your project easily.

Display (which you have already found one
Arduino (why? easy to program, lots of libraries available, and also tutorials)
RTC - Real-time clock - This is another IC (DS1307, for example)

Arduino need not be UNO. You can use ATTiny85 MCU. the programming will be the same as how you program a UNO. ATtiny85 has no builtin I2C, but the libraries are there to emulate I2C to be connected to OLED displays.
If you want to avoid the third option, go with internal timekeeping alone. But, over a week, you will see the time difference (the internal clocks of the MCU are not accurate, so the time will lead or lag over a period of time)
have you thought about a keypad or a single button to give the option to the user to set the time?


Run Arduino on USB and at the same time BreadBoard on higher voltage? I am trying to design a bicycle LED lighting system, and for that I bought an Arduino yesterday (so very beginner with Arduino).

My final system will operate at 6V, so I plan to put everything on a breadbord and tune everything (blinking times, resistor values, etc.) and for that I want to keep my Arduino plugged to USB during development.

So my question is:

How should I connect USB-powered Arduino to a higher-voltage-powered breadbord (between 6 and 12V) safely?

I think as far as i understood the problem, the system or whatever you call is will run on what ever power as long that power is not fed to the arduino that will not be a problem, just connect the two grounds together and power the arduino through the computer and connect the pins to the system accordingly. i think this will solve thus the trivial problem.


How to post HTTP POST requests on my website? I am working on a NodeMCU board to post sensor data on my website service. Basically my project is about POST and GET requests both in single code.

I am succeeding in sending GET requests from my website. However, I just can't post data to my website.

To post I have 2 different links (asp services): one will post data and another will be used to get data same as transmitted by first link.

Here is my code, and also how to post 2 variables in http post request?

#include (ESP8266WiFi.h)
#include (ESP8266HTTPClient.h)

const char* ssid = "oppo";
const char* password = "11111111";
int giSwitchNum = 1, buttonPin = 2;

void setup () {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  pinMode(D1, OUTPUT);
  pinMode(D2, INPUT);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print("Connecting..");
  }
  giSwitchNum = 1;
  Serial.print("Connect");
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
    HTTPClient Post;
    Post.begin("http://lemontechnologies.net/Services/Service.svc/SetData");
    Post.addHeader("operator", "text/plain");
    Post.POST("Key=hi&val=jagrut1");
    String payload = Post.getString();
    Post.end();
  }
  delay(500);
}

void wifi_connect(){
  WiFi.mode(WIFI_OFF);        //Prevents reconnection issue (taking too long to connect)
  delay(1000);
  WiFi.mode(WIFI_STA);        //This line hides the viewing of ESP as wifi hotspot
  //WIFI_STA It's very important !!!!

  WiFi.begin(ssid, password);     //Connect to your WiFi router
  while(WiFi.status() != WL_CONNECTED){
    delay(1000);
    Serial.print(".");
  }

  Serial.println("Wifi connected");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  return;
}


Cannot load anything from library So I installed libraries through the Arduino interface (Sketch > Include Library > Manage Library). Then I check: C:\Users\username\OneDrive\Documents\Arduino\Libraries, and I confirm the new libraries are there.

However, when I compile I always get the error that Arduino cannot find the library, no matter which one I try to import.

I'm on Arduino 1.8.5, Windows. What am I missing?

This was a problem with using your OneDrive folder.

duskwuff wrote:

  This is a known incompatibility between the Arduino IDE and Microsoft OneDrive. A fix should be available soon; in the meantime, move your Arduino sketches out of the OneDrive folder.

The issue with OneDrive folders has been resolved as of version 1.8.6.

https://www.arduino.cc/en/Main/ReleaseNotes

  ARDUINO 1.8.6 2018.08.23

  [ide]

  Updated arduino-builder to 1.4.0:

  parallel build (improve compile speed)
  better reuse of already compiled files
  Windows: fixed build for sketch stored under OneDrive cloud folders

Simply update to a newer version of the Arduino IDE and you will be able to compile and upload your sketch.


Writing new functions into progmem after main program is burned I've been experimenting with writing very basic operating system-like programs on the Arduino, and so far I have been running user-defined programs on a small virtual machine I wrote.  This has been an interesting experience, but the VM runs on an assembly-like language and not C.

I want to be able to do something more.  I would like to be able to write a core OS, and then install new programs, written in C.  The core OS would get user input for which program to run, and then jump to that program.

Now, I know that I can do this trivially by writing the OS along with all of the programs into a single sketch. The programs are then just functions, and the OS just calls those functions.  However, I want to do this with functions I've written after I've burned the main OS.

From what I can tell, this is just a bootloader with additional user functionality.  However, I don't think that's quite right for two reasons:

First, I keep hearing that you can't write to progmem at runtime.  But isn't that what a bootloader does?  Which is correct?

Second, once a user program ends, I should return to the OS.  As far as I understand it, on the ATMega, once the main function terminates it jumps into a no-operation function and that's that.  I'd need it to jump back to the bootloader and continue the bootloader's operation.  Is that even possible?

First, I keep hearing that you can't write to progmem at runtime. But
  isn't that what a bootloader does?

Indeed. My understanding is that non-bootloader code cannot write to
the Flash, except on the smallest AVRs. You may need to check the
datasheet of your target MCU.

  Second, once a user program ends, I should return to the OS.

You could require for the user programs to be linked against a library
you provide. Just implement void exit(int status) in that library and
it will automatically override the version from avr-libc.


Arduino Wireless SD Shield Is it possible to use the Wireless SD shield without the wireless function, or XBEE Module? I do not need it to be wireless it simply was cheaper than any other I could find, so I was wondering if it was possible to use it just like a normal, non-wireless SD Shield? Thanks!

In general, on a combined "Something plus SD card" shield like this the SD card is a completely separate section to the rest of it. The only real exception is on some audio shields (mp3) where the SD card is directly controlled by the audio CODEC chip.

So yes, you can pick and choose which portions of the shield you actually use in your code. Just by not using the bits you don't want to use.


Sending servo position data from one Arduino to another I'm trying to take the position data generated from this servo sweep, and send over serial to another Arduino. The position data is stored as pos in the code I included, what would be the best method for doing this?

/* Sweep
 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
  }
}

Yes, sending data over Serial is as simple as using Serial.write() or it's siblings. When sending data over Serial you have to consider, how you want to send it.

Raw binary data: You can simply use the Serial.write() command, which will send the variable as binary data. If you whatch this on the serial monitor of your PC, you will not see readable numbers, because what is shown there is interpreted as ASCII-encoded data, where every byte value has a corresponding character (for example the value 97 is the letter 'a'). On the other Arduino you just use Serial.read() to write the byte data directly to a variable. This is practical, if you are sending always the same amount of data (like the value of one sensor). If the length of a message is variable, you have to use a delimiter, to mark the end of a message. Here the second way is more save.
ASCII encoded data: You can send your data human readable as ASCII encoded data. The value 128 then would consist of 3 bytes, one for each character. Here you always have to use a delimiter, so that the receiver can tell the values apart. A common message delimiter is the newline character '\n'. On Windows you also often have newline and carriage return '\r' together. For decoding you can use one of the many functions, that convert a string/character array to a number with the wanted format (in your case integer), for example atoi().

Refer to the Serial examples in the Arduino IDE to see the code in action.

Note: Since the value of pos only varies between 0 and 180, you can use one byte to save and transmit it, instead of the 2 bytes the integer uses.


Calculate sensor unique address with a 8 position DIP Switch I have a large amount of sensor boards that I need to be able to configure setting unique addresses. Each sensor is attached to it's own arduino, I'm using a 8 position DIP switch for setting the address.

I have tried diferent approaches. When I switch On and OFF I get random values. I understood that I would be able to get up to 255 possible positions, but without being able to get the proper byte data I would have to manually code each possibility, which seems wrong.

Schematic :

Code

#include "DipSwitchI2C.h"

DipSwitchI2C::DipSwitchI2C(int address)
{
    _address = address;
}

void DipSwitchI2C::begin()
{
    Wire.begin();
}

int DipSwitchI2C::read()
{
    unsigned int address = 0;
    unsigned int value = 0;

    Wire.requestFrom(_address, 1);
    if (Wire.available())
    {
        value = Wire.read();
    }
    Wire.endTransmission();

    for (int i = 0; i < 8; i++)
    {
        address += (value & (1<<i)) > 0;
    }

    return address;
}

Assuming that your switches are on pins 2-9 on an UNO.  Change pins to match what you actually have.

byte addressVal = 0;
for(int i = 2: i<10; i++){
    addressVal <<= 1;
    addressVal += digitalRead(i);
}

This will check each switch and add a 1 to the end of the byte.  On each iteration it shifts the contents of that byte 1 place to the left.  After it reads all the pins you have a byte with a value 0 to 255 depending on the states of the pins.


Read write with half duplex SPI I'm currently struggling interfacing an SPI device using just 3 pins (CLK, DATA, NSS).

Wiring up? Connecting MOSI/MISO together?

How do i read since it's half duplex?

In ESP32 there are flags which can be set (SPI_TRANS_USE_RXDATA, SPI_TRANS_USE_TXDATA). How can i accomplish this in the Arduino environment? i didn't see a such option and the API seems a little bit limited.

Thanks for any advice.

All you need is a single resistor.

simulate this circuit – Schematic created using CircuitLab

When DATA is an input the data from MOSI passes through the resistor to both DATA and MISO.  When DATA is an output the data from DATA goes to MISO and voltage is dropped safely across R1 to the sink or source of MOSI depending on what state it is in.

In other words, when DATA is input it receives from MOSI. When DATA is output MOSI is ignored.

Code wise, it's no different to any other transfer. You just never have any valid data to transfer while receiving. So just transfer anything (0xFF is a common choice).

For example, if you need to send 0x38 first then receive two bytes, you would:

SPI.transfer(0x38);
uint8_t byte1 = SPI.transfer(0xFF);
uint8_t byte2 = SPI.transfer(0xFF);


Is my Arduino destroyed or are the pins destroyed? I made a working model of Bluetooth light control with arduino and Bluetooth. Everything worked fine and then after some time I connected the circuit again it didn't work and the pins 7,10,11,12 aren't working . I was using a Bluetooth shield but I tried the simple LED flash program and even that's not working .

Please suggest any good way of making it working again or at least explain what happened with it.

Try running the blink LED, on a different terminals.
If the LED is working properly, then most likely the pins are destroyed.
Why are they destroyed?
Most likely, you've withdrawn more current than the pins can actually provide.

According to the datasheet of the Arduino uno, the IO pins can handle up to 40mA.

The only possible way to solve this problem is to change the IC (Atmega328) by another one. It's not guranteed that it will work, but the microcontroller is reletively cheap.

The definite answer can not be determined unless you showed us a schematic of your connection.


How to connect a phone's camera to an Arduino? I would like to ask how to connect my phone's camera to an Arduino, just like it is done in this this video. Is anyone familiar with this application they are using?

That video shows a Bluetooth connection between the smartphone and the Arduino.

(A USB connection between the smartphone and the Arduino might be better in some ways).

details

If you want more information after watching a video like this, click the "show more" button underneath the video to see the details.
Those details clearly say "The Nexus S device connects to the IOIO board via Bluetooth, and uses the smartphone's camera in conjunction with OpenCV and the external IR sensors to control the vehicle."
Those details also include a link to
"Android Based Robotics".

The OpenCV image processing software runs on the smartphone. In this autonomous application, the image data never leaves the smartphone. The software on the smartphone reduces the image data to two integers -- the X,Y pixel location of the center of the green ball.

The Arduino and the Bluetooth link can easily handle a few integers at over 200 Hz. Neither one is suitable for handling live video data.

The Arduino could probably act as the controller.
The camera could send the X,Y pixel location of the green ball to the Arduino; while the Arduino collects all the other sensor data; then the Arduino could use that to decide what to do; then send the appropriate control signals to the motor drivers.

However, in this autonomous toy car it appears that the the smart phone acts as a controller.
The Arduino collects all the other sensor data, forwards that data to the smartphone; then software on the smart phone takes that data and the X,Y pixel location of the green ball; then the smartphone decides what motors need to turn; then the smartphone sends the appropriate commands to the Arduino, and the Arduino demultiplexes those commands to the motor drivers.

For even more details on building robots using smartphones and Arduino, see

"Android Based Robotics" ( http://www.socsci.uci.edu/~jkrichma/ABR/ ).
The Tinkernut video
"DIY Smartphone Controlled RC Car" ( https://www.youtube.com/watch?v=xsJ7176fLNw )
goes into more details of how to connect a smartphone to an Arduino via Bluetooth.
Android Based Robotics: ground robot manual
( https://groups.google.com/forum/#!topic/android-based-robotics/_H8Zmvbxx-M )
"Simple RC car for beginners (Android control via Bluetooth)"
( http://solderer.tv/cxemcar/ ) ( via http://english.cxem.net/ ).
Communicate with Your Arduino Through Android (using USB cable)
ArduinoCommander:
"Control your Arduino board from your Android device over Bluetooth, Ethernet or USB"


Timer STM32 #error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting I have installed the library of TimerInterrupt_Generic for ArduinoSTM32 module via Arduino IDE, so i have tried to test the example of library as you can see below:

and i have gotten this error:

TimerInterruptLEDDemo:45:4: error: #error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting.
   #error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting.
    ^
In file included from /home/so/snap/arduino/current/Arduino/libraries/TimerInterrupt_Generic/examples/STM32/TimerInterruptLEDDemo/TimerInterruptLEDDemo.ino:64:0:
/home/so/snap/arduino/current/Arduino/libraries/TimerInterrupt_Generic/src/TimerInterrupt_Generic.h:86:4: error: #error Unsupported Board! Please check your Tools->Board setting.
   #error Unsupported Board! Please check your Tools->Board setting.
    ^
exit status 1
#error This code is designed to run on STM32F/L/H/G/WB/MP1 platform! Please check your Tools->Board setting.

Also, This question is asked here:
https://github.com/khoih-prog/TimerInterrupt_Generic/issues/2

The Roger Clark's STM32 core  you're using is not currently supported. I don't know in the future if I can add that core into the supported list.
You have to use this Arduino_Core_STM32.
Convert to new core by following the intructions in Getting Started


Reduce Sketch Size Help! I dont know what to do?

Sketch uses 3712 bytes (12%) of program storage space. Maximum is 30720 bytes.

Global variables use 210 bytes (10%) of dynamic memory, leaving 1838 bytes for local variables. Maximum is 2048 bytes.

Program:

String texto;
int flag;
void setup() {
Serial.begin(9600);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(7, OUTPUT);//luz stop
pinMode(8, OUTPUT);//faros
}
void loop() {
while (Serial.available())//
{
delay (10);
if (Serial.available() > 0) //verifica que este disponible el puerto serie y verifica que haya algun
caracter
{
char c = Serial.read(); //guara cualquier caracter que haya llegado por el puerto serie
texto += c; //concatenamos
}
} ///Sentencias de control///
if (texto == "1") //compara el contenido de la avariable "texto" con el numero 1
{
digitalWrite(7,LOW); //Apaga la luz stop
digitalWrite(11, LOW);
digitalWrite(12, HIGH);
digitalWrite(10, HIGH);
digitalWrite(9, LOW);
}
if (texto == "3") //compara el contenido de la avariable "texto" con el numero 3
{
digitalWrite(7,LOW); //Apaga la luz stop
digitalWrite(11, HIGH);
digitalWrite(12, LOW);
digitalWrite(10, LOW);
digitalWrite(9, HIGH);
}
if (texto == "2") //compara el contenido de la avariable "texto" con el numero 2
{
digitalWrite(7,LOW); //Apaga la luz stop
digitalWrite(11, LOW);
digitalWrite(12, HIGH);
digitalWrite(10, LOW);
digitalWrite(9, HIGH);
}
if (texto == "4") //compara el contenido de la avariable "texto" con el numero 4
{
digitalWrite(7,LOW); //Apaga la luz stop
digitalWrite(11, HIGH);
digitalWrite(12, LOW);
digitalWrite(10, HIGH);
digitalWrite(9, LOW);
}
if (texto == "5") //Compara el contenido de la avariable "texto" con el numero 5
{
digitalWrite(7,HIGH); //Enciende la luz stop
digitalWrite(11, LOW);
digitalWrite(12, LOW);
digitalWrite(10, LOW);
digitalWrite(9, LOW);
}
if (texto == "6") //Compara el contenido de la avariable "texto" con el numero 6
{
if (flag==1)
{digitalWrite(8, LOW);
flag=0;
}
else if (flag==0)
{digitalWrite(8, HIGH);
flag=1;
}
}
texto = "";
}

Next time, select your code and press ctrl-K... Also align your code (indent it well).

However, you don't need help actually as you have plenty of memory left. As as written:

You only use 12% of program storage space. This might seem a lot having such a small sketch, but most of it is because of library usage/framework (such as the digitalWrite call(s).
210 bytes of dynamic memory is also not something to worry. Btw, this is unrelated to the sketch size, but to your use of (global and other) variables.

So unless you know beforehand your sketch will be much bigger, don't change it because of that reason (too less space).

However, there is another reason, to shorten the sketch, and that is because of duplicated code. As you can see, there is in the entire sketch a lot of repetition (or almost repetition), as in:

if (texto == "5") //Compara el contenido de la avariable "texto" con el numero 5
{
  digitalWrite(7,HIGH); //Enciende la luz stop
  digitalWrite(11, LOW);
  digitalWrite(12, LOW);
  digitalWrite(10, LOW);
  digitalWrite(9, LOW);
}

What you can do to improve it is:

Either use a switch statement instead of the if/else statements
Or create a function that incorporates this condition, together with the following item. This solution is in your case the most clear.

What you do is creating a new function:

void setPins(bool condition, int pin7, int pin11, int pin12, int pin10, int pin9)
{
  if (condition)
  {
    digitalWrite(7, pin7);
    digitalWrite(11, pin11);
    digitalWrite(12, pin12);
    digitalWrite(10, pin10);
    digitalWrite(9, pin9);
  }
}

And you call your function with:

setPins(texto == "5", HIGH, LOW, LOW, LOW, LOW);

And the same for all other conditions. I only used 5 as example.


Help, I want to turn relay constantly on until a difference is detected, but triggered only one instead Help, I want to use arduino to control relay for electricity, i get data from a sensor and when a value is detected it should be constantly on until another detection triggered again, i can get the program to work but triggered only once instead when it should be constantly turned on, here'e my code:

int Pinout = 13;

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

void loop() {
    int val = analogRead(A0);
    if (val <= 500) {
        digitalWrite(Pinout, LOW);
    }
    else {
        digitalWrite(Pinout, HIGH);
    }
}

the relay i am using is a chinese relay module with 3 pin and VCC and GND connected to external power supply, and INput pin to 13 digital pin Arduino and the relay is which i believed is Active LOW, and for analog read i am using moisture sensor

As far as I can see, the relay will stay on when val is less or equal than 500, and stay off when val is higher than 500.

However, there might be a problem when val keeps fastly moving around 500; it will switch on and off quite fast.

To prevent this, you should make two 'triggers', e.g. turn it on when the value <= 480, and turn it off when the value >= 520. When it is in between 480 and 520 it will not change. This will cause less fast changes of the relay. Of course if the initial value is already between 480 and 520 you have to make a choice yourself.


Trying to use Tap Detection solution using ADXL345 with Arduino I am using ADXL345 sensor connecting with Arduino via I2C interface, I am able to test the data at tri-axial axis but as there are some other features also, which I am going to try with Tap detection method as I didn't use TAP THRESH register and instead of that I am using the registers (in decimal) of Tap latency - 33, Tap Duration - 34, Tap Window - 35.

For which I just started with raw code,

#include <Wire.h>

// ADXL345 I2C address is 0x53(83)
#define Addr 0x53

void setup()
{
  // Initialise I2C communication as MASTER
  Wire.begin();
  // Initialise serial communication, set baud rate = 9600
  Serial.begin(9600);

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select bandwidth rate register
  Wire.write(0x2C);
  // Normal mode, Output data rate = 100 Hz
  Wire.write(0x0A);
  // Stop I2C transmission
  Wire.endTransmission();

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select power control register
  Wire.write(0x2D);
  // Auto-sleep disable
  Wire.write(0x08);
  // Stop I2C transmission
  Wire.endTransmission();

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select data format register
  Wire.write(0x31);
  // Self test disabled, 4-wire interface, Full resolution, Range = +/-2g
  Wire.write(0x08);
  // Stop I2C transmission
  Wire.endTransmission();
  delay(300);
 }

 void loop()
 {
   unsigned int data[3];
   for(int i = 0; i < 3; i++)
   {
    // Start I2C Transmission
    Wire.beginTransmission(Addr);
    // Select data register
    Wire.write((33 + i));
    // Stop I2C transmission
    Wire.endTransmission();

    // Request 1 byte of data
    Wire.requestFrom(Addr, 1);

    //Read Three Bytes
    if(Wire.available() == 1)
    {
      data[i] = Wire.read();
    }
 }
   int TAP_DUR = data[1];
   int TAP_LAT = data[2];
   int TAP_WIN = data[3];

   Serial.print("TAP DURATION: ");
   Serial.println(TAP_DUR);
   Serial.print("TAP Latency: ");
   Serial.println(TAP_LAT);
   Serial.print("Tap Window : ");
   Serial.println(TAP_WIN);
   delay(3000);
   }

which is not working properly, and giving the result like this

TAP DURATION: 0
TAP Latency: 0
Tap Window : 22272
TAP DURATION: 0
TAP Latency: 0
Tap Window : 22272
TAP DURATION: 0
TAP Latency: 0
Tap Window : 22272

The main aim is to test the no of tap count and duration between single tap and double tap rather than using any library I need to work with the code I have been making.

Suggestion and bits of advice to make it work will be welcome.

the arrays are indexed from 0 but you assign to TAP_ variables array values indexed 1,2,3.

Are you sure the sensor is wired ok? Did it work with a library example?


What to do after prototyping? I want to make a USB gamepad, and I've heard that an Arduino would be great for this kind of project. But before I start to work on it, I want to make sure I understand some things. Here are my basic diagrams of what the project will look like during prototyping and after prototyping:

Do the diagrams look right? Am I understanding the process correctly? For me to properly build a final circuit, I would have to emulate all the necessary (the most important one being the USB) circuitry that an Arduino has around it's microprocessor.

And my final question is, how would I load my program on to the microprocessor (with and without the "Arduino-like" USB circuitry)?

Yes, your thinking is pretty much correct.

You can place an ATMega32U4 chip and the associated required circuitry within your own circuit design. The required circuitry is actually quite simple - a crystal for the CPU clock, a few capacitors (load capacitors for the crystal, and decoupling), two 22Ω termination resistors for the USB bus, and a 10KΩ pullup on the reset pin. That's about it (besides power of course).

As far as programming goes, you can either install a bootloader (butterfly - like the Leonardo etc) that works through the USB, or you can directly program the chip using ICSP. It's best to provide an ICSP header anyway (it's the SPI pins plus RESET basically), and if you have done that (which you'd need really to be able to get a bootloader on there) then you may as will skip the bootloader entirely and just program direct through the ICSP header. Of course, you'll need some kind of programmer (an Arduino can do the job at a pinch, but it's worth spending the $10 to get a cheap AVR programmer from eBay).


Arduino randomly freezes during runtime? I'm currently trying to create a traffic simulation project on Arduino, where it can change lights, open a gate, and turn on street lamps based on light. If anybody could help me diagnose why my arduino is behaving this way, that'd be extremely appreciated. Here is my code, if it helps you understand.

//Libraries Used
#include<Servo.h>

//Variable Declaration
int red1 = 10;
int yellow1 = 9;
int green1 = 8;
int red2 = 13;
int yellow2 = 12;
int green2 = 11;
int debug = 3;
int PIR = 5;

int button1 = 2;
int buttonState = 0;

int light = 0;

unsigned long previousTime = 0;
unsigned long currentTime = 0;
int currentState = 0;

int currentPIR = 0;
int pirState = LOW;

Servo servo;

void setup()
{
  pinMode(red1, OUTPUT);
  pinMode(yellow1, OUTPUT);
  pinMode(green1, OUTPUT);
  pinMode(red2, OUTPUT);
  pinMode(yellow2, OUTPUT);
  pinMode(green2, OUTPUT);
  pinMode(debug, OUTPUT);

  pinMode(PIR, INPUT);

  pinMode(button1, INPUT);

  servo.attach(4);
  servo.write(90);
}

void loop()
{

  currentPIR = digitalRead(PIR);
  if(currentPIR == 1){
    servo.write(180);
  }else{
    servo.write(90);
  }

  buttonState = digitalRead(2);
  light = analogRead(A0);

  if(light > 100){
    digitalWrite(debug, HIGH);
  }else{
    digitalWrite(debug, LOW);
  }

  if(buttonState == HIGH){
    if(currentState == 3){
      digitalWrite(debug, HIGH);
      currentState++;
    }
  }
  //Using millis() instead of delay(), so program doesn't pause completely.
  currentTime = millis();
  changeLights();
}

void changeLights(){
  if(currentState == 0){
    //Red, Green
    digitalWrite(red2, LOW);
    digitalWrite(red1, HIGH);
    digitalWrite(green2, HIGH);
    asyncDelay(4000);
  }
  else if(currentState == 1){
    //Red, Yellow
    digitalWrite(green2, LOW);
    digitalWrite(yellow2, HIGH);
    asyncDelay(2000);
  }
  else if(currentState == 2){
    //Red, Red
    digitalWrite(yellow2, LOW);
    digitalWrite(red2, HIGH);
    asyncDelay(750);
  }
  else if(currentState == 3){
    //Green, Red
    digitalWrite(red1, LOW);
    digitalWrite(green1, HIGH);
    asyncDelay(4000);
  }
  else if(currentState == 4){
    //Yellow, Red
    digitalWrite(green1, LOW);
    digitalWrite(yellow1, HIGH);
    asyncDelay(2000);
  }
  else if(currentState == 5){
    //Red, Red
    digitalWrite(yellow1, LOW);
    digitalWrite(red2, HIGH);
    asyncDelay(750);
  }
}

void asyncDelay(int delayTime){
  if(currentTime - previousTime == delayTime){
    currentState++;
    previousTime = currentTime;
    if(currentState == 6){
      currentState = 0;
    }
  }
}

You should replace:

if(currentTime - previousTime == delayTime){

with

if(currentTime - previousTime >= delayTime){

There is always a chance that, since you are using a servo which is quite intensive with interrupts, that millis() may skip a beat and that statement can never be true.


USB MIDI HID with the ATmega32u4? There are existing projects that allow the Uno and other devices using the ATmega8u2 to operate as a USB MIDI HID, such as MocoLUFA. Unfortunately, as far as I am aware, these require uploading new firmware that isn't compatible with programming via the Arduino UI.

Are there any similar projects for the ATmega32u4 (Leonardo, Micro)?

Is it possible to use an Arduino as a USB MIDI HID, while still being able to program it as normal?

The teensy series from pjrc.com allows USB MIDI natively (full USB speed!).  It works well and does not require any firmware tomfoolery.  It can also do HID keyboard/mouse/joystick natively as well.

There's the 2.0, which is 32u4, and the 2.0++ which has more pins and memory.  If you want to step off the Atmel reservation the teensy 3.0 and 3.1 have more speed and memory; in a couple of weeks they are coming out with a Teensy LC which is a 3 with less bells and whistles for cheaper.


Ublox GPS with Arduino Mega 2560 not working Recently I bought a GPS module (ublox neo-6M-0-001) for my Arduino Mega 2560. I connected Vcc and Gnd (LED at GPS module glows blue and sometimes blinking).

GPS module RX port is connected to the Arduino's TX3, Port 14.
GPS module TX port is connected to the Arduino's RX3, Port 15.

As a first step I just want to print the serial data received from the GPS module:

#include "SoftwareSerial.h"

SoftwareSerial mySerial(15, 14); // RX, TX

void setup() {
  Serial.begin(9600);
  Serial.println("uBlox Neo 6M Test");
  mySerial.begin(9600);
}

void loop() {
   if (mySerial.available())
     Serial.write(mySerial.read());
}

Saldy, there is no data received from the GPS module. According to the datasheet the baud rate 9600 seems to be correct.

Do I need to configure the GPS module somehow before it delivers data? Do I need to buy an external antenna?

Thanks for your help.

The Arduino Mega 2560 has three additional hardware serial ports. Why not use one of them instead? Serial1 on pins 19 (RX) and 18 (TX).

void setup()
{
  Serial.begin(9600);
  Serial.println("uBlox Neo 6M Test");
  Serial1.begin(9600);
}

void loop() // run over and over
{
  if (Serial1.available())
     Serial.write(Serial1.read());
}

Cheers!


Reading sensor with current ouput with Arduino I am having diffuclt times with this sensor, so I kndliy ask for your help!
The sensor is named "SPUVA-CS-C3535-A", datasheet here.
The sensor I use (cs3535) has just two pins (+ and -).
From my undesrstanding the ouput is a current corresponding on the UV light exposed to this sensor.
Max value of the current is difficult to understand from the datasheet that also do not have a typical suggested circuit. It seems that a medium value is 200nA, it seems really low!
I have connected (+) of the sensor to 3.3V, (-) of the sensor to A0, and a 220ohm resistor from A0 to Gnd. But readings are always 0.
Any help would be really appreciated! Thanks

The "sensor" is just a photodiode that is sensitive to UV. You use it the same as any photodiode.

The simplest (and crudest) way is to use a very large (eg 1MΩ) pullup resistor to 5V on an ADC pin, then connect the sensor (reverse biased) between the ADC pin and GND.


Why are my if statements acting like the condition is always true? Here is my code. My issue is is that the keys are getting "pressed" even though there is nothing jumping any of the pins on the Arduino.

// UNO-HIDKeyboard-Library - Version: Latest
// This program has been created by pcs3rd.
// Please do not change this line.
#include <HIDKeyboard.h>
HIDKeyboard keyboard;   // Initiate keyboard
// Pin deffanitions and variables...
int key0 = 2;   // Button 0 (Unused but optional)
int key1 = 3;   // Button 1
int key2 = 4;   // Button 2
int key3 = 5;   // Button 3
int key4 = 6;   // Button 4
int key5 = 7;   // Button 5
int key6 = 8;   // Button 6
int key7 = 9;   // Button 7
int key8 = 10;  // Button 8
int led0 = 13;  // Indicator light.
int state0 = 0; // Button 0
int state1 = 0; // Button 1
int state2 = 0; // Button 2
int state3 = 0; // Button 3
int state4 = 0; // Button 4
int state5 = 0; // Button 5
int state6 = 0; // Button 6
int state7 = 0; // Button 7
int state8 = 0; // Button 8

void setup() {
   keyboard.begin();    // Start keyboard emulation
   Serial.begin(9600);  // Start Serial Output
   delay(300);          // Wait to be recognized be PC.
   pinMode(key1, INPUT_PULLUP); // set pin mode
   pinMode(key2, INPUT_PULLUP); // set pin mode
   pinMode(key3, INPUT_PULLUP); // set pin mode
   pinMode(key4, INPUT_PULLUP); // set pin mode
   pinMode(key5, INPUT_PULLUP); // set pin mode
   pinMode(key6, INPUT_PULLUP); // set pin mode
   pinMode(key7, INPUT_PULLUP); // set pin mode
   pinMode(key8, INPUT_PULLUP); // set pin mode
   pinMode(led0, OUTPUT);       // set pin mode
   Serial.println("Startup Completed!");
}

void loop() {
   // write state info to vars
   state0 = digitalRead(key0); // Button 0
   state1 = digitalRead(key1); // Button 1
   state2 = digitalRead(key2); // Button 2
   state3 = digitalRead(key3); // Button 3
   state4 = digitalRead(key4); // Button 4
   state5 = digitalRead(key5); // Button 5
   state6 = digitalRead(key6); // Button 6
   state7 = digitalRead(key7); // Button 7
   state8 = digitalRead(key8); // Button 8
   if (state0 == HIGH) {       // Button 0
     digitalWrite(led0, HIGH);
     // keyboard.pressSpecialKey(0x68); (You can enter a scancode instead of 0x68,)
     Serial.println("state0");
     delay(30);
   }
   if (state1 == HIGH) { // Button 1
     digitalWrite(led0, HIGH);
     keyboard.pressSpecialKey(0x68);
     Serial.println("state1");
     delay(30);
   }
   if (state2 == HIGH) { // Button 2
     digitalWrite(led0, HIGH);
     keyboard.pressSpecialKey(0x69);
     Serial.println("state2");
     delay(30);
   }
   if (state3 == HIGH) { // Button 3
     digitalWrite(led0, HIGH);
     keyboard.pressSpecialKey(0x6A);
     Serial.println("state3");
     delay(30);
   }
   if (state4 == HIGH) { // Button 4
     digitalWrite(led0, HIGH);
     keyboard.pressSpecialKey(0x6B);
     Serial.println("state4");
     delay(30);
   }
   if (state5 == HIGH) { // Button 5
     digitalWrite(led0, HIGH);
     keyboard.pressSpecialKey(0x6C);
     Serial.println("state5");
     delay(30);
   }
   if (state6 == HIGH) { // Button 6
     digitalWrite(led0, HIGH);
     keyboard.pressSpecialKey(0x6D);
     Serial.println("state6");
     delay(30);
   }
   if (state7 == HIGH) { // Button 7
     digitalWrite(led0, HIGH);
     keyboard.pressSpecialKey(0x6E);
     Serial.println("state7");
     delay(30);
   }
   if (state8 == HIGH) { // Button 8
     digitalWrite(led0, HIGH);
     keyboard.pressSpecialKey(0x0F);
     Serial.println("state8");
     delay(30);
   }
   digitalWrite(led0, LOW);
   Serial.println("scan");
   delay(30);
}

Yet, even though I have 'if' statements, the code still gets executed, as shown in my monitor:

Startup Completed!

state0
hstate1
istate2
jstate3
kstate4
lstate5
mstate6
nstate7
state8
scan
state0
hstate1
istate2
jstate3
kstate4
lstate5
mstate6
nstate7
state8
scan

Are there any hints to what could be going on? I reformatted the code for readability, but it is pretty much the same as before. Also, I am not using pin 0 or one. I am using 13 for onboard LED.

Microcontroller pins tend to read LOW when left floating (but not always!). However, pin 1 is used to communicate with the USB-UART converter, and I believe it is set HIGH in the idle state. So assuming you are not pressing any buttons, keys 2-8 will be in the LOW state by default, but key 1 will be HIGH. Hence when defaultCase = HIGH;, the first if is triggered. When defaultCase = LOW; all if's but the first one fire up. Solution — don't use digital pin 1 (edit: avoid pin 0 and maybe 13 as well).

Edit: The answer above refers to the original code without the pull-up resistors enabled.


Reading a varying voltage into Arduino Using an Arduino Nano and a current transformer  (CT), I'm trying to sense the current flowing through a 120 V 60 Hz line.

Circuit

CT outputs 0-1&nbsp;V according to its specifications. This output is biased AREF/2 = 2.5 V.

analogRead Values

The x-axis represents the index number of the ADC sample, while the y-axis represent the ADC value (0-1024). Sampling rate is about 9 kHz. Peak-to-peak difference is about 1026 samples.

Is this waveform what you would expect from the CT? Why are there regions where the values are flat, rather than varying continuously?

Furthermore, if we look at the curve part of the plot, why is Arduino reading values both above 512 and below 512 alternately? It reads a value above 512, then a value below 512, then a value above 512 and so on.

Time taken for an analogRead was measured to be 110 microseconds for my setup and there are 1026 samples between the waveform peaks. That means there will be about 9 peaks in 1 second, although I would expect 60 peaks since we are sensing a 60 Hz line. What do you make out of this? There's a capacitor, C1, in the circuit, would it have anything to do with this?

Are these analogRead values suitable to be used to calculate the RMS voltage, and hence the RMS current passing through the wire being sensed? The final goal of this is to calculate the power usage after determining the RMS current flowing through the wire.

Sketch used to get values for plot

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

void loop() {
   double sensorValue = analogRead(1);
   Serial.println(sensorValue)
}

Actual analogRead data points in the bump regions

487
534
487
535
488
537
484
536
487
538
486
536
484
540
484
539
485
540
483
540
484
541
481
539
481
540
484
540
480
543
484
539
481
540
484
541
486
542
485
538
485
538
488
535
489
534
491
530
491
529
493
531
492
526
498
526
499
524
499
520
503
518
502
518
507

Plot of analogRead values

The analogRead values are now stored in a buffer before being transmitted over Serial. There are now 55 ADC datapoints making up 1 period. Considering the analogRead time is 110 µs, each cycle takes 6.05 ms, giving us a frequency of 165 Hz! What may have gone wrong?

void loop() {
    double sensorValue = analogRead(1);
    char buf[32];

    dtostrf(sensorValue, 8, 2, buf);
    value = buf;

    if (stop == 0) {
        if (i < 10000) {
            message += ',';
            message += value;
            i++;
        }
        else {
            stop = 1;
            Serial.println(message);
        }
    }
}

Regarding your measurements, I would completely disregard the first set with Serial.println() in the loop. I would exepect the timing of this to be unreliable.

Your second set of data that you captured in a buffer looks correct, but your Frequency Estimation / timing may be wrong. I would invert a Digital Output at each loop iteration. You can measure the frequency of that with a Multimeter and your ADC sample rate would be twice that value.

For a PC or laptop power supply that's quite a common current waveform.

Without effective Power Factor Correction the current signal shown below would be quite typical (source: http://www.nlvocables.com/blog/?p=300)

You will need to calculate RMS values and it would be wise to filter the signal.

Here's an instructable I wrote on how to build and code an Arduino Yun based Electricity Monitor with Cloud Support / Temboo and Google Drive. It should be of some help to you.


PWM of a frequency signal? Working on my first real sketch, so will try to keep this short.  Feel free to ask more info if needed.

To power a flyback transformer I need to apply PWM -to- a PWM signal.  The easiest way to describe this is that while a standard PWM signal is 'on' for some set time, then 'off' for the remainder of the period, I need to send a signal where the 'on' is actually a 14kHz square wave of 50% duty...then pulse this signal ~1 to 100% duty at ~500Hz.

No problem with the 14kHz PWM - I found the PWM.h library and set that up.

But what is the best way to chop that up with a second PWM at, say 500Hz?

With some amount of kludge, can I 'bit bang' it with DO - WHILE?  Will WHILE read a variable outside the loop?  Are there easier ways?

i=1;
do {                                //Pulse microsecond 'frames' of high freq signal?
                                    //ie 14kHz carrier PWM'd at 500Hz = 2000 microseconds per 'frame' cycle
                                    //at 50% duty would be 1000 micros high and 1000 micros low

    pwmWrite( outpin, 128 );        //Turn on 14kHz carrier at 50% duty
    delayMicroseconds(1000);        //Delay to generate the 'HIGH' portion of the frame
    pwmWrite( outpin, 0 );          //Turn 14kHz carrier off
    delayMicroseconds(1000);        //Delay to generate the 'LOW' portion of the frame
   } while (i == 1);                //...and keep doing loop while the state is '1' or 'ON'

delay(1000);                        //?Will this allow the above loop  to repeat while waiting here for 1 second?
i=0;                                //i != 1, so break out of the while loop above?
                                    //then continue doing other stuff below...

Any help greatly appreciated.

On an Arduino Mega (or an Uno with the ATmega328P replaced with an ATmega328PB, but then you'd have to adapt the code slightly), this can be done via the output compare modulator:

void setup() {
  // CTC, OC0A toggle on compare match, prescale 1/8
  TCCR0A = _BV(COM0A0)|_BV(WGM01);
  TCCR0B = _BV(CS01);

  // toggle every 35.5 μs at 16 MHz and 1/8 prescale
  OCR0A = 70;

  // phase and frequency correct PWM, TOP is OCR1A, OC1C clear going up and set going down, no prescale
  TCCR1A = _BV(COM1C1)|_BV(WGM10);
  TCCR1B = _BV(WGM13)|_BV(CS10);

  // period of 2 ms at 16 MHz and no prescale
  OCR1A = 16000;

  // on-time of 1 ms at 16 MHz and no prescale
  OCR1C = 8000;

  // no interrupts from the timers
  TIMSK0 = 0;
  TIMSK1 = 0;

  // only output a 1 when both timers are outputting a 1
  PORTB &= ~_BV(PORTB7);

  // halt the timers and reset the prescaler
  GTCCR |= _BV(TSM);
  GTCCR |= _BV(PSRSYNC);

  // reset both timers
  TCNT0 = 0;
  TCNT1 = 0;

  // enable output
  DDRB |= _BV(DDB7);

  // let the timers run
  GTCCR &= ~_BV(TSM);
}

void loop() {
  // Just adjust the frequencies and duty cycle as required here.
  // Everything is handled by the hardware and takes effect immediately upon writing to the register.
  // OCR1A: the desired period of the slower signal, in 8ths of microseconds. Can be up to 65535.
  // OCR1C: the desired on-time of the slower signal, in 8ths of microseconds. Can be up to 65535.
  // OCR0A: 1 less than the desired period of the faster signal, in microseconds. Can be up to 255.
  // The on-time of the faster signal is always half of the period.
  // If necessary, you can trade precision for more range for any of the above values by adjusting the prescaler.
}

With that sketch, pin 13 on the Mega will have the desired waveform. There's two big advantages to this method. First, it doesn't require any CPU resources at all (no loops or interrupts) once it's set up, so you can dedicate all of loop to reading the potentiometer and adjusting the duty cycle without worrying about glitches in the output. Second, being entirely hardware controlled means its output will be accurate and perfectly consistent (the 500 Hz component is perfect, and the 14 kHz component is approximately 14085 Hz). The one disadvantage, though, is that millis and everything else in the Arduino library that uses timers internally won't work quite right, since we're using the same hardware timers that they depend on.


Sine wave PWM Arduino Micro I'm trying to generate a sine wave on my Arduino micro.
I used this code.

int Pin = 9;

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

void loop()
{
 float something = millis()/10000.0;
 int value = 128.0 + 128 * sin( something * 2.0 * PI  );
 analogWrite(Pin,value);
}

I have a low pass filter at the output of the pin to smooth the wave. The problem is : I get a nice square wave with a duty cycle from 0 to 100%, but not a sine wave. Ideally, I'd like to set a frequency of 10 Hz.
Can anyone tell me where I made a mistake ? Thanks a lot !!!

it is how PWM works. digital pins can do only 1 and 0.


Using Modbus-RTU with Arduino and temperature controller I'm trying to connect with a 4 channel temperature controller using Arduino Modbus Library.

This is a part of my temperature controller datasheet. It has register for read PV of each channel.

I have studied example code of the library and now i'm trying to read PV of each channel.

So, I have modified the example code as below,

#include <ModbusMaster.h>

    // instantiate ModbusMaster object
    ModbusMaster node;

    void setup()
    {
      // use Serial (port 0); initialize Modbus communication baud rate
      Serial.begin(19200);

      // communicate with Modbus slave ID 2 over Serial (port 0)
      node.begin(2, Serial);
    }

    void loop()
    {
      static uint32_t i;
      uint8_t j, result;
      uint16_t data[6];

      i++;

      // set word 0 of TX buffer to least-significant word of counter (bits 15..0)
      node.setTransmitBuffer(0, lowWord(i));

      // set word 1 of TX buffer to most-significant word of counter (bits 31..16)
      node.setTransmitBuffer(1, highWord(i));

      // slave: read (4) 16-bit registers starting at register 2 to RX buffer
      result = node.readHoldingRegisters(1, 4);

      // do something with data if read is successful
      if (result == node.ku8MBSuccess)
      {
        for (j = 0; j < 4; j++)
        {
          data[j] = node.getResponseBuffer(j);
        }
      }

    }

My questions are,
Explain below lines in the code

          // set word 0 of TX buffer to least-significant word of counter (bits 15..0)
      node.setTransmitBuffer(0, lowWord(i));

      // set word 1 of TX buffer to most-significant word of counter (bits 31..16)
      node.setTransmitBuffer(1, highWord(i));

I didn't  pass any request to slave, So, can I get the 4 PV value like this?
If not, please explain how can I do it.

The setTransmitBuffer calls are for writeMultipleRegisters, which you removed from the example.

The first parameter of the readHoldingRegisters is the address of the register. The second parameter is the count of registers to read.

Your sketch doesn't show the retrieved data. You have no indication of success or fail.


Timer interrupt triggers too often The following question is based on the Arduino Pro Mini (8MHz, 3.3V)

I'm in process of developing (yet another) LED strip driver shield. For that I wrote a simple control loop, that adjusts the channel brightness (PWM duty cycle) to a given target value with a smooth transition.

For testing purposes I configured Timer1 with a 0.5Hz interval to randomly assign new target values. This works almost as intended. When watching the values you can see the constant value periods and completely random, fast changing periods in between (picture generated with Arduino built-in plot). The curved, rather smooth lines are the PWM outputs following the target value (that part is confirmed to work):

The relevant code responsible for the changing of the target value is

ISR(TIMER1_COMPA_vect) //timer1 interrupt 0.5Hz
{
  for(auto it = 0; it < 4; ++it)
        channel_target[it] = random(0, 255);  // assign a random value between 0..255 (max for pwm)
}

My assumption is, that the ISR is called very fast in the fuzzy intervals but since I havn't done much with arduinos yet, I'm not familiar on what kind of background functions might interfere with that.

For completeness the full code:

double          channel[4];
uint8_t         channel_target[4];
const double    channel_k_p[4]      = { 0.001, 0.001, 0.001, 0.001 };
const double    channel_k_i[4]      = { 0.01, 0.01, 0.01, 0.01 };
double          err;
const uint8_t   led_pins[4]         = { 3, 5, 6, 9 };
char            serial_buffer[100];

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

    for(auto it = 0; it < 4; ++it)
        channel[it] = 0;

    for(auto it = 0; it < 4; ++it)
    {
        pinMode(led_pins[it], OUTPUT);   // sets the pin as output
        analogWrite(led_pins[it], 0);
    }

    cli();//stop interrupts

    TCCR1A = 0;// set entire TCCR1A register to 0
    TCCR1B = 0;// same for TCCR1B
    TCNT1  = 0;//initialize counter value to 0
    // set compare match register for 1hz increments
    OCR1A = 15624;// = (8*10^6) / (0.5*1024) - 1 (must be <65536)
    // turn on CTC mode
    TCCR1B |= (1 << WGM12);
    // Set CS10 and CS12 bits for 1024 prescaler
    TCCR1B |= (1 << CS12) | (1 << CS10);
    // enable timer compare interrupt
    TIMSK1 |= (1 << OCIE1A);

    //set timer2 interrupt at 500Hz
    TCCR2A = 0;// set entire TCCR2A register to 0
    TCCR2B = 0;// same for TCCR2B
    TCNT2  = 0;//initialize counter value to 0
    // set compare match register for 8khz increments
    OCR2A = 248;// = (8*10^6) / (500*64) - 1 (must be <256)
    // turn on CTC mode
    TCCR2A |= (1 << WGM21);
    // Set CS21 bit for 64 prescaler
    TCCR2B |= (1 << CS21) | (1 << CS20);
    // enable timer compare interrupt
    TIMSK2 |= (1 << OCIE2A);

    sei();  // reactivate interrupts

    randomSeed(analogRead(0));
}

void loop()
{
    for(auto it = 0; it < 4; ++it)
    {
        sprintf(serial_buffer, "%d ",  channel_target[it]);
        Serial.write(serial_buffer);
    }

    for(auto it = 0; it < 4; ++it)
    {
        sprintf(serial_buffer, "%d ", round(channel[it]));
        Serial.write(serial_buffer);
  }
    Serial.write("\n");

    delay(100);
}

ISR(TIMER2_COMPA_vect)  // timer2 interrupt at 1kHz
{
    // ******************************
    // Channel brightness control loop
    for(auto it = 0; it < 4; ++it)
    {
        err = channel_target[it] - channel[it];

        channel[it] += err * channel_k_p[it];           // proportional
        channel[it] -= err * 0.002 * channel_k_p[it];   // integral

        if(channel[it] > 255)
            channel[it] = 255;
        analogWrite(led_pins[it], floor(channel[it]));
    }
}

ISR(TIMER1_COMPA_vect) //timer1 interrupt 0.5Hz
{
  for(auto it = 0; it < 4; ++it)
        channel_target[it] = random(0, 255);  // assign a random value between 0..255 (max for pwm)
}

The analogWrite() function generates a PWM output signal using a
hardware timer. Output on pin 3 is driven by timer 2, whereas
output on pin 9 is driven by timer 1. Here, you are trying to
use these timers for PWM generation and for your own code timing at
the same time. This cannot work. Either you let the Arduino core library
use the timers for analogWrite(), or you take them for you, but not
both.

The solution to your problem is very simple. Nothing in your code really
requires a timer to start with. You can handle both the brightness
control loop and the value changes using the technique of the Blink
Without Delay Arduino tutorial:

const uint32_t TARGET_CHANGE_PERIOD = 500000;
const uint32_t BRIGHTNESS_UPDATE_PERIOD = 1000;

void loop()
{
    uint32_t now = micros();
    static uint32_t last_target_change;
    if (now - last_target_change >= TARGET_CHANGE_PERIOD) {
        last_target_change += TARGET_CHANGE_PERIOD;
        // Change the brightness targets.
    }
    static uint32_t last_brightness_update;
    if (now - last_brightness_update >= BRIGHTNESS_UPDATE_PERIOD) {
        last_brightness_update += BRIGHTNESS_UPDATE_PERIOD;
        // Update the channel brightnesses.
    }
}


Buffer overflow error in ESP8266_SoftwareSerial library I am running into buffer issues when running the Firmware.ino example here.

The output from my Arduino serial log on baudrate 115200 (I put the ESP on baudrate 9600):

Begin
01:17:15.538 -> Baudrate set success
01:17:15.585 -> Station + softAP - OK
01:17:18.631 -> Joining AP successful, IP: 192.168 r⸮+@⸮
01:17:18.991 -> Single Mode OK
01:17:18.991 -> Sending Request to www.google.com
01:17:19.084 -> create tcp - OK
01:17:19.710 -> not sentbuffer is full!
01:17:20.022 -> HZiw93GUFmVJYFz-yRmahGURP_UBbRb4EF0Ahwzx8MJ1GOyC5Z0dns8UD41G8kUqnL0oxNPxa6xF9nAqNF3X3B_hKW11zoyaBPn8trvUNt-69qbFCNOZwNjgoaloKbOQs7NN-B3tpmwFKpHfKsfKyZfiMdhulN3SgZMhewYBg9c; expires=Wed, 05-Feb-2020 05:17:18 GMT; path=/; domain=.google.com; HttpOnly
01:17:20.162 -> Accept-Ranges: none
01:17:20.162 -> Vary: Accept-Encoding
01:17:20.209 -> ConnecS,
01:17:24.179 -> Sending Request to www.google.com
01:17:24.774 -> create tcp - ERROR
01:17:28.759 -> Sending Request to www.google.com
01:17:29.432 -> create tcp - ERROR
01:17:33.402 -> Sending Request to www.google.com
01:17:34.021 -> create tcp - ERROR
01:17:38.028 -> Sending Request to www.google.com
01:17:38.669 -> create tcp - ERROR
01:17:42.681 -> Sending Request to www.google.com
01:17:43.294 -> create tcp - ERROR
01:17:47.298 -> Sending Request to www.google.com
01:17:47.954 -> create tcp - ERROR
01:17:51.925 -> Sending Request to www.google.com
01:17:52.595 -> create tcp - ERROR
01:17:56.563 -> Sending Request to www.google.com
01:17:57.204 -> create tcp - ERROR
01:18:01.222 -> Sending Request to www.google.com
01:18:01.871 -> create tcp - ERROR
01:18:05.839 -> Sending Request to www.google.com
01:18:06.460 -> create tcp - ERROR
01:18:10.456 -> Sending Request to www.google.com
01:18:10.596 -> create tcp - OK
01:18:11.049 -> buffer is full!
01:18:11.049 ->
01:18:11.049 ->
01:18:11.049 -> +IPD,1430:HTTP/1.1 200 OK
01:18:11.096 -> Date: Tue, 06 Aug 2019 05:18:09 GMT
01:18:11.096 -> Expires: -1
01:18:11.096 -> Cache-Control: private, max-age=0
01:18:11.143 -> Content-Type: text/ht
l; charset=ISO-8859-1
01:18:11.143 -> P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
01:18:11.190 -> Server: gws
01:18:11.190 -> X-XSS-Protection: 0
01:18:11.190 -> X-Frame-Options: SAMEORIGIN
01:18:11.224 -> Set-CooS,
01:18:15.192 -> Sending Request to www.google.com
01:18:15.822 -> create tcp - ERROR
01:18:19.849 -> Sending Request to www.google.com
01:18:20.473 -> create tcp - ERROR

As you can see, at first it starts ok, gives a buffer error, runs in error for a while, then runs OK again. This happens a couple times, then it runs only in error. I imagine this is some issue with the buffer of the ESP or the Arduino, but I'm not sure how to diagnose it further.

Things I have tried to fix the error:
 - As mentioned in the Firmware.ino example comments, I uncommented #define ESP8266_USE_SOFTWARE_SERIAL
 - Also as mentioned in the comment, I changed line 42 from 64 to 256. It didn't work either time.
 - There is a MAX_BUFFER_SIZE in the included ESP8266.h library that I also changed, from 300 to 256, because I thought that might help, but the error persisted.

There's some heavy String usage in that library, would not recommend it for anything you want to be stable, especially with an Uno.

The library seems to create a connection by first clearing the SoftwareSerial buffer and then issuing the right AT command. It waits for 500ms for a response before giving up. I suspect the wait interval is sometimes not long enough for the module to receive, parse and handle the command before responding. So you should try increasing it to 2000 ms at line 773.

The buffer is full message just refers to the library's own buffer for holding received data, which is 300 bytes by default. The buffer's getting filled so quickly (and the SoftwareSerial internal buffer likely overrun too) because you're loading a webpage like Google's which has more than 300 bytes in the response header alone. It's even possible that by the time the next request commences with another AT command, the ESP8266 is still dumping the response from the previous request, and so the command's response is still way down the queue and so doesn't get read before the timeout.

Instead, try loading a simple webpage like httpbin.org/ip. That is, at lines 952, 954:

char* request =  "GET /ip HTTP/1.1\r\nHost: www.httpbin.org\r\nConnection: close\r\n\r\n";

if (createTCP("www.httpbin.org", 80))


Relationship between avrdude's "programmer" and bootloaders I'm trying to understand the "programmer-id" concept, as specified in -c avrdude's option.

avrdude asks me to choose a "programmer-id" among many it knows of.
Let's say (just as an example) I have a Arduino 2560 to which I connect via USB, and I want to program it using the bootloader.  Then, in this scenario,
is one programmer-id and just one supposed to work?

More in general, one has

1) some particular board (MCU, -p in avrdude)

2) some particular programming method/connection (JTAG, ISP, development board, USB/serial,  etc)

3) (if using bootloader) some particular bootloader code in Flash.

How are these things related with the programmer selection? I guess that some (most?) programmers-ids are specific to some programmer connection/method (AND probably with some hardware family?), and they have nothing to do with the bootloader.  What is the programmer to use for a standard Arduino with bootloader, connected via USB? What more can be said?

Furthermore, the Arduino IDE lets me choose "Upload" and "Upload Using Programmer" (the first works for me, the second doesn't). Why this distinction? Isn't a programmer always used? What does the IDE do, under the hood (does it call avrdude?) when choosing "Upload" ?

If you are using the bootloader, you are not using a programmer. The programmer, when used, is connected to the ICSP pins on the Arduino. The bootloader however expects a well-defined sequence of data from the Arduino through the serial port immediately after reset. The bootloader recognizes that (if received) and reprograms the flash.

If you turn on verbose mode for uploading you will see the programmer type:

-carduino

That is, the Arduino is using the bootloader programming method.

See my post here: What happens when code is uploaded using the bootloader?

  Furthermore, the Arduino IDE lets me choose "Upload" and "Upload Using Programmer" (the first works for me, the second doesn't).

Yes, with "Upload Using Programmer" you need a programmer, such as the AVRISP which you would plug into your USB port, and then select that as the type of programmer to use. In this case, your Arduino does not need to be plugged into the USB as the serial port is not used for programming.

Note that some programmers supply Vcc (ie. +5V) to the Arduino and some don't. The AVRISP doesn't.

  Furthermore, it seems that that "Optiboot" is a different bootloader than the standard included in the Arduino.

As far as I know, recent Arduino Unos (and probably others) ship with Optiboot. Its main advantage is that it is smaller (only 512 bytes).

  More in general, do avrdude need to know the particular bootloader?

I think the smaller boards use STK500 protocol (see links below) and the larger ones (eg. the Mega) use STK500 Version 2. That is because they have a larger address space. So yes, it needs to know the protocol.

When I switched my board type to Mega2560 the "-c" option changed to:

-cwiring

I am guessing from that, the "arduino" is code for "STK500" and "wiring" is code for "STK500 V2".

Protocols

AVR061: STK500 Communication Protocol
AVR068: STK500 Communication Protocol version 2


Why these specific voltage divider resisters needed for Arduino Uno RX TX pins? I have an Arduino Uno attached to a Parallax Boe-Bot shield, and plugged into the shield breadboard, the Parallax WX ESP8266 Wi-Fi SIP.

When I attach the DO/DI pins of the ESP8266 board to the RX/TX pins of the Uno, it does not work without a very narrow range of resisters in a voltage divider configuration. I'm trying to learn more about electronics and I would like to know, why these specific values in this specific case?

The DI/DO pins of the SIP are documented as "SIP - output high (set by Vin voltage, either 3.3 or 5.0 V), low 0 V. Input high >Vin/2, input low

When I attach the Parallax shield 5V to the SIP Vin, and the DO to a 220 resister to RX, and also DO to a 1K resister to ground, and DI to 220 to TX and also DI to 1K to ground, serial communications works fine.

If I use the shield 3.3V to SIP Vin, it does not work.

If instead of 220 / 1K, I use 470 / 2K, or 4.7K / 10K, for example, it doesn't work.

If I only set up the voltage divider on the RX pin, it doesn't work.

However, if instead, with either 5V or 3.3V to the SIP Vin, and no resisters, I can run the Uno TX direct to the SIP DI, and the SIP DO to a digital pin, and run that digital pin with SoftwareSerial, for example.

I can run both DI and DO directly with SoftwareSerial, and either 5V or 3.3V to supply Vin.

It's only when I want to connect DO/DI direct to use the Uno's UART (because I don't want serial-driving interrupts to interfere with servo pulses) that I have to carefully select these resisters (through trial and error) and be sure to power with the 5V. Some combinations get communication with errors, but just these specific values (out of the resisters I happen to have on hand) work.

I understand that it is something to do with 3.3V vs TTL serial, but I would like the details. (I will be picking up a logic level converter to try in place of the voltage divider.)

EDIT:

By "not working" -- in all but two cases, with fresh batteries, the SIP seems to get data from the Uno TX, and the DO lamp on the SIP flashes, but Serial.read() sees nothing on the Uno regardless of configured rates. In one of the two cases (I can't recall which) unintelligible, incomplete data is read on the RX pin, and in the last, good case -- where both pins have voltage dividers and the SIP is powered by the 5V line of the Arduino shield (for the Boe-bot) -- with those specific resister values -- the data from the SIP DO is received on the Serial, from pin RX.

The output of a voltage divider is:

Vout = Vin * R2 / (R1 + R2)

Where R2 is the resistor in your case which is connected to ground.

See: Sparkfun - voltage dividers

Now in your example of 220 / 1k you have a multiplier of:

Vout = Vin * 1000 /1220 = Vin * 0.82

If both boards are running at 5V you don't need the voltage divider at all, but if you do use it the output would be:

Vout = 5 * 0.82 = 4.1

Now the Atmega328P chip on the Uno has the electrical characteristics defined in the datasheet, amongst others is that a digital pin high has to have a minimum of 0.6 * Vcc (if Vcc is in the range 2.4V to 5.5V)

So if Vcc is 5V (which it is on the Uno) you have to have 0.6 * 5 (that is, 3V) as the minimum for it to be recognised as high.

So, using the voltage divider of 220/1k you have a high still being 4.1V which is in the range 3 to 5V.

However if you have the board set to 3.3V then the output of the voltage divider will be 3.3 * 0.82 = 2.76V which is too low to be recognized as high.

For sending serial from a 3.3V board to a 5V board, simply omit the voltage divider, and then the 3.3V (for high) is in range (it has to be 3+ volts).

However for sending from a 5V board to a 3.3V board you do need a voltage divider (or level shifter) because 5V is too much for a 3.3V board. You can use a voltage divider calculator to simplify the maths.

Something like 1k/1.8k would be about right.

Vout = 5 * 1800 / 2800 = 3.21

According to the documentation for the Parallax WX ESP8266 Wi-Fi Module:

  (9) Level shifters and buffers

  To ensure maximum compatibility with a wide range of 3.3V and 5V microcontrollers and development boards, the Parallax Wi-Fi module includes voltage level shifters and buffers to ensure that the logic voltage levels at the SIP header are set by the VIN voltage level. If you
  supply 3.3V to VIN, then the IO pins logic voltage level will be 3.3V. If you supply 5V to VIN, then the IO pins logic voltage level will be 5V

I don't see why you need to use a voltage divider or level shifter in the first place.

References

Atmega328P datasheet (32.9 MB)
Sparkfun - voltage dividers
Voltage divider calculator
Another voltage divider calculator
Voltage dividers - Wikipedia


DS3231 AT24C32 IIC making digital outputs not work I have just taken the code from

https://learn.adafruit.com/adafruit-ds3231-precision-rtc-breakout/wiring-and-test

to get DS3231 AT24C32 IIC to work fine with my Aduino and its working fine.

I have then taken
https://learn.adafruit.com/adafruit-arduino-lesson-4-eight-leds
and expanded it to work with three 74HC595 Shift Register. And this is working fine with all three sets of LEDS lighting up one after an other like in the demo.

So I do not think there is anything wrong with my wiring.

When I merge the two demos together, all the output pins on my this shirt register just give out positive current constantly.

I have walked through each line of the code and the problem is caused by

if (! rtc.begin()) {

if I take out that if statement everything works.  But since that is the bit that starts the clock I want that.

So how do I get the DS3231 started and not have all the pins on the third shift register high?

Also if it matter it is an official Leonardo board.

#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;

int latchPinOne = 5;
int clockPinOne = 6;
int dataPinOne = 4;

int latchPinTwo = 11;
int clockPinTwo = 10;
int dataPinTwo = 8;

int latchPinThree = 3;
int clockPinThree = 13;
int dataPinThree = 2;

byte leds = 0;

void setup()
{
#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  pinMode(dataPinOne, OUTPUT);
  pinMode(latchPinOne, OUTPUT);
  pinMode(clockPinOne, OUTPUT);

  pinMode(dataPinTwo, OUTPUT);
  pinMode(latchPinTwo, OUTPUT);
  pinMode(clockPinTwo, OUTPUT);

  pinMode(dataPinThree, OUTPUT);
  pinMode(latchPinThree, OUTPUT);
  pinMode(clockPinThree, OUTPUT);

  Serial.begin(9600);
  Serial.println("Start");

  delay(3000); // wait for console opening
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }
}

void loop()
{
  leds = 0;
  for (int i = 0; i < 8; i++)
  {
    bitSet(leds, i);
    updateShiftRegister();
    delay(500);
  }
}

void updateShiftRegister()
{

  digitalWrite(latchPinOne, LOW);
  shiftOut(dataPinOne, clockPinOne, LSBFIRST, leds); // send the data
  digitalWrite(latchPinOne, HIGH);

  digitalWrite(latchPinTwo, LOW);
  shiftOut(dataPinTwo, clockPinTwo, LSBFIRST, leds); // send the data
  digitalWrite(latchPinTwo, HIGH);

  digitalWrite(latchPinThree, LOW);
  shiftOut(dataPinThree, clockPinThree, LSBFIRST, leds); // send the data
  digitalWrite(latchPinThree, HIGH);
}

This looks like a classical case of pin conflicts when merging several sketches.

In this case it is hidden by the fact that TWI SDA and SCL are separate pins on the Arduino Leonardo. But they are also connected to pins 2 and 3 (not A4 and A5 as on Arduino Uno).

Selecting other pins (latch/data) for the third shift register should help.

Cheers.


>>  Syntax in arduino I was trying to follow this tutorial and came across >>. What exactly does this do?

>> is right shift a value by a certain number of bits.
<< is left shift a value by a certain number of bits.
-> is accessing a member of a class or struct that is referenced by a pointer.
Right Shift and Left Shift
If you have a binary number 0b00010000 and right shift it two bits you get 0b00000100. The C notation for that is val >> 2.  The same for left shift - val << 2 would result in 0b01000000.
Pointers and members
Normally when you access a member of a class or struct you use ., such as Serial.println().  However it is possible to make a pointer to a class instance, and when you do you need to access the members with -> instead of . - such as mySerial->println().
This arrow notation serves as syntactic sugar: mySerial->println() is interpreted as (*mySerial).println(). The parentheses are necessary because the dereferencing operator * has a lower order of precedence compared to the dot . operator.


How I can use multi sensor in one code in Arduino? How I can use multi smoke sensor in one code? I mean how can I use more than one sensor, where both sensors has the same purpose, like use smoke sensor in multi room. Similar to this code where one is used only. How I can more than one, in Arduino Uno R3,,

<per>
    int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// Your threshold value
int sensorThres = 400;

void setup() {
  pinMode(redLed, OUTPUT);
 pinMode(greenLed, OUTPUT);
pinMode(buzzer, OUTPUT);
pinMode(smokeA0, INPUT);
Serial.begin(9600);
}

void loop() {
  int analogSensor = analogRead(smokeA0);

  Serial.print("Pin A0: ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);
}

How I can add more than one sensor to get same purpose. check detect 1 and detect2 and detect 3 if one of this detection LED Red ON, Thanks`

just duplicate the parts of the code that handle the sensor.

int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeSensor1 = A5;
int smokeSensor2 = A4;
int smokeSensor3 = A3;
// Your threshold value
int sensorThres = 400;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeSensor1, INPUT);
  pinMode(smokeSensor2, INPUT);
  pinMode(smokeSensor3, INPUT);
  Serial.begin(9600);
}

void loop() {
  int analogSensor1 = analogRead(smokeSensor1);
  int analogSensor2 = analogRead(smokeSensor2);
  int analogSensor3 = analogRead(smokeSensor3);

  Serial.print("Pin A0: ");
  Serial.println(analogSensor1);
  // Checks if it has reached the threshold value
  if( (analogSensor1 > sensorThres) || (analogSensor2 > sensorThres) || (analogSensor3 > sensorThres) )
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);
}


Variable declaration inside main loop In the past I declared variables inside the main loop which worked just fine.
In a new project I did the same:

void loop(void)
{
    uint8_t counter;
    ....
    if (buttonPress)
        counter = 0;
    ...
    if (someCondition == true)
    {
        Serial.println(counter);
        counter++
    }
}

But then the output of the variable counter shows that for some reason the counter variable is reset to 0 instead of counting up. This happens even after the button is released.

The scope of the variable counter is the main loop and I just assumed that it will keep its value and count up.

What might be the reason for this variable to reset to 0?
Is it that other functions are called within the main loop?
Is it that an interrupt handler is called every now and then?

The solution I've found is to declare the variable as static:

static uint8_t counter;

Then it increments as expected.

Even though I've found a solution I'd really like to understand what the problem with my first approach was.

Michael's answer was good, as usual. Let me give you some more background though:

In C/C++ (And in most modern languages) variables have a "scope", or an area where they are defined.

Global scope:

Variables declared at the top level of your program have global scope, and exist for the life of your program. These variables are usually created on the .data or .bss sections.

Local scope

Variables declared inside a function have local scope. Unless they are static, they get created when the function is entered, and get discarded when the function exits. These variables are created on the stack as part of the function's stack frame.

Object scope

In C++ and other object-oriented languages, instances of objects have their own scope, "instance variables". Every instance of an object has its own set of instance variables. (Think of cars, and a car radio. You and I might own the exact same model of car, but if I set my car's radio station and you set your car's radio to a different station, each instance of the car has a different setting for the radio station.)

Static variables:

Static variables are variables that are declared "statically." That means that they are only created once and persist, even if they are declared inside a scope like a function or a class instance. These have the lifespan of a global variable but can be declared inside a function or in an object.

Loop is a function, so variables declared inside of loop() are local variables. They get created anew every time the function is called, and discarded every time the function exits.


How to compile a sketch using arduino-builder? How do you compile a sketch with a custom library path using arduino-builder? The docs are a little light.

I have my source code organized like this:

lib
    SomeLib
        somelib.h
        somelib.cpp
src
    otherfile.h
    main.ino

I've installed Arduino 1.8.1 into /usr/share/arduino.

I'm trying to compile this for an Arduino Uno from my project root directory with:

arduino-builder -compile -hardware /usr/share/arduino/hardware -tools /usr/share/arduino/hardware/tools -libraries lib -fqbn arduino:avr:uno -build-path .build src/main.ino

But it returns this error:

fork/exec {runtime.tools.ctags.path}/ctags: no such file or directory

What's causing this error?

You need to specify the path to the tools-builder folder, which is where ctags is. Try this:

arduino-builder \
  -compile \
  -hardware /usr/share/arduino/hardware \
  -tools /usr/share/arduino/hardware/tools \
  -tools /usr/share/arduino/tools-builder \
  -libraries lib \
  -fqbn arduino:avr:uno \
  -build-path .build \
  src/main.ino


What is the purpose of Serial.println() without an argument? I am attempting to control a stepper motor with Sparkfun's Big Easy Driver, and I see the line "Serial.println();" they put in the example code. Why is there no argument and what function does this serve?

//Declare pin functions on Arduino
#define stp 2
#define dir 3
#define MS1 4
#define MS2 5
#define MS3 6
#define EN  7

//Declare variables for functions
char user_input;
int x;
int y;
int state;

void setup() {
  pinMode(stp, OUTPUT);
  pinMode(dir, OUTPUT);
  pinMode(MS1, OUTPUT);
  pinMode(MS2, OUTPUT);
  pinMode(MS3, OUTPUT);
  pinMode(EN, OUTPUT);
  resetBEDPins(); //Set step, direction, microstep and enable pins to default states
  Serial.begin(9600); //Open Serial connection for debugging
  Serial.println("Begin motor control");
  Serial.println();
  //Print function list for user selection
  Serial.println("Enter number for control option:");
  Serial.println("1. Turn at default microstep mode.");
  Serial.println("2. Reverse direction at default microstep mode.");
  Serial.println("3. Turn at 1/16th microstep mode.");
  Serial.println("4. Step forward and reverse directions.");
  Serial.println();
}

To complement jose can u c's answer: the Arduino Serial object uses
CRLF as the end-of-line marker. That's an ASCII CR (carriage return,
or '\r' in C) followed by ASCII LF (line feed, '\n' in C). Thus,

Serial.println();

is equivalent to

Serial.print("\r\n");


Reading a 10 pin 7 segment (2 digits) sing Arduino 1. Please Help! thanks for taking the time to read this, I really appreciate it.
I am very new to Arduino and the Micro controller world so please forgive my ignorance.

So I have an old 7 segment display that displays outside temperature, what i want to do is read the temp into the Arduino and light up an LED if the temperature gets high, and a different color if the temp gets low.

I know i can use a thermometer and plug it into the Arduino and go from there, but that would be cheating. So my question is, can i read each pin of the 7 segment display and translate that into a number into the Arduino?

Task: Read a dual  10 pin 7 segment by jumping wires into the Arduino.
Setup: I am using the code and setup found here: "http://blog.rastating.com/using-a-7-segment-led-display-w-arduino-uno/" to display a number (21) for testing purposes. I want to jump the pins into another Arduino and read "21"

please see pictures.

Any help would be very very appreciated!!

Thanks again for reading.

This last picture shows "21" using the code and set up on the above link.
I want to jump another Arduino into the breadboard and read "21" or any other temperature (depends on outside thermometer) into the serial monitor. Now the challenging part is the code, Im not really good at coding but i understand if this had 1 pin for each LED i would just read each one and translate it into the serial monitor. However this only has 10 pins therefore represents a challenge.

Any input is greatly appreciated, I dont even know how to start.

Your display is multiplexed, so you will need to monitor not only the segment lines but also the digit lines.

First figure out if your display is "common anode" or "common cathode" as the logic in one case will be inverted from that of the other.

For your test case, you can write the driving and reading arduinos to the display in the same way, but configure all the connected pins on the reading one as inputs.

The tricky part is going to be detecting when the segment select has changed, but you could do it by storing the current value of each select pin, and then reading the new value.  If you see that the old value was inactive and the new value active, then wait a tiny amount of time and read all of the segment lines.  You want to wait long enough to make sure that the data lines have been driven to match, but no so long that you get the data for the next digit instead.  If you have access to a scope, you can find the best value, but you could also experiment by making the delay short until you get wrong data, making it long until you get wrong data, and then picking an intermediate value.

You may find it easiest to read all 7 or 8 segment lines into a single byte value, and then compare it to each element in the lookup table you used in the driver code until you find a match.

If you don't know the exact wiring of the segments on the unknown target board, consider printing the bytes to the serial monitor as you cause the displayed values to change (cup of ice water, cup of hot water...) and taking notes of the segment values vs. the digits you see display.  It will be a puzzle, but one you should be able to figure out.