ESP8266 Arduino 2.2inch ILI9341 TFT library I recently got one TFT LCD from aliexpress which supports SPI and uses ILI9341.
This is the one.TFT LCD
I have the ESP8266 EspressoLite 1 board, and I am using ESP8266 Arduino.
(https://github.com/esp8266/Arduino)
I made the following connection :
SCK #14, MOSI #13, MISO #12 and CS #4, DC #5,RESET #0
and used the example graphicTest (which is available in the Adafruit_ILI9341-master folder) . I was able to make the display work for a few seconds.
In the graphic test, once the line test starts my ESP8266 gets restarted. This was getting repeated .
In my existing project, I used the following code to just show some messages :
Adafruit_ILI9341 tft = Adafruit_ILI9341(4, 5, 13, 14, 0, 12);
  tft.begin()
  tft.fillScreen(ILI9341_BLACK);
  tft.setCursor(0, 0);
  tft.setTextColor(ILI9341_GREEN);  tft.setTextSize(4);
  tft.println(message);

The message is shown once a response is sent back from ESP. This works for a couple of times and then it again gets stuck and reboots.
I am not sure whether I am using the optimised library for ESP8266 for this LCD or whether there is any as such.
I read in forums and could see that there were some adafruit libraries in the ESP8266 Arduino but now that it is not available and only some TFT_Touch_Shield_V2 are present.
Has anyone faced the same issue or can tell me a better way to make this display work with ESP8266 Arduino.
Thanks in advance. !!!

You did not include any output from the esp8266, but I'm pretty sure what is happening is that the watchdog timer is expiring and resetting your board. This is because the SPI transactions to transfer data to the display are taking too long.

Put the following line in both setup() and loop() before any display operations happen:

wdt_disable();

Needless to say, if you actually do need the WDT in your application, you can reenable it after the display operations complete (of course, if you are doing something that depends on the wdt, you already know this!)

Look at the source for the Adafruit library, make sure there are #ifdef ESP8266 statements there; older versions did not support the 8266.
You may also want to increase the default speed at which the library drives the SPI bus from 8000000. I've gotten it to work at up to 40MHz, with the board flashed at 160MHz of course, and it's a lot faster (unsurprisingly), but if you have long wires or a marginal-quality display, that may fail.

Post pictures :)


DHT11 not working with LED in arduino the point of my code is to turn on a LED when the humidity level reaches a certain amount. However it reads the amount of humidity but the LED is not turning on. Why isn't it working??
#include <SimpleDHT.h>

// for DHT11,
//      VCC: 5V or 3V
//      GND: GND
//      DATA: 2
int pinDHT11 = 2;
SimpleDHT11 dht11;

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

void loop() {
  // start working...
  Serial.println("=================================");
  Serial.println("Sample DHT11...");

  // read without samples.
  byte temperature = 0;
  byte humidity = 0;
  int err = SimpleDHTErrSuccess;

  if (humidity > 70 ) {
     digitalWrite(9, HIGH);
  }
  else if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
    Serial.print("Read DHT11 failed, err="); Serial.println(err);delay(1000);
    return;
  }

  Serial.print("Sample OK: ");
  Serial.print((int)temperature); Serial.print(" *C, ");
  Serial.print((int)humidity); Serial.println(" H");

  // DHT11 sampling rate is 1HZ.
  delay(1500);
}

Your code does not work because in fact error statement reads the value of temperature and humidity sensor.
You set the humidity and temperature variables to 0. If statement compares this variables to 70, before actually reading sensor data.
I haven't tested but this should work.
#include <SimpleDHT.h>

int pinDHT11 = 2;
SimpleDHT11 dht11;

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

void loop()
{
    // start working...
    Serial.println("=================================");
    Serial.println("Sample DHT11...");

    // read without samples.
    byte temperature = 0;
    byte humidity = 0;

    int err = SimpleDHTErrSuccess;
    if ((err = dht11.read(pinDHT11, &temperature, &humidity, NULL))
        != SimpleDHTErrSuccess)
    {
        Serial.print("Read DHT11 failed, err=");
        Serial.println(err);
        delay(1000);
        return;
    }

    Serial.print("Sample OK: ");
    Serial.print((int)temperature);
    Serial.print(" *C, ");
    Serial.print((int)humidity);
    Serial.println(" H");

    if (humidity > 70 )
    {
        Serial.println("Humidity is above 70%");
        digitalWrite(9, HIGH);
    }
    else
    {
        Serial.println("Humidity is below 70%");
    }
    // DHT11 sampling rate is 1HZ.
    delay(1500);
}


Problem with uploading LUFA MassStorage .hex file to Leonardo I have been trying to make my Leonardo board to work as a USB device. So I started with compiling the open source LUFA USB library demo "MassStorage" for the Leonardo board settings. Since I'm using Mac OS, I downloaded the "AVR Tools" software to upload the hex file to the board(I didn't want to use the ISP protocol to flash. Because it is not possible to remove the chip from the board to make the correct ISP circuit connection). Anyway I was managed to flash the board. But afterwards it is not detectable by the computer. The serial port is not detectable. This proves it flashed something. Afterwards I flashed it again with the original bootloader file and it was identified as before. I'm a beginner to Arduino programming and forgive me if I'm asking elementary question. What am I doing wrong?

Cannot say for sure, but if you was able to flash something, then loose functionality, but was still able to flash it back, then there is possibility, that you flashed the application part (with would-be-bootloder code), not the bootloader part (and the old bootloder in bootloader part then enabled you to flash back something sensibe).

bootloader is resposible for saving application in memory in process of flashing and running the application after that, or in case you just connect the board and do not start flashing it just after (maybe software/transmit) reset.

if you save bootloader to application part of memory, it is highly possible, that it would not do anything good, as the original bootloader would still run first and setup your board and the application (with new bootloader code) would try something futile (and maybe have bad addresses already, as it is suppose to be runned in bootloader place, not in application).

There are two parts of flash memory in arduino - one for application, other for bootloader and they have different use, even if they are just different parts of one big flash area. So make sure, what you actually updated and how was the hex compiled (for which address)


Possible to create IP-to-USB HID (keyboard) device using Arduino? Is it possible to create an IP-to-USB HID (keyboard) using Arduino?

I'd like to connect an Arduino to my network using Ethernet, and then send it commands using TCP/IP and have those commands translated to USB HID and sent as keystrokes to the connected PC.

I've found a few articles discussing USB HID emulation using the Arduino Uno (see http://mitchtech.net/arduino-usb-hid-keyboard) but it refers to using GPIO pins as buttons.

Am I correct that this might work if I use an Arduino Uno and then purchase an Arduino Shield Ethernet?  (seems a bit expensive, but is this the cheapest option?)

Thanks in advance!

Yes, it is perfectly possible.

You ideally need an Arduino with a direct USB interface, such as the Leonardo. Then you can just access the Keyboard object to send the keystrokes to the PC.  How your receive the data through Ethernet is entirely up to you. A simple TCP interface may be easiest - open the connection with whatever telnet-like client and whatever you type gets sent through.  The trick will be getting it into character-at-a-time mode.


How to get ip information of arouter/AP with ESP8266 i, I would like to get ip number, DHCP ip range subnet mask information of an external AP/router autonomusly through the ESP8266 sketch, so the ESP8266 code can determine a suitable static ip range to configure. Any example code or references would be appreciated.

All you can do is get what DHCP gives you.

Connect to the AP
Use DHCP to get an IP address
Store the IP, netmask and gateway in variables
Use the netmask to determine the "fixed" bits in the IP address.
Replace the "unfixed" bits of the IP with your own chosen IP portion
Re-set the IP information with your static information.

What you cannot do is determine what the DHCP range is. Only the router knows that, and it doesn't broadcast it.

The proper way of handling it, though, is to get the router to provide a fixed DHCP IP address for the MAC address the ESP8266 has. Most routers have this functionality available.


Pro Mini Fuse Repair It looks like I broke my Arduino (Compatible) Pro Mini board using AtmelStudio to change the fuses. I was having trouble with speed and using some basic sketches. For example, the LED blink was on for 2 seconds and off for 2 seconds instead of 1 second. I tried to change the fuses to Ext Clock + 65 ms, and now I can't use the thing at all. Cannot enter programming mode. Any ideas?

Sounds like you broke your fuses.

You may be able to enter programming mode by applying an external clock signal to the clock in pin (use another Arduino to generate it).  If that doesn't work then the only way to fix it is with a "High Voltage Programmer".

Nick Gammon has a very good tutorial here: http://www.gammon.com.au/forum/?id=12898


3.3v Arduino I2C communication with motor controller powered at ~6v I am trying to just use the voltage from 4 Alkaline AA batteries in series (6v nominal) to power a motor with the TI drv8830 IC.

My question is, will this circuit (specifically just pulling the sda and scl pins to 3.3v) work reliably?   The datasheet says at maximum of 6.8v vcc the chip will still recognize 3.3v i2c lines (minimum 3.13V at that vcc voltage) but will the varying voltage of the battery cause the communication to be unstable?   There is a 10uf capacitor between vbat and gnd (not shown).

will the varying voltage of the battery cause the communication to be unstable?

No. As the battery voltage drops the input HIGH threshold (which is a function of VCC) also drops. If anything as the battery voltage drops the communication becomes more stable.

Since I2C is an open drain protocol the voltage makes no different for sending data - that voltage is set by the pull-up resistors to 3.3V.


Pressure Gauge analog reading via RS232 I am trying to read the analog signal from a Pfeiffer TPG 261 Single Gauge (https://www.idealvac.com/files/brochures/Pfeiffer_Single_Gauge_TPG261.pdf)

The pin assignment of the connector I am using is the following:

Here is the circuit I have built:

And here is the code used:

int pressureSensorPin = A0;

int analogValueP = 0;

void setup(void)
{
  Serial.begin(9600);
}
void loop()
{
  analogValueP = analogRead(pressureSensorPin);
  Serial.println(analogValueP);
  delay(1000);
}

Unfortunately the ouput I get with such a build is only 0 with now and then a 1023.

Any idea of what I am doing wrong ?

You have a misconception, which signals get's outputted where. If you want to simply read the analog signal of the sensor, you need to use the "control" connector. There you can find the analog signal on pin 2. But this analog signal goes up to 10V, so you need a voltage divider between the sensor and the Arduino, to divide the voltage down to 5V max.

Currently you are using the RS232 connector. RS232 is a communication standard, which transmits digital data, not analog data. Thus you read only digital values (min voltage and max voltage, nothing inbetween). You can use it do talk with the sensor, change configuration settings and reading data digitally. But to actually do this, you need to consider 2 important things:

RS232 is an interface, which involves it's own voltage levels (namely +-12V), which do not fit the TTL level (0 - 5V) that the Arduino Uno uses. You can very well destroy your Arduino by connecting it directly to RS232. For making this work, you need a level converter chip (I think the MAX232 is commonly used for this), to convert the voltage levels to TTL logic. From there on this communication is normally called UART.
You need to understand and then implement the sensors communication protocol (when to send what data), so that the sensor and Arduino are understanding each other

For me it seems, that the analog signal from the "control" connector is all, that you currently need, so for simplicity you can use this. RS232 is used for more control over the functionality of the sensor.


Reading DHT22 reboots arduino I’ve got a quite weird behavior of DHT library.

I’ve got DHT22 sensor. If it’s signal cable is not connected, reading the sensor causes a problem: Arduino reboots or hangs in unpredictable places.

If I connect the signal cable again, the problem vanishes.

Is this normal behavior or some sort of bug? I think unsuccessful reading affects some part of Memory.

PS. The project is quite big and I can’t share the code here.

It happens that I found an evidence that dht object influences foreign memory. Look at this code:

DV("pClock->isInited 3", pClock->isInited); // prints 1
dht1.readHumidity();
DV("pClock->isInited 4", pClock->isInited); // print 0 !!!!
// nothing more can be called between these lines.

// DV is a macro which prints label and value.
// Both objects created before this.

DHT dht1(11, DHT22);
…
dht1.begin();
…
pClock = new ZhClock(); // uses RTC_DS1307
pClock->init(&rtc); // rtc is RTC_DS1307

This problem is usual if you are in shortage of RAM.
Adafruit's libraries wastes lots of memory. You should be very careful to run their stuff if you are in shortage of memory.

I suggest you to try another library which quite old, but uses much lesser memory to read DHT sensor’s data:
https://github.com/markruys/arduino-DHT


Need help in the project "Arduino for audio processing" I am following this link from Instructables site:

http://www.instructables.com/id/Arduino-Audio-Input/

My question is:

Instead of using the Microphone Radioshack 33-3038, which is listed in the tutorial, can I use https://www.sparkfun.com/products/9964?

Kindly suggest if there any modifications required in other parts for the circuitry, if I go for Electret Microphone.

The replacement microphone you link to contains all the circuitry in that instructable*.  You can do away with the op-amp and all the associated stuff, and just connect it direct to the analog input of the Arduino.

*Actually it's better circuitry since they do it right, unlike the Destructable that is a rubbish circuit.


ESP8266MOD programing using Arduino uno? I want to make a very simple webserver who sends welcome message to anyone who joins it using WiFi.

I have a ESP8266MOD module, I want to program it using arduino ide and arduino uno board.
How I can use arduino uno to program this WiFi module without using urat USB serial board?

SoftwareSerial.h is not working with esp.write() command, I believe it is because of low power, can anyone suggest me on power supply too?

Thanks in advance,

Mohan

When you use the Uno for its UART only, i.e. grounding RST pin, its Rx pin 0 becomes Tx, and Tx pin 1 becomes Rx -- because that's what pins on the UART you are connecting to. AppMonk didn't say what specific breakout/ chip mount he's using, there are many, or say how he's managing level-shifting from the Uno to the ESP if needed. The Tx pin on Uno (0, labeled Rx) is putting out 5v and the ESP would prefer 3.3, so level shifting w/ simple voltage divider is recommended. You don't need to level shift the Tx signal from ESP to Arduino's Rx (pin 1).


Explanation for micros function I was trying to understand the working of micros() function internally and I had a look at the function in Arduino.h

This is the code:

unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;

    cli();
    m = timer0_overflow_count;
 #if defined(TCNT0)
    t = TCNT0;
 #elif defined(TCNT0L)
    t = TCNT0L;
#else
    #error TIMER 0 not defined
#endif

#ifdef TIFR0
        if ((TIFR0 & _BV(TOV0)) && (t & 255))
        m++;
#else
        if ((TIFR & _BV(TOV0)) && (t & 255))
        m++;
#endif

    SREG = oldSREG;

    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

Can someone please explain me what this line is doing :

  if ((TIFR0 & _BV(TOV0)) && (t & 255))
   m++;

If the timer 0 has overflowed (TIFR0 & _BV(TOV0)) and there is at least a count of 1 in the timer count register (t & 255) then increment the local copy of the overflow count.

That overflow count is used later on to add an upper 8 bits to what is basically an 8 bit counter to turn it into a 16 bit one ((m << 8) + t).


Scrolling an I2C text I want tried to make a programm to display a text on an I2C LCD-Display.
The text should be scrolled for one position every time the function is called.

On the internet I saw a lot of solutions but there were all diffrent from what I need.

So I tried to make my own code.
The code works well except of the part where I try to scroll in the Text from the left.

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 16, 2);

char Str[12] = {'T', 'r', 'u', 'e', 't', 'z', 's', 'c', 'h', 'l', 'e', 'r'};
int pos = 0;
int posretry = 0;
bool ledon = false;

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

  lcd.init();
  lcd.backlight(); //lcd.noBacklight();
}

void scroll()
{
  for (int i = 0; i < 12; i++)
  {
    //Print text
    lcd.setCursor(i + pos, 0);
    lcd.print(Str[i]);

    //Move in text from the left

    if (pos >= 6)
    {
      lcd.setCursor(i + pos, 0);
      lcd.print(Str[i]);

      lcd.setCursor(posretry, 0);
      lcd.print(Str[11 - posretry]);

      posretry++;
    }
  }
  delay(500);
  lcd.clear();

  pos++;
}

void changeled()
{
  if (ledon == false)
  {
    digitalWrite(13, LOW);
  }
  else
  {
    digitalWrite(13, HIGH);
  }

  ledon = !ledon;
}

void loop()
{
  scroll();
  changeled();  //Example Event
}

The goal is to move the text to the right and show the not displayed letters on the left.

Example:

|er    Truetzschl|  -->
|                |

A Video about the error can be found here:
https://data.jonas-heinze.de/shares/stackexchange/lcd/

Thanks for your help.

You do some strange things that I, at least, don't understand (e.g. I don't see what you need posretry for), but you might have a reason for doing so.
But you don't reset posretry and pos, which means they will very soon be out of a reasonable range. At some point the int will actually overflow to negative values, which is definitely not going to work!

To make it less complicate, you should write a function that prints the char array shifted by a desired value as a beginning.

The below code is completely untested as I don't have your hardware and I'm aware that it does not include all your desired features. But it should give you an idea of how scrolling can be implemented in principle and it's up to you to improve/fix it.

#define LCD_SIZE 16
#define STR_LEN 12
char str_to_print[STR_LEN]={'T', 'r', 'u', 'e', 't', 'z', 's', 'c', 'h', 'l', 'e', 'r'};

void print_scrolled (uint8_t scrolled_by) {
  for (uint8_t i=0;i<LCD_SIZE;i++) {
    lcd.set_cursor(i,0);
    if (scrolled_by>=LCD_SIZE) scrolled_by=0;

    if (scrolled_by<STR_SIZE) lcd.print(str_to_print[scrolled_by]);
    else lcd.print(' ');
    scrolled_by++;
  }
}

You could call it like this:

for (uint8_t i=0;i<STR_LEN;i++) {
  print_scrolled(i);
  delay(500);
}

Once you are familiar with my approach you should be able to enhance it with additional features (end of text coming in from the other side, spaces between end and beginning, etc).


Board and library updates required caused an error I compiled my code several times today,
I would quit and restart randomly through the day.
each time I started I get a error box board and libraries need updates.
I did an AVR board up date, then compiled and now I get this every time.....

avrdude: no programmer has been specified on the command line or the config file
         Specify a programmer using the -c option and try again

Yes I have tried rebooting my Windows 7 64 bit AMD machine.

this is on IDE "Arduino 1.6.8"

Of course I made the mistake of not backing up my IDE folders in the belief that an update would not screw my IDE up.

Nothing will upload, not even any of the examples.
I turned on Show Verbose output during Compilation, and upload
I pasted the full output and it was 4500 char to many for this so I turned of the compilation check and left just the upload check on show verbose errors

I loaded in the example blink,

the file followed by the IDE lower window text.

/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.

  Most Arduinos have an on-board LED you can control. On the Uno and
  Leonardo, it is attached to digital pin 13. If you're unsure what
  pin the on-board LED is connected to on your Arduino model, check
  the documentation at http://www.arduino.cc

  This example code is in the public domain.

  modified 8 May 2014
  by Scott Fitzgerald
 */

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}

END OF FILE
Copy and paste of the lower IDE window  last lines the same as above

Sketch uses 928 bytes (2%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
C:\Users\Lee\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino2/bin/avrdude -CC:\Users\Lee\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino2/etc/avrdude.conf -v true -patmega328p -carduino -PCOM10 -b115200 -D -Uflash:w:C:\Users\Lee\AppData\Local\Temp\build9c9ef3bdfe2fccb480bc6e4bac749e41.tmp/Blink.ino.hex:i

avrdude: Version 6.3, compiled on Jun 22 2016 at 16:05:21
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

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

avrdude: no programmer has been specified on the command line or the config file
         Specify a programmer using the -c option and try again

There is that line again   What do I do to fix this?
besides deleting everything and starting all over again?

I do not want to delete and start over

This sounds very much like the problem I had when I updated my ARV version,I was also getting "no programmer has been specified error", I run Windows 7 32bit, the way i got out of it was to go back to the update screen when it pops up and in Arduino ARV Boards area....select versions....I went back to version 1.6.10...now it all works again.....at this point I am no longer updating my ARV, but I will after a few more version updates come out, there is obviously something that conflicts at this stage, if you google the problem you will find other of ways to fix this.


"Return" Code Not Working I'm trying to experiment with a "return" function. Yet each time I try to run my program, there happens to be an error, like "expected declaration before '}' token."

Can someone explain the basics of a return function, and look at my code below to possibly see what the problem could be?

{
int index;

pinMode(10, INPUT); //button input

int checkInput();

if (digitalRead(10) == 0) {

return 1;
else{

return 0;
 }
}

It has nothing to do with the retun statements. You have to close each { with a }. you are missing one.

   {
int index;

pinMode(10, INPUT); //button input

int checkInput();

if (digitalRead(10) == 0) {

return 1;}
else{

return 0;
 }
}


Possibility to program the ATmega32u4 on the Arduino Yun using a configuration file Is it possible to send a Configuration File viz. conf.json that can be sent to the Arduino Yun via Ethernet and a Python Program can parse the configuration and set for example Sampling Rate of a Sensor which is connected to the 32u4?

The problem for me is that Sampling Rate in the Arduino Sketch is actually a preprocessor directive and I understand that C++/Arduino Sketches need to be compiled once before the changes take place.

However, how can I change the preprocessor directive in the sketch using a configuration file?

e.g.

#define SAMPLE_RATE (100)

in a conf.json file somewhere there might be:

{"sample_rate": 1000}

Once the .json file is parsed using python is it possible to change

#define SAMPLE_RATE (100) // to #define SAMPLE_RATE (1000)

You can't. You'll have to change your macro into a variable and change that variable when suitable data is received through the serial port.

You may also have to trigger a reconfiguration of whatever software is doing the sampling, or reconfigure the hardware, depending on what it is you are sampling.


Turning an LED on when an error occurs, then turn it off after 2 seconds I am currently working on making some test equipment for µUSB cables. The code is supposed to recoqnise when an error in the cable occurs. Most of it works as expected, but I have some trouble understanding the use of millis() timers.
I, therefore want to ask, in the code below, how can I make my program pick up on an missing connection in the cable and make sure it turns on the LED always? And secondly, how can I make it stay on for 2 seconds, even if the cable has "fixed" itself again (i.e. the connection has returned)?

Update
It seems that I have misunderstood the assignment. The program should turn on a LED, when an error is present and keeps this on while the error is present (already fixed this in the code). When the connection has been regained a timer should start, which turns off the LED after two seconds. (Here's the trouble I'm having, I can't seem to pinpoint where and how this timer should start)

case microUSB:
  if (Vcc_Ext_val > 50)
  {
    digitalWrite(ActivateLoad, HIGH);
    LoadActivated = true;

  }
  else if (Vcc_Ext_val < 30)
  {
    digitalWrite(ActivateLoad, LOW);
    LoadActivated = false;
  }
  if ((Vcc_Ext_val < 50) || (USB_DP_VAL < 10)|| (USB_DM_VAL < 10))
  {
    PulseCurrentMillis = millis();
    if (FirstPulse == true)
    {
    digitalWrite(RedIntLED, StateLEDON);
    FirstPulse = false;
    }
    if (PulseCurrentMillis - PulseLastMillis >= PulseInterval)
    {
      PulseLastMillis = PulseCurrentMillis;
      if (LEDState == StateLEDON)
      {
        LEDState = StateLEDOFF;
      }
      else
      {
        LEDState = StateLEDON;
      }
    }
    digitalWrite(GreenIntLED, StateLEDOFF);
    digitalWrite(RedIntLED, LEDState);
  }
  else
  {
    digitalWrite(GreenIntLED, StateLEDON);
  }
  break;

When you turn on the led, record the time.

After that, turn off the led if

The led is on and
Sufficient time has passed.

edit: this is what I would do.

//detect if sufficient time has passed
//1. turn on the led on button high -> low transition
//2. turn off the led after certain time (LED_DLY)
uint8_t led_ctrl(void) {
    static uint32_t led_timeoff=0;                              //time to turn the led off
    uint32_t time_now = millis();                               //take time now

    //if sufficient delay has passed, turn the led off
    if (isLED_ON() && (time_now >= led_timeoff)) {              //if led is already on
        LED_OFF();                                              //turn off the led
    }

    //if the button has experienced a the falling edge, turn on the led and set up the time to turn the led off
    if (btn_pressed()) {
        LED_ON();                                               //turn on the led
        led_timeoff = time_now + LED_DLY;                       //set up the time to turn off the led
    }

}

it is almost a literal implementation of what I wrote above.

here is the code in action, responding to button's falling edge with a 150ms delay turn off for the led: the button is on D12 and the led on D8.

fairly straight forward, isn't it?


Dynamically modifying the call stack using pointers In a C++ Arduino library, can we modify the call stack from inside a function by intentionally decrementing a pointer to a stack variable so that it's out of range? Like this:

void FooBar()
{
  char a;
  char *ptr = &a;
  ptr -= 4;
  // Can we edit the call stack with ptr now?
}

Can we use this to, for example, change what function is "calling" FooBar() by replacing the function pointer of the calling function on the call stack to another function? Or can we change the values of function variables in the calling function in mischievous fashion?

I am answering in the context of the AVR calling conventions, as they
are the only ones I know well enough to be able to answer here.

  Can we use this to, for example, change what function is "calling"
  FooBar() by replacing the function pointer of the calling function
  on the call stack to another function?

That will probably be impossible in C++. Let's say you have the
following call chain: main() → f() → FooBar(). In the body of
FooBar(), the stack will look like this (oldest stuff at top):

return address from f() to main()
registers saved by the f() prologue
return address from FooBar() to f()
registers saved by the FooBar() prologue

Getting the stack pointer is easy. No need to declare a dummy variable,
just:

char *stack_pointer = (char *) SP;

Now, to change the required return address, you need to skip over the
registers saved by the FooBar() prologue. And this is the big problem:
you do not know how many registers were saved there. Function prologues
are written by the compiler, and whatever they save depends on how many
registers are needed within the function, which in turn depends on the
complexity of that function. Even minor changes to the function can
modify the number of registers its prologue saves.

The only solution to this problem I can imagine is to forego the
compiler-generated prologue and write FooBar() in assembly. If you
wish to do it within a C++ file, you can attach the "naked" attribute to
the function and write its body using inline assembly.

  Or can we change the values of function variables in the calling
  function in mischievous fashion?

No need to tamper with the stack for this. The compiler strives to store
as many local variable as possible in CPU registers rather than the
stack. The caller's local variables are most likely still in those
registers and you can modify them at will (in assembly). That's why you
have this register-saving prologue and register-restoring epilogue in
the first place. Indeed, if you make the function "naked" and don't do
the saving/restoring yourself, you will very likely end up corrupting
the caller's locals.


How to convert this prototype to finished product? My prototype contains below components:

Arduino Uno R3
Bluetooth LE nRF8001 Break-out (https://www.adafruit.com/products/1697)
MicroSD Break-out (https://www.adafruit.com/products/254)
ADXL335 triple-axis Accelerometer

I think It's OK on paper (and presumably on a breadboard too). I'm trying to wrap my head around on how to convert it to a finished product that sits inside a plastic box.

What are my options?

For instance, can I create a single PCB that contains all the components? If not, how can I connect these multiple break-out boards together? Is soldering some wires on both boards to connect them is a viable option?

Edit:

My ultimate goal is to create a product that is for sale. So I mean something that can be mass-produced and can meet regulatory requirements.

This is why I was thinking about a single PCB. Arduino (or should I say ATMegaXXX?) is fairly simple to place on a custom PCB. So I was thinking perhaps I could "re-create" my break-outs (see above) on this PCB thus creating a single piece including all components and the microcontroller. For some reason this makes sense to me but I don't know how hard it is or if it is even possible.

First, you should read this this question here.

The reasonable answer here varies a lot depending on how involved you want to get, and what volumes you want to sell at.

Fortunately, you're not using any breakouts with truly exotic parts. The nRF8001 is just a QFN part, which can be soldered by hand without too much trouble.

Speaking loosely, the process would look like this:

Design a PCB layout that contains everything.
(Optional) - Figure out if you want to put it in a enclosure of some sort.
(Optional) - Determine how you're going to have the enclosures produced or modified from an existing product. You can have a contract machine-shop do the work, but again, $$$$.
Send out to have PCB prototypes manufactured. I like OSHPark, but there are LOTS of options.
Assemble your boards.
Find out your prototype doesn't work.
Go back to step 1 (expect this to happen a few times)
Rent/Beg/Borrow some equipment to do EMC pre-qualification testing (for FCC).
Realize you have an EMC disaster.
Respin boards a few more times (e.g. go back to 1 again) to fix the pre-qualification EMC issues.
Feel like you have a decent layout, have it FCC tested.
Pay $10K+ for FCC testing.
If you're lucky, you passed, you now have a proper, FCC certified product.
Nope, go back to 1 again if you failed.
Do lot assembly, either manually (major time investment), or contract out (expensive!).
Sell your widget!

Note that you can contract out the prototype assembly, but doing so is expensive, even if you do it in china. The magic (or cursed, really) term here is "NRE", or non-reoccurring expenses/engineering. Colloquially, it's the "setup cost" of doing a production run. Sure, you may only pay $5-50 per-widget to have them assembled, but there will be a $1000+ base charge. This reflects the fact that the primary time-cost on the part of an assembly house to build your widget is setting up the production line, working up and debugging a pick-and-place routine, building test-setups, etc... Once everything is up and running, the actual per-unit cost is fairly marginal.

This is also why commercial electronic devices can be so cheap. They're made in truly enormous volumes, and that lets the companies amortize the NREs across the entire production run. NREs are basically the bane of any small electronics business. They're also basically the reason specialty widgets are so expensive. Places like spark-fun can get away with fairly cheap products because they have their own complete assembly line in-house, and even there, you're often paying 4X+ the cost of parts for just the IC on a PCB with a few cents worth of passives.

Since you seem to be new to PCB design, this is possibly not a great first project. It's doable, but expect it to cost 4X+ what you expect, and take 2X+ the time you planned. There are a LOT of facets to designing a proper product, and they each contain an entire field.

It'd probably be better off to start out with some simpler boards, maybe a through-hole-only arduino clone, or similar (though SOIC can be soldered without a hot-air station or anything).

Some assumptions I'm making:

If you're serious, you will have to lean SMT assembly practices. Through-hole only is not a viable stance anymore.
Expect to buy a lot of tools, and burn a lot of money in failed prototypes.
Expect 3 board revisions. At minimum, before you have something you can get tested. I could maybe do it in 2, if I got really, really lucky, but I doubt that would happen, and this sort of thing is my day-job.

Hardware is HARD, and worse, it's completely unforgiving. If you're coming from a software engineering background, you basically have to discard all your assumptions, as they will actively hurt you.

Imagine a software project where "compiling" can take 4 weeks. That's hardware development.


clear serial buffer not working Also asked in forum.arduino.cc

bool receive_command(char answer[]);
void serial_flush(void);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  for(byte i=0;i<3;i++){
if(receive_command("OK")) Serial.println("OK found");
 serial_flush();
  }
}

void loop() {}

void serial_flush(void) {
  while (Serial.available()) Serial.read();
}

bool receive_command(char answer[]) {
 unsigned long _time = 0;
  const int max_time = 10000;
  bool flag = 0;

Serial.print("in Serial buffer=");
  Serial.println(Serial.available());
  if(Serial.available()){
  Serial.write(Serial.read());
  Serial.println(" left in serial buffer");}

  while (Serial.available() < 2) {
if ((millis() - _time) > max_time) {
      Serial.println("waited too long nothing received");
  return flag;
    }
    }
  do {
    if (Serial.findUntil(answer, '\n')) return flag = 1;
  } while (Serial.available());

return flag;

}

via serial monitor with CR+LF line ending I`m sending this string:
abcdefghijklmnopqrstuvwxyzOKabcdefghijklmnopqrstuvwxyz
26chars+OK+26chars+CR+LF=56 chars

Output:

in Serial buffer=0
OK found
in Serial buffer=1
b left in serial buffer
in Serial buffer=0
waited too long nothing received

after OK is found serial_flush() is executed but after second run there serial.available() shows there is something in serial buffer. right at that moment it was char 'b' but it also can show char 'd'  and 'c' depending how long it will run.

why serial_flush() is not clearing the buffer?

Thanks.

The processor is somewhat faster than serial input. If you really want to wait for nothing more to arrive you should probably add a short delay (although jsotola's suggestion of looking for a newline is sensible). Something like:

void serial_flush(void) {
 while (true)
   {
   delay (20);  // give data a chance to arrive
   if (Serial.available ())
     {
     // we received something, get all of it and discard it
     while (Serial.available ())
       Serial.read ();
     continue;  // stay in the main loop
     }
  else
    break;  // nothing arrived for 20 ms
   }
}


Create New Serial Class Inheriting from Stream How should I inherit from Stream, for creating a new class MySerial able to be initialized from a Stream0 instance?.

The error so far is: "cannot declare variable 'mySerial' to be of abstract type 'MySerial'".

If I make a class MySerial not inheriting, but adding a property Stream, everything works fine, except the new call mechanism for the resend() function, created to accept Stream instances.

EDIT: This is the edited code. Current error is: "expected unqualified-id before '=' token".

MySerial.h

class MySerial:public Stream{
    private:
        int param;
    public:
        MySerial(){}; // OK
        MySerial(Stream &Serial0){MySerial=&Serial0} // Here is the question
        // Stream Implementation
        int available(){return available();}
        int read(){return read();}
        int peek(){return peek();}
        size_t write(uint8_t c){return write(c);}
        using Print::write;
};

MySerial.ino

#include <MySerial.h>
#include <SoftwareSerial.h>

SoftwareSerial swSerial(6,7);
MySerial mySerial(swSerial);

void setup(){}
void loop(){
    if (mySerial.available()){
        c=mySerial.read();
        resend(mySerial,c);
    }
}
// This function should accept any Stream: SoftwareSerial, MySerial, Serial...
void resend(Stream &Stream0, char c){
    Stream0.write(c);
}

The Stream class has pure virtual methods which must be implemented in derived not abstract class.

The pure virtual method from base class Print is:

virtual size_t write(uint8_t) = 0;

The pure virtual methods from Stream are:

virtual int available() = 0;
virtual int read() = 0;
virtual int peek() = 0;

additionally add in your class the line

using Print::write;

to pull in overloaded methods write(str) and write(buf, size) fromPrint

Here I have an example of a simple class derived from Stream.

EDIT: Most of your question seemed to focus on wrapping some Stream implementation. Now I see that you maybe want to enhance the SoftwareSerial class and add a new method in the inherited class. It is simple:

MySerial.h

#ifndef _MYSERIAL_H_
#define _MYSERIAL_H_

#include <SoftwareSerial.h>

class MySerial: public SoftwareSerial {
private:
  int param;

public:

  MySerial(uint8_t receivePin, uint8_t transmitPin) :
      SoftwareSerial(receivePin, transmitPin, false) {
    param = 0;
  }

  void resend(char c) {
    write(c);
  }
};
#endif

MySerial.ino

#include "MySerial.h"

MySerial mySerial(6, 7);

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

void loop() {
  if (mySerial.available()) {
    int c = mySerial.read();
    mySerial.resend(c);
  }
}


How does supply voltage affect `analogRead()` on AVR-based microcontrollers? I'm using an ATmega328P based Arduino to prototype reading a TMP36 temperature sensor. I will eventually move this to an ATtiny85 based board with a battery supply. Both the TMP36 and ATtiny85 have a Vcc range from 2.7V to 5.5V so a battery that starts at say 4.5V and slowly drops to 2.7V should not be out of range.
I am expecting to read temperatures in the range -5°C to +30°C which should correspond to a TMP36 output between 0.5 to 0.9V. I am getting 0.74V at around 23°C so this sort of range seems plausible.
The TMP36 outputs 10 mV/°C regardless of Vcc (within 2.7-5.5v). But I suspect the AnalogRead() value will be scaled by the supply voltage and so will slowly change as the battery drains. Is this correct?
Do I need to include an external voltage-regulator / voltage-reference device to supply some fixed voltage (e.g. 2.5V) to AREF?

Solution
Following Edgar Bonet's Answer I successfully enabled the internal voltage reference for the ADC.
Initially I added a 100nF bypass capacitor to AREF and tried
#define REFS1 7
#define REFS0 6
#define REFS2 4

...
//ADMUX = (_BV(REFS1) | _BV(REFS2)); // 2.56V ATtiny85   datasheet §17.3 pp134
ADMUX = (_BV(REFS1) | _BV(REFS0)); // 1.1V  ATmega328P datasheet §23.9 pp217

but didn't get it to work, my code had no effect on values from analogRead(). So after a bit of further reading I instead used
analogReference(INTERNAL);

Which worked.

The ADC measures a voltage ratio. The conversion result is the rounded
value of 1024×V/Vref, where V is the voltage at the input and
Vref is the voltage reference.
In the default Arduino configuration, the reference is connected to Vcc.
This will not fit your use case, as the voltage you want to read does
not vary proportionately to Vcc. You could use an external reference.
However, the ATtiny85 has two internal voltage references at 1.1 and
2.56 V. Either of these may be well suited for you application,
which should save you having to add an extra part.
See the chapter on the ADC in the datasheet for details on
how to select the voltage reference.


Underwater positioning system (swimming pool) I'm making a few experiments with a quite simple rover car I made using Arduino UNO and a few spare parts. Just for the heck of it I made it waterproof and now I want to toss it in my pool to make some underwater exploration. Maybe I'll fit some scrubers under it to make it easer to clean the floor.

My problem is: my rover navigates on its own, avoiding walls and objects using an ultrasonic sensor. But underwater the speed of sound goes up, and different qualities of water make it even harder for this system to work. Sometimes the pool is full of particles, and the scruber will probably worse the water quality around the robot.

My question is: what kind of system is better to navigate underwater, simply avoiding walls? The current behavor (on dry ground) is to turn to the right and go on when it finds a wall, I would like to keep this behavior, but underwater. As it's a simple toy, I'm hardly willing to spend a hundred bucks on a fancy laser proximity sensor, neither I need to map the entire pool with a single pulse, it should be a simple wall avoiding system.

Thank you!

How about a tilt switch?  The bottom corners of a pool should allow the car to ride up the wall a little, when it tilts past 5 or 10 degrees, turn it left.....


Can I use arduino to generate 8mhz frequency ultrasonic pulses in piezo discs? void setup()
{
    pinMode(freqOutputPin, OUTPUT);
    Serial.begin(9600);

    // Set Timer 2 CTC mode with no prescaling.  OC2A toggles on compare match
    //
    // WGM22:0 = 010: CTC Mode, toggle OC
    // WGM2 bits 1 and 0 are in TCCR2A,
    // WGM2 bit 2 is in TCCR2B
    // COM2A0 sets OC2A (arduino pin 11 on Uno or Duemilanove) to toggle on compare match
    //
    TCCR2A = ((1 << WGM21) | (1 << COM2A0));

    // Set Timer 2  No prescaling  (i.e. prescale division = 1)
    //
    // CS22:0 = 001: Use CPU clock with no prescaling
    // CS2 bits 2:0 are all in TCCR2B
    TCCR2B = (1 << CS20);

    // Make sure Compare-match register A interrupt for timer2 is disabled
    TIMSK2 = 0;
    // This value determines the output frequency
    OCR2A = ocr2aval;

    Serial.print("Period    = ");
    Serial.print(period);
    Serial.println(" microseconds");
    Serial.print("Frequency = ");
    Serial.print(freq);
    Serial.println(" Hz");
}

void loop(){}

I am working on a project where i need an ultrasonic pulse of 8Mhz every one second and emitter is piezo disc. Please help me with the code.

With 8 Mhz pulse, I assume you mean a pulse of 0.125 µs duration every second. "Frequency" may be misleading here.

Since the ATmega328 in the Arduino Uno is only clocked at 16 Mhz, you only have one extra cycle before having to turn it back off. Debugging and developing at this sort of speed absolutely requires a good oscilloscope.

I would attempt setting your output pin via register, and then turning it off again right after. Use cli() to prevent interrupts during your desired pulse.

void setup() {
  DDRC |= (1 << DDRC0);   //Set PC0 as output (Analog Pin 0)
}
void loop() {
  cli();                  //Disable interrupts
  PORTC = 0b00000001;     //Set Analog Pin 0 HIGH
  PORTC = 0b00000000;     //Set Analog Pin 0 LOW
  sei();                  //Enable interrupts again
  delay(1000);            //Delay for 1000ms until next pulse
}

Beware that this would also set all other pins on Port C (Analog Pins 1 through 5) LOW.

This

  PORTC |= (1 << PORTC0);     //Set Analog Pin 0 HIGH
  PORTC &= ~(1 << PORTC0);     //Set Analog Pin 0 LOW

would be cleaner and only affect Analog Pin 0, but it may take more than one clock cycle to execute.
Unfortunately, I don't have a quick enough oscilloscope to try this out.
If it is too fast (e.g., you get a pulse of duration 0.06125 µs, you may want to insert another PORTC = 0b00000001; before turning it off again. It is not unlikely that compiler optimization might just remove this when compiling, so you may have to set some other register to waste that one clock cycle.


How can I make motor vibrate using arduino depending on the ultrasonic distance? I want to make the vibration motor vibrate depending on the distance to an obstacle, for example if the distance is too short it should vibrate quickly and vice versa.

How can i make motor vibrate using arduino depending on the distance?
Can you explain for me how can I use the delay in the vibration code?
I found this code in the internet for vibration:

digitalWrite(y, HIGH);
delay(50);
digitalWrite(y, LOW);
delay(50);

I know that I can change the delay, but how can we do it depending on our purpose?
Please help me .. I don't know the use of the delay :(

You could just replace the "50" in the first delay with the ultrasonic distance variable, I'll explain a bit more below.

Let's assume your ultrasonic sensor outputs an analogue value between 0V and 5V. The output is connected to analog pin A0. Then you just set pinMode(A0, INPUT) and analogRead the value from the pin and store it in the variable X or whatever. Then you just use the variable X as a delay and it will do what you want. The higher the value gets the longer it will vibrate. Something like this:

[...]
val = analogRead(A0);
digitalWrite(5, HIGH);
delay(val);
digitalWrite(5, LOW);
[...]

Second option, if you only wish to turn it on if it is above or under a certain limit, would be using an if condition.

For example:

if(variable > 50){
  // if the variable named variable is over 50 this code is going to be executed
} else {
  // If the variable is below 50 this is executed
}

If you are unfamiliar with if conditions then I suggest reading this too.


Unable to upload code on Arduino Nano My Arduino Nano v3.0 (made by Gravitech US) is behaving in an unexpected manner. Whenever I try to upload a simple Blink program on the board it always give error which is shown below.

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x01
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x01
...

I have another Nano (a Clone) and an Arduino UNO, both of which work perfectly using the same USB cable and PC.

History: When I used this Nano (original) for the first time, it was having some issue related to the FTDI chip. The FTDI USB was locking up on power up. I referred an answer from Arduino Nano 3.0: FTDI USB locks up on power up.  I shorted the pin no. 26 (TEST) and 25 (AGND) on the FTDI chip, and then I was able to use it. I uploaded the Blink program and tested it, which was working fine.

Now, at present (three years later), when I try to upload even a simple Blink example sketch on it, it never succeeds, and gives me the above mentioned error.

I also tried holding the reset button and releasing it when it shows

  Uploading...

Another Issue: Sometimes when I just check the continuity on my Arduino Nano just to confirm whether the hardware is okay or not, it gives me unexpected results. On checking, the Pins RST and GND get shorted sometimes. And sometimes even VCC, RST and GND get shorted. I also checked the small reset switch on board, and it is working fine.

I contacted Gravitech, but they aren't responding.

What can be the issue with my arduino Nano? I haven't used it yet in any of my project. Just the Blink program that I uploaded 3 years ago on it, was the last time I saw it working.

Any help would be greatly appreciated.

Select Tools>Processor>ATmega328p(old bootloader)

I was having the same problem. The default uploaded sketch was causing the problem. The code was reading one of the analog pins and throwing the value via serial port and causing the problem. Changing to old bootloader fixed it for me


Uploading/Flashing different programs to two different Arduino uCs, using one USB I'm designing a custom dual-uC board, where I want there to be two Arduinos both running different programs - kind of dual core arduino. In order to load new programs onto the uCs, yes, I could have two USB ports each connected to one of the uCs (say a ATmega32u4). But I'm trying to work out strategies with just one USB port (and no usb-hub).

Also, I don't need the USB functionality for general use, only for program updates.

Option 1:

Switch access to each USB capable Arduino (e.g. ATmega32U). Program one uC, toggle switch, program other uC

EDIT: this is fine, however I ideally want to use zero additional end-user buttons - I want the end-user to do as little as possible.

Option 2:

The arduino UNO has two devices, ATmega16U2 and a ATmega328. During normal operation the 16U operates as a usb-to-serial. However, I'm aware that there are custom firmwares that allow different functionality (such as USB-Joystick etc) - it is possible to switch firmawares between a custom-firmware and default firmware, to allow the ATmega328 to be programmed normally but also to run the custom program. But it seems that Arduino.h doesn't support the ATmega16U2, so I would have to program this device using the AVR or another framework.

Alternatively, the ATmega32U4 is supported by Arduino.h but there doesn't seem to be Arduino usb-serial 'firmware' for the 32U (only the 8U & 16U)

Option 3:

Can I use a ATmega32u4 with Arduino-ISP programming an ATmega328p?

EDIT: above seems valid:
https://petervanhoyweghen.wordpress.com/2012/09/16/arduinoisp-on-the-leonardo/

Other simple recommended approaches?

EDIT: the firmware update should be physically as hands off as possible, as to be used by end-user, and preference for solutions that require zero additional buttons/etc

UPDATE:

I tried the Arduino as ISP method (option 3), and it works

Provided that you are okay with producing a customized PC side tool (which you would probably want anyway for user convenience) automated target selection should be far superior to manual.

You should be able to use one ATmega16u2 with a  minimally customized firmware as a front end to program two distinct ATmega328p's.  This could be as simple as selecting the target based on the baud rate, having it hold the de-selected one in reset the whole time, and using some resistors on the shared TX lines for safety.  Last I checked the stock firmware used a soft serial at some rates, and that can be put on different pins, so it could be another way to de-conflict and select targets.

Your idea of using a 32u4 both as a functional part and as a buddy-programmer for another part is perfectly valid too - you can do that programming to a serial bootloader (it should be a simple matter to port the 16u2 firmware, or find another example), or via the ISP pins.

Now that I think about it, there's been a version of this question here before, as I remember writing about an idea for using two ATmega328p's permanently wired to a stock USB-serial, but with their bootloaders customized to use unique baud rates, and a little logic added so that on reset each would leave its serial TX pin tristated if it didn't detect bootloader traffic at its individually unique baudrate, thus allowing the other to be programmed without interference.


Arduino Uno + Sim808: Using HTTP client for GPRS GSM My problem is that I do not want to use AT commands everywhere to get/post data to my web server because it is brainstorming with all the delay and anything. I want to use library like gsm.h or something similar. Is there simple libraries which I can use to do the HTTP/HTTPS request (get/post) to my web server?

This code is my attempt with gsm.h, but it does not work. I suppose it only works with Arduino + Telefonica GSM/GPRS shield, not Sim808:

/*
 Web client

This sketch connects to a website through a GSM shield. Specifically,
this example downloads the URL "http://www.arduino.cc/asciilogo.txt" and
prints it to the Serial monitor.

Circuit:
* GSM shield attached to an Arduino
* SIM card with a data plan

created 8 Mar 2012
by Tom Igoe

http://www.arduino.cc/en/Tutorial/GSMExamplesWebClient

*/

// libraries
#include <GSM.h>

// PIN Number
#define PINNUMBER ""

// APN data
#define GPRS_APN       "GPRS_APN" // replace your GPRS APN
#define GPRS_LOGIN     "login"    // replace with your GPRS login
#define GPRS_PASSWORD  "password" // replace with your GPRS password

// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;

// URL, path & port (for example: arduino.cc)
char server[] = "arduino.cc";
char path[] = "/asciilogo.txt";
int port = 80; // port 80 is the default for HTTP

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

    Serial.println("Starting Arduino web client.");
    // connection state
    boolean notConnected = true;

    // After starting the modem with GSM.begin()
    // attach the shield to the GPRS network with the APN, login and password
    while (notConnected) {
       if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &
       (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) {
          notConnected = false;
       } else {
          Serial.println("Not connected");
          delay(1000);
       }
    }

    Serial.println("connecting...");

    // if you get a connection, report back via serial:
    if (client.connect(server, port)) {
       Serial.println("connected");
       // Make a HTTP request:
       client.print("GET ");
       client.print(path);
       client.println(" HTTP/1.1");
       client.print("Host: ");
       client.println(server);
       client.println("Connection: close");
       client.println();
    } else {
      // if you didn't get a connection to the server:
      Serial.println("connection failed");
    }
}

void loop() {
     // if there are incoming bytes available
     // from the server, read them and print them:
     if (client.available()) {
        char c = client.read();
        Serial.print(c);
     }

     // if the server's disconnected, stop the client:
     if (!client.available() && !client.connected()) {
        Serial.println();
        Serial.println("disconnecting.");
        client.stop();

        // do nothing forevermore:
        for (;;)
        ;
     }
 }

Is there GSM/GPRS library that I can use with Sim808?

Start Arduino IDE, open the Library manager, search for SIM800 and there is 3 libraries available there that you can install. The advantage is that this libraries is kept up to date and when a new version is available you will get a notice to upgrade.

There is a HTTP PUT/GET library "HttpClient" that can be installed the same way as above.

Or

If you googlem using "sim800 library arduino" you will find several libraries like:

https://cristiansteib.github.io/Sim800l

or on github:

https://github.com/search?l=Arduino&q=sim800&type=Repositories&utf8=%E2%9C%93

And as I understand it the 808 is GSM/GPRS + GPS, so the GPS features isn't normally covered by these libraries.


Add nRF24L01 to a project I Have a Liquid Level Project that Currently uses an Oled display.  I have just discovered the existence of the nRF24L01 wireless communication module; and it is exactly what I need to make my project more user friendly.
Eventually I want to have a dashboard that brings all my info together in one place, but for now I just want to figure out how to get my Liquid Level Project transmitting, and receive the data on another Arduino and view it on the Serial monitor.  As is all it does is print out "?" in the Serial monitor.
I have this Sketch on the Liquid Level Project Arduino:
#include <Wire.h>
#include "SSD1306Ascii.h"
#include "SSD1306AsciiAvrI2c.h"
SSD1306AsciiAvrI2c oled;
#define I2C_ADDRESS 0x3C
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

double SensorAnalogValue;
uint8_t calculation=1;
String Show_value;

//create an RF24 object
RF24 radio(9, 8);  // CE, CSN

//address through which two modules communicate.
const byte address[6] = "00001";

void setup()
{

  Serial.begin(9600);
  oled.begin(&Adafruit128x64, I2C_ADDRESS);
  oled.setFont(CalLite24);
  oled.clear();

  radio.begin();

  //set the address
  radio.openWritingPipe(address);

  //Set module as transmitter
  radio.stopListening();

}

void loop()
{

  SensorAnalogValue = analogRead(A0) * 5.0 / 1023.0;
  if (SensorAnalogValue < 1.726) {
    calculation=0;
    Show_value="Low";
  }
  if (SensorAnalogValue > 4.04) {
    calculation=0;
    Show_value="High";
  }
  if(calculation!=0){
  //  Serial.println(SensorAnalogValue);
    Show_value=(String)Liquid_Volume(SensorAnalogValue);
  }
  Serial.println(SensorAnalogValue);

oled.setCursor(20, 0);
  oled.print(Show_value);
  oled.print(" L");
  oled.println(" ");
  oled.print(Show_value);
  oled.print("L");
  oled.println(" ");
delay(500);
   oled.clear();

  radio.write(&Show_value, sizeof(Show_value));
  delay(1000);

  calculation=1;
}
int Liquid_Volume(double Volt) {
  double A =   2.81842;
  double B = -11.00151 ;
  double C =  14.4765 ;
  double D =  28.73579 ;

  return A * Volt * Volt * Volt + B * Volt * Volt + C * Volt + D;
}

And the Receiver has this:
//Include Libraries
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

//create an RF24 object
RF24 radio(9, 8);  // CE, CSN

//address through which two modules communicate.
const byte address[6] = "00001";

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

  radio.begin();

  //set the address
  radio.openReadingPipe(0, address);

  //Set module as receiver
  radio.startListening();
}

void loop()
{
  //Read the data if available in buffer
  if (radio.available())
  {
    char Show_value[32] = {0};
    radio.read(&Show_value, sizeof(Show_value));
    Serial.println(Show_value);
  }
}

I think the problem is in:
radio.write(&Show_value, sizeof(Show_value));

I believe "radio.write" is used kinda like Serial.print, or oled.print,  But I don't really understand the "sizeof" part, maybe that is the problem?

radio.write(&Show_value, sizeof(Show_value));

I believe "radio.write" is used kinda like Serial.print, or
oled.print, But I don't really understand the "sizeof" part, maybe
that is the problem?

Sort of.  There's kind of two interrelated problems.  The major one is that the actual data of a String is not contained with the actual String type itself.  It's allocated on the heap.  What the String class contains is a pointer to it and some numbers for tracking the allocated size and amount used.
So the first problem is you're not reading the memory that actually contains the text inside the string.
sizeof(Show_value) evaluates to the size in bytes of the String class itself, which is the size of a pointer and a couple of integers, about 6 bytes, and not the size of the content of the string.
So you're sending a pointer (a memory address) that the receiver wouldn't know what to do with, and some information about how much was allocated and used and nothing of the String content.
Try:
radio.write(Show_value.c_str(), Show_value.length());

.c_str() gets a pointer to the actual string content itself.  And .length() is the actual size of the used part of the String's allocated area on the heap.
That said, it's better to avoid String where you reasonably can.

Regarding:

Does this also mean I need to replace radio.read(&Show_value, sizeof(Show_value));

It would. Doing that is a bit more complicated since .c_str() yields const char *; String isn't designed to make write-access to its underlying data as easy.
Without hacking your way around String's expectations, that would require using a temporary buffer. Something like:
char buffer[33] = "";  // Note: this will actually fill the entire buffer with '\0', which some find a surprise.
// The idea in the above is to accommodate the maximum RH24L01 packet size 32 bytes plus room for a null terminator.

radio.read(buffer, sizeof buffer - 1);  // We're only making the 32 byte chunk available to the .read() call, and leaving the last byte to it's '\0' value to force null termination in any case.

String s = buffer;

This assuming that you're either filling the packet with bytes, or including the null terminator in the packet, or both.  If you're using a dynamic payload size, rather than initializing the array with = "";, it could be left uninitialized and the received packet size could be used to place the null terminator at the location needed.
You could wrap this in a function if you plan on doing it a lot.  But again, it's probably better if you can just use the array and not work with String.


sleep and wake up arduino mega according to ds3231 interrupt how can I make my arduino mega sleep during 6pm-7am..and wakes or stay up during 7am-6pm and doing its job like activating the solenoid valve based on my soil moisture sensor reading.this is for my backyard farm.anyone can help me making a code for it? please i really need it.

here is my code

#include <DS3231.h>
#include <Wire.h>
#include <avr/sleep.h>

 int wakePin = 2;   // pin used for waking up
 int led = 13;

 DS3231 clock;
 RTCDAteTime dt;

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

 // initialize DS3231
 Serial.println("Initailize DS3231");
 delay(100);
  clock.begin();
  pinMode(wakePin,INPUT_PULLUP);
  pinMode(led,OUTPUT);

   //Disarm alarms and clear alarms for this example, beacuse alarms is battery backed.
   //Under normal conditions, the settings should be reset after power and restart microcontroller
   clock.armAlarm(false);
   clock.clearAlarm();

   //Set Alarm1 - Every 20s in each minute
   // setAlarm1(date or day,hour,minute,second,Mode,Arrmed=True)
     clock.setAlarm1(0,0,0,20,DS3231_MATCH_S);
     attachInterrupt(0,wakeUpNow,LOW);

   //check alarm settings
    checkAlarms();
  }

   void checkAlarms()
  {
   RTCAlarmTimea1;
   RTCAlarmTimea2;

    if (clock.isArmed1())
   {
    a1 = clock.getAlarm1();

     Serial.print("Alarm1 is triggered:);
     switch(clock.getAlarmType1())
    {

       case DS3231_MATCH_S:
       Serial.print("When seconds match: ');
       Serial.println(clock.dateFormat("_ _:_:s",a1));
       delay(100);
        break;
        default:
         Serial.println("UNKNOWN RULE");
         break;
     }
    }
   }

       void wakeUpNow()
   {
       //execute code here after wake-up before returning to the loop() function
      //timers and code using timers(serial.print and more...)will not work here.
     //we don`t really need to execute any special functions here, since we
     //just want the thing to wake up
      Serial.print("Woke up");
     delay(100);
     }

      void sleepNow()
     {
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);  //sleep mode is set here
      sleep_enable();   //enables  the sleep bit in the mcucr register
      attachInterrupt(0,wakeUpNow,FALLING); //use interrupt 0(pin2) and run function
      sleep_mode();
         // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

         sleep_disable();  //first thing after waking from sleep: disable sleep
         detachInterrupt(0); //disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running
          time.
        }

         void loop()
        {
           dt=clock.getDateTime();

             Serial.println(clock.dateFormat("d-m-Y H:i:s-I",dt));
              delay(100);
           //Call isAlarm1(false)if you want clear alarm1 flag manualy by                     cleaAlarm1();
              if(clock.isAlarm1())
           {
                 Serial.println("ALARM 1 TRIGGERED!");
                 digitalWrite(led,HIGH);
                   delay(1000);
                  digitalWrite(led,LOW);
                  Serial.println("Entering Sleep");
                    delay(100); //sleep fucntion called here
                     sleepNow();
               }
                delay(900);
               }

First, Arduino Mega does not have an RTC (Real Time Clock) built-in. So, to program it the way you like, would mean either using a module like DS3231 or similar, or have the Mega connected to internet, with a network card module like ENC28J60 and getting the time from there. If you don't use any of those methods basing your scheduler only on the Arduino internal timer (using sleep for example) will result in program needing to set the correct time each time Arduino is powered.


Identify connected PC per Arduino Question:
Is there a way to collect any data (e.g. MAC addresses, installed devices, driver versions, etc.) from a PC by simply connecting an Arduino via USB to it, so that this PC can be clearly identified?

Background:
Basically, I`m using an Arduino to send some text to a computer by emulating a keyboard, but I don´t want the text to be sent to any computer I connect the Arduino with. That is why I want the PC to be identified first.

To be clear: this should be done without having to install programs on the PC in the first place.

No you cannot. Arduino communicates to pc via UART so there must be a host which can send or receive the data. You have to install software on the host computer which can send and receive data to the com port to which arduino is connected to.


Undefined functions send() and receive() on TwoWire/SPI I have downloaded a sketch that uses SPI.  The sketch includes the Wire library but at compilation time, I am getting errors that TwoWire doesn't have methods called send() and receive()?

This is caused by the sketch you downloaded being old.  In prior releases, the methods called send() and receive() were used to send and receive SPI data.  These were renamed to be write() and read().  If you change your code where there are references to Wire.send() and change to Wire.write() and also change Wire.receive() to Wire.read(), you should find that your applications compile and run correctly.


uBlox LEA 6H and UNO no data While using NEO 6M and getting close-to-perfect accuracy, connecting the 3dr uBlox LEA 6H shows incoming characters, but gibberish data (at 38400) like it is connecting to a wrong baud rate (although it isn't, i've checked it with u-center and works when connected to Ardupilot).
So i guess it is some kind of configuration to show only certain parts of NMEA (if it is showing NMEA and not something else).

Your uBlox LEA 6H is most likly configured to use the UBX binary protocol and not NMEA at all. This protocol, as well as how to switch your LEA 6H between NMEA and UBX is in this document, from the uBlox website:
http://www.u-blox.com/images/downloads/Product_Docs/u-blox6_ReceiverDescriptionProtocolSpec_%28GPS.G6-SW-10018%29.pdf

You may be able to use the code from the ArduPilotMega project to communicate in UBX, they use the UBX protocol and the code is open source, but I can't guarantee its very good quality.


SPI communications with an Yost Labs IMU I am pairing an Arduino UNO with a Yost Labs 3-Space Sensor Nano, the user manual for said sensor can be found here and the user manual for the sensor family here (kinda confusing, Yost Lab's documentation contradicts itself IMO)
This is my code, pretty straight forward (although this is my first time working with SPI). I am 100% sure the wiring is correct, and I have attached a diagram of my wiring here. The logic voltage converter I am using is this
I believe that as per the user manual, this should successfully return 3 floats in 4 bytes each, corresponding to the filtered euler angles of pitch, yaw, and roll. However, all I am reading is bytes full of 0xFF (or 11111111 in binary) which I believe corresponds to null / no command.
Are there any visible errors in my code?
#include <SPI.h>

SPISettings settings(6000000, MSBFIRST, SPI_MODE0 ); //variable to hold SPI settings
//Set Slave Select, MOSI, MISO, CLK
const int CSN = 10;
const int SI = 11;
const int SO = 12;
const int CLK = 13;

// Needed to convert the bytes from SPI to float
union u_types {
   byte b[4];
   float fval;
} data[3];  // Create 3 unions, one for each euler angle

void setup() {
 //Set Pin Modes
 pinMode(CSN, OUTPUT);
 pinMode(SI, OUTPUT);
 pinMode(SO, INPUT);
 pinMode(CLK, OUTPUT);
 //Set Slave Select High to Start i.e disable chip
 digitalWrite(CSN, HIGH);
 //Initialize SPI
 SPI.begin();
 //pour a bowl of serial
 Serial.begin(9600);
}

//function to transfer commands through SPI
byte transferByte(byte byteToWrite) {

 byte Result = 0x00;
 digitalWrite(CSN,LOW);
 delay(1);
 Result = SPI.transfer(byteToWrite);
 delay(1);
 digitalWrite(CSN,HIGH);
 return Result;
}

//function to swap endian
void endianSwap(byte temp[4]) {
 byte myTemp = temp[0];
 temp[0] = temp[3];
 temp[3] = myTemp;
 myTemp = temp[1];
 temp[1] = temp[2];
 temp[2] = myTemp;
}

void loop() {
 SPI.beginTransaction(settings);

 // Clear the internal data buffer on the IMU
 byte result = transferByte(0x01);
     Serial.print("Cleared internal buffer. Result: "),Serial.println(result);

 // Send start of packet:
 result = transferByte(0xF6);
      Serial.print("Send start of packet. Result: "),Serial.println(result);

 // Send command (tared euler angles)
 result = transferByte(0x01);
      Serial.print("Send commmand 0x01. Result: "),Serial.println(result);

 // Get status of device:
 result = transferByte(0xFF);
      Serial.print("Status of device. Result: "),Serial.println(result);

 while (result != 0x01) {  // Repeat until device is Ready
   delay(1);
   result = transferByte(0xFF);
   Serial.print("Status of device. Result: "),Serial.println(result);
 }

 // Get the 12 bytes of return data from the device:
 for (int ii=0; ii<3; ii++) {
   for (int jj=0; jj<4; jj++) {
     data[ii].b[jj] =  transferByte(0xFF);
     delay(1);
   }
 }

 SPI.endTransaction();

 for( int mm=0; mm<3; mm++) {
   endianSwap(data[mm].b);
 }

 Serial.print("fval 1:"), Serial.println(data[0].fval);
 Serial.print("fval 2:"), Serial.println(data[1].fval);
 Serial.print("fval 3:"), Serial.println(data[2].fval);

 delay(3000);
}

You almost certainly shouldn't raise CSN after each byte, only after the entire packet.
Although the data sheet is not explicit the chip select is usually used to frame an entire command. As it is at the moment it keeps starting a new transaction.
I like the comment in the data sheet that "...the 3-Space Sensor will not work properly in outer space or on planets with no magnetic field".


Connect 12v DC sensor to Arduino UNO using TTL RS485 I'm trying to connect Arduino Uno with BGT PM2510 sensor (which uses 7-12V DC) by using UART TTL to RS485 Two-way Converter.
The only thing I wonder is can the sensor damage the MCU ?
According to the information on 12v sensor, it says:
Output signal: RS485 (Modbus protocol), I did measurement on A & B port of that sensor, the multimeter shows 3.3V.
My question is, can the sensor damage the MCU. I intend to connect Arduino & sensor as the diagram below:

Thank you,

You should be fine.
RS-485 does specify signal levels of ±1.5V to ±5V, but even so, and even when the sensor would misbehave or when the common mode voltage is low or high, there is still the TTL-to-RS485 converter in the middle that has 5V TTL logic on the Arduino side.
As long as the TTL-to-RS485 converter is properly connected to the Arduino and working as it should, the Arduino is safe.


How do I detect the Computer's operating system? I'm working on an emoji keyboard and it requires different input depending on the OS it's connected to. I've written the relevant methods using Arudion's default Keyboard library and can manually set which one is used. I'm wondering if there is a method or library for Arduino (currently using a Adafruit Feather 32u4 Bluefruit LE) that allows me to detect the OS.

If not, I'll set up a switch, but that'll cost me pins.

If you can't get the OS from the USB port, why not use the existing keys/inputs to set the mode on startup? That is, if you tell the user to press different combinations of 2 buttons on startup, you have 4 (2 bits => 4 values) different paths on startup:

00 => Normal startup, don't change mode
01 => OS 1
10 => OS 2
11 => OS 3


Get USB host controller serial number or ID using Teensy or other HID devices I have a Teensy board and would like to know if there's a way to get a serial number (or any other kind of ID that is preferably unique) of the host controller that I plug my Teensy into. E.g. can I get any unique identification numbers of my Macbook's USB controller when I plug my Teensy into it? C/C++ code examples for Teensy would be highly appreciated.

Nothing in the USB spec requires the host to provide any sort of identification to connecting devices. The standard way of implementing what you want consists in writing a custom driver which communicates the necessary information to the device. If installing a custom driver is not an option, all you can do is try to detect the OS by observing what it does during the enumeration process. Such identification will not be reliable (enumeration process can change after an OS update) and by no means unique.

Note that if your goal is to make sure the host is trusted, a simple ID will not be enough as it can be easily spoofed. You'll have to implement some sort of authentication scheme, e.g. challenge-respose.


How to include  outside the .ino file As I understand, Arduino IDE considers two paths for the libraries:

first,

  "C:\Program Files\Arduino\libraries"

and second, the "libraries" folder next to the schetchbook.

I have a configuration.h file, that I include in the main file, Test.ino, like this:

#include <configuration.h>

and in the configuration.h file I try to include SPI.h like this:

#include <SPI.h>

But I get the following error:

fatal error: SPI.h: No such file or directory

It seems that I am obliged to include SPI.h only from the ino file. But why?
And how can I do what I want here? do I have to change IDE?

P.S: the software is large and I am improving maintainability.

See my answer How the IDE organizes things. There is no easy way to avoid having to put an include in the main .ino file, unless you write your own build process (or perhaps use another toolchain).

I think you could put SPI.h (and other things, like Wire.h) in the main .ino file, even if they aren't used due to your configuration parameters. The linker would strip them out because the modules were not referenced.


Remove Function at Preprocessor Time I have a single function for debugging messages, used through all the project. When KEYDEBUG is defined as 1 or 0, the function is enabled or disabled as required.

#define KEYDEBUG 0

void debugging(int var){
   #if KEYDEBUG
   //Assert
   #endif
}

When checking the compiler, the variable var raises a warning -Wunused-parameter.
How should remove this warning just at this part of the project?
Or which other alternative for using debugging code and removing it from memory for production release?

In your case you do not use the entire body, so you can use a macro.

This way the code when KEYDEBUG is 0, will be like the complete function would not exist (except for the void cast, see below).

#include "assert.h"

#define KEYDEBUG 0

#ifndef KEYDEBUG
#define debugging(x) void(x);
#endif

void debugging(int var){
   assert(var);
}

void setup() {
  // put your setup code here, to run once:
  debugging(1);
}

The information below is for not using the function parameter, but keep the function (in case you have code in your function that also does something when KEYDEBUG is 0.

Unused attribute

The cleanest way I could find is using the unused attribute:

#if KEYDEBUG
   void debugging(__attribute__((unused)) int var){
      //Assert
#else
   void debugging(int var){
      //Assert
#endif
   }

or if you prefer better readability:

#if KEYDEBUG
   void debugging(__attribute__((unused)) int var){
      //Assert
   }
#else
   void debugging(int var){
      //Assert
   }
#endif

Cast to void

Less clean but does the job:

void debugging(int var){
   #if KEYDEBUG
      //Assert
   #else
      (void) var; // prevent unused parameter warning
   #endif
}

Macros/Parameter

It's not easy to remove the variable since it's used in a function and will be called from many places probably. You could maybe you use a macro but that gets messy soon.

This solution works, and afaik the compiler will optimize the code out (if not , it will cost very less anyway).


How to check if a GSM module is working or not? I wanted to know if my GSM sim800 is working or not. A mishap occured while I was experimenting around with my GSM module and I arduino uno. The link to the module which I bought: http://www.ebay.in/itm/SIM800-Quad-Band-GSM-Module-with-SMA-Antenna-Better-than-SIM900A-or-SIM900-/301782413058?hash=item4643a22f02:g:8LsAAOSwwbdWMidW I want to know ow can I check if my module is fine?

Power it up and check the 'status' light.  If it blinks with a 1 blink per second cycle, it is attempting to connect to the network.  If it connects, it does a slow blink at 1 blink/3s, it made the network connection.

I don't know if your board does an auto-power-on, but you might need to push the power button or reset button.


HC-0# Bluetooth module questions I've been playing with the HC-06 BT module lately, but now I want to do more with it and I'm not sure how to. I was wondering if it's possible to get signal strength from the module, or would I have to purchase another HC-0# module to do so? Also the HC-05, can initiate connection if I'm understanding documentation right, and return available devices in the area?

I was wondering if it's possible to get signal strength from the module

No, it doesn't appear so from the data sheet / AT command list.

  Also the HC-05, can initiate connection if I'm understanding documentation right, and return available devices in the area?

Yes, and it can get the signal strengths.  You should be able to get an HC-05 module on a breakout board from Ebay for less than $10 delivered.  There's also a method to update the HC-06 firmware to be an HC-05 but it's probably easier for you to buy one.


How do I control arduino uno multiplexed digital pin (using HC74595) Edit:

I moved the whole initial post to avoid misunderstanding and confusing everyone, sorry

after all the reading i came up with this:

this is my code for ultrasonic sensor that going into digital pins in my arduino:

int trigPin1=2;
int echoPin1=3;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
}

void loop() {
  long duration1, distance1;
  digitalWrite(trigPin1, LOW);  // Added this line
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin1, HIGH);
  delayMicroseconds(15); // Added this line
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = duration1/58;

  Serial.print (distance1);
  Serial.print (",");
  delay(100);
}

and this is the idea i wrote to set the "extra digital outputs" on the 595 chip:

int DS_pin = 8;
int STCP_pin = 9;
int SHCP_pin = 10;

void setup()
{ // put your setup code here, to run once:
  pinMode(DS_pin, OUTPUT);
  pinMode(STCP_pin, OUTPUT);
  pinMode(SHCP_pin, OUTPUT);
  writereg();
}

bool registers[8];

void writereg()
{
  digitalWrite(SHCP_pin, LOW);

  for (int i = 0; i<=7; i++)
  {
    digitalWrite(STCP_pin, LOW);
    digitalWrite(DS_pin,registers[1]);
    digitalWrite(STCP_pin, HIGH);
  }
    digitalWrite(SHCP_pin, HIGH);
}

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

}

now if you guys have a little time to check it, and tell me what should i wrote so the ultrasonic sensor will be working with the 595 chip's outputs?

Let say im going to put the Trigger pin into Q0 and Echo pin into Q1

thanks in advance

It is good that you are thinking of abstraction in order to simplify programming.  Simplifying programming by using familiar names makes it easier to understand the code.

In your example:

int triggerPin=2
pinMode(triggerPin, OUTPUT)

..you are abstracting the actual pin used to trigger the ultrasound by calling it by a familiar name "triggerPin".  You could have just as easily wrote the same code as:

pinMode(2, OUTPUT)

Now you are asking how to abstract the pins when connecting the Arduino to the 74HC595.  The truth is, you don't have to.  But to make it easier to write & read the code you can use what ever names make sense to you.  In this example of connecting an Arduino to a 74HC595 there are 3 Arduino pins connected to the 74HC595.  They called them "dataPin", "latchPin" and "clockPin".  If these make sense to you use these names.

  Add: can i address the output like this?

 #define LED_PIN     Q1

No, nothing knows what "Q1" is.  Remember, you are adding this hardware to the Arduino.  So nothing, not the compiler nor a library, knows about the hardware you added let alone a pin called Q1 on the added hardware.

First you need to understand how to set Q1 through Q8.  Refer to the 74HC595 Arduino tutorial linked to above.  Inspect the example programs.  Once you understand how to set / un-set Q1 through Q8, you can decide if you what to simply shift out a number or if you want to use abstraction giving names to the shift register output pins.

If I were only writing patterns, for example lighting up 8 LEDs, I would stick to numbers. However, if I were controlling different things, for example a light, a motor & a buzzer, I would assign each a unique name and build my program around the names.


Why is Arduino STINO upload function not working? I'm using sublime text for editing and modifying my arduino libraries. Sublime text is pretty pretty, useful and embed a very powerfull plugin system. Someone created an Arduino plugin for it. The compilation function works but the upload doesn't.

I'm trying to upload on an arduino leonardo using Windows 7 x64.

Did anyone tried to fix this problem ?

I finally found it: Problem was solved after commenting those three lines in */Arduino-like IDE/app/uploader.py:

if force_to_reset:
    pre_serial_port = serial_port
    wait_for_upload_port = self.args.get('upload.wait_for_upload_port', 'true') == 'true'
    serial_port = resetSerial(pre_serial_port, self.output_console, wait_for_upload_port)
    # if self.args['cmd'] != 'avrdude':
    #   if serial_port.startswith('/dev/'):
    #       serial_port = serial_port[5:]
    if serial_port:
        for cur_command in self.command_list:
            command_text = cur_command.getCommand()
            command_text = command_text.replace(pre_serial_port, serial_port)
            cur_command.setCommand(command_text)


Timer2 Compare Interrupt not working as expected To get this out of the way first: I have already looked at "Timer2 does not work as it should" and "Timer2 “Clear OC2B on Compare Match” not working as expected in CTC mode" but have not found the answers there very useful.

Now on to my problem:

I'm trying to use the Timer2 in CTC mode to have an interrupt every 500us. For this, I have the following code:

#include "TimerTwo.h"

TimerTwo Timer2;

ISR(TIMER2_COMPA_vect) { //ISR on Compare Match A
  Timer2.isrCallback();
}

void TimerTwo::initialize() {
  cli();
  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 2khz increments
  OCR2A = 124;// = (16*10^6) / (2000*64) - 1 (must be <256)

  // turn on CTC mode
  TCCR2A |= _BV(WGM21);

  // Set CS22 bit for 64 prescaler
  TCCR2B |=  _BV(CS22);

  // enable timer compare interrupt
  TIMSK2 |= _BV(OCIE2A);
  sei();
}

void TimerTwo::attachInterrupt(void (*isr)()) {
  TIMSK2 |= _BV(OCIE2A);
  isrCallback = isr;
}

void TimerTwo::detachInterrupt() {
  TIMSK2 &= ~_BV(OCIE2A);
  isrCallback = nullptr;
}

and

#ifndef TIMERTWO_H
#define TIMERTWO_H

#include <Arduino.h>

class TimerTwo
{
  public: //methods
    void initialize();
    void attachInterrupt(void (*isr)());
    void detachInterrupt();
    void (*isrCallback)();
};

extern TimerTwo Timer2;

#endif

It was inspired by the TimerOne library.

However, when I measure the period at the output pin (which I have attached inside some other code) I only get a period of 1ms. Even if I set ORC2A to 63, this fact doesn't change.

I have the constructor of this called inside my setup() so the registers should not be overwritten by the wiring.c.

I have also looked at the datasheet of the ATmega328p and checked that all registers are set correctly.

Thanks in advance for your help. If you need any further information, let me know.

So you're right that CTC is acting weird. I've noticed this few years ago too on different board, but I've always suspected asychronous mode (I've added 32k RTC Xtal on Arduino Mega).

However Fast PWM mode with OCR2A as a TOP value seems to be working:

class TimerTwo
{
  public: //methods
    void initialize();
    void attachInterrupt(void (*isr)());
    void detachInterrupt();
    void (*isrCallback)() = nullptr;
};

TimerTwo Timer2;

ISR(TIMER2_COMPA_vect) { //ISR on Compare Match A
  Timer2.isrCallback();
}

void TimerTwo::initialize() {
  cli();

  OCR2A = 124;                        // = (16*10^6) / (2000*64) - 1 (must be <256)
  TCCR2A = _BV(WGM21) | _BV(WGM20);   // turn on fast PWM mode with top in OCR2A
  TCCR2B = _BV(WGM22) | _BV(CS22);    // Set CS22 bit for 64 prescaler
  TCNT2  = 0;                         // initialize counter value to 0

  sei();
}

void TimerTwo::attachInterrupt(void (*isr)()) {
  isrCallback = isr;
  TIMSK2 |= _BV(OCIE2A);
}

void TimerTwo::detachInterrupt() {
  TIMSK2 &= ~_BV(OCIE2A);
  isrCallback = nullptr;
}

volatile uint32_t counter = 0;
void isrHandler() {
  ++counter;
}

void setup() {
  Serial.begin(115200);
  Timer2.initialize();
  Timer2.attachInterrupt(&isrHandler);
}

void loop() {
    static uint32_t counter_old = 0;
    Serial.println(counter - counter_old);
    counter_old = counter;
    delay(500);
}

EDIT: Ok, so after some digging on this issue I've found that setting CTC mode might cause OCR2A corruption (I guess?) . It seems to be working if you reorder the settings to:

  TCCR2B = 0;          // stop the timer and reset WGM22
  TCCR2A = _BV(WGM21); // turn on CTC mode with top in OCR2A
  OCR2A  = 124;        // = (16*10^6) / (2000*64) - 1 (must be <256)
  TCNT2  = 0;          //initialize counter value to 0
  TCCR2B = _BV(CS22);  // Set CS22 bit for 64 prescaler (for starting the timer)


Why can't I connect more than one Arduino Uno + Ethernet Shield to my network? I'm using 3 Arduino Uno boards with Ethernet shields. Each is connected to my home Internet switch with an Ethernet cable.  I assigned a different local IP address to each Arduino and gave each board a different MAC Address.

Each Uno is collecting temperature/humidity for a bedroom in my house.  The data is sent to a MySQL Database using PHP/HTML.

They work fine for a while (5 minutes) and then they conflict each other.  If I use one Arduino at a time it works fine, but I can't get them to work together.

Any idea how to solve the problem?

It would be most helpful to see the code you're using and to know more about the configuration of your network and the symptoms of the conflict – for example where is the web site running?

Some things to try:

Simplify your network. Eliminate everything but the Arduinos and the web server. See if that changes anything.
Run the command arp -a (assuming you've got a machine running something UNIXish). It will show you the MAC and IP addresses of hosts on your network. Look to see if the Arudinos are still there and if there are any devices that conflict with them.
Try to ping the Arudinos. Do they respond?
Use WireShark or tcpdump to monitor traffic on the network. Look for traffic to or from the Arudinos (by IP addresses and by MAC addresses).
Add some debug code to the Arduino sketch so that you can watch what they are doing (send it out the serial monitor). See if what goes on the wire matches what you expect (monitoring with tcpdump).


How to send Multiple decoded IR signals in one script My final goal is to use my Arduino microcontroller as an "automatic remote". For now I would like to know how to send decoded NEC protocols one after another in a script.

I am using the Nano V 3.0 with a IR led I salvaged from an old remote. I used a VS838 and a 338R IR receiving module to decode the signals, both work 100%

I know how to send one protocol in a loop.

e.g

#include <IRremote.h>

IRsend irsend;

void setup()
{
}

void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(0x10676897, 32);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

I also know how to send the same protocol repetitively.

(Although it won't work in the loop I reckon it'll work in the final script)

e.g

#include <IRremote.h>

IRsend irsend;

void setup()
{
}

void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(0xFFFFFFFF, 32);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

However, I would like to include 106722DD, 10676897 ,10678877 and send them in one single C++ Script.

I was thinking something like calling each script through a loop might suffice but I have no idea how to do it in C++

Any help will be appreciated.

I'm not 100% certain what you are asking, so sorry if there is superfluous info in here.

Given that:

void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(0x10676897, 32);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

Sends a single command twice as one burst I think what you want to do is this:

void loop() {
    for (int i = 0; i < 2; i++) {
        irsend.sendNEC(106722DD, 32);
        delay(40);
        irsend.sendNEC(10676897, 32);
        delay(40);
        irsend.sendNEC(10678877, 32);
        delay(40);
    }
    delay(5000); //5 second delay between each signal burst
}

If that works it could be generalised into:

// New function to send 'items' codes which are held in the array 'data'
void sendMulti (const uint8_t& items, const uint32_t* data)
{
    for (int i = 0; i < 2; i++)
    {
        for (uint8_t itemIndex = 0; itemIndex < items; ++itemIndex)
        {
            irsend.sendNEC(data[itemIndex], 32);
            delay(40);
        }
    }
    delay(5000); //5 second delay between each signal burst
}

void loop () {
    static const uint8_t MaxItems = 3;
    uint32_t  data[MaxItems] = {106722DD, 10676897, 10678877};

    sendMulti(MaxItems, data);
}

Then you could move onto reading the codes from serial or a network, etc.


Adafruit feather M0 wifi firmware update I just noticed that the firmware on the m0 wifi might need updating but says not to use the provided updater, how do you update the firmware so ?

Thanks

USE AT YOUR OWN RISK
Here's what I did... (maybe some steps not necessary, but this worked for me)

1) First run the "CheckWifi101FirmwareVersion" found in the Arduino WiFi 101 library.

NOTE: You need to add in the WiFi.setPins(8,7,4,2); after void setup() {
If it's backlevel (before 19.4.4), then

2) Download the Adafruit WiFi101 Updater on github (
   https://github.com/adafruit/WiFi101-FirmwareUpdater/archive/master.zip
   )

3) Install the "FirmwareUpdater" from the Arduino WiFi 101 Library

Add in the recommended changes (even if it's the defaults)

#define WINC_CS 8
#define WINC_IRQ 7
#define WINC_RST 4
#define WINC_EN 2

and the usual WiFi.setPins(8,7,4,2) after void setup() {

4) Copy the firmware you wish to flash to same directory as "winc1500-uploader.exe"

5) Run the command:

  winc1500-uploader.exe --port [YourComPort] --firmware [YourFirmwareFileName].bin

So for example I did:

  winc1500-uploader.exe --port COM9 --firmware m2m_aio_2b0.bin


L298N vs Motor Shield R3 I'm new to Arduino and need some clarification on motor drivers.

I was wondering if I can use a L298N instead of the Motor Shield R3, I hope not to be comapring apples to oranges, the doc of the Motor Shield R3 say "The Arduino Motor Shield is based on the L298"  and more or less I see similar projects (Robot cars) using both but as mention I don't if I can use one or the other as "replacement".

(L298N)

(Motor Shield R3):

Yes.  The shield is easier to user, but the breakout board you've shown uses the same chip.  I'd suspect that the breakout board, which has a much bigger heat sink, can handle larger motors, though.  You'll need to put wires from PWM and digital pins to the breakout board you're showing, but it's not super challenging to use those.  I've used extremely similar boards in the past, as well as shields, and both work great.  How big are your motors?  If they're WAY too big (the breakout board can only handle 2 amps IIRC) then you'll need something else anyway.


Uno - error during uploading with library I'm writing the code in VS Code on IO Platform. Yesterday i finished my code and uploaded it to the Arduino Uno. It works fine. Next day i launched the VS Code and i changed the code a bit, then i uploaded it and i got the error.

Error:

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
(.text+0x0): multiple definition of `__vector_7'
NewPing.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\uno\firmware.elf] Error 1

I am using the libary NewPing.h. The code should does this: If is distance more than 20cm, the the buzz makes the sound and turns on the red led. If distance is less than 20cm, the blue led turns on

The code:

#include <Arduino.h>  //It has to be there, because the arduino ide in VS Code will not work.

#include <NewPing.h>

#define echo_pin 3
#define trig_pin 4
#define max_range 450

#define red_led_pin 7
#define blue_led_pin 9
#define buzz_pin 10

int distance = 0;

NewPing sonar(trig_pin, echo_pin, max_range);

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

  pinMode(buzz_pin, OUTPUT);
}

void loop() {

  distance = sonar.ping_cm();
  delay(50);

  if (distance > 0) {
          distance = 0;

    for (int i=0; i<5; i++) {
      distance += sonar.ping_cm();
      delay(50);
    }
    distance /= 4;

    Serial.print("Distance: ");
    Serial.print(distance);
    Serial.println("cm");

    if (distance > 20) {

      digitalWrite(blue_led_pin, LOW);
      digitalWrite(red_led_pin, HIGH);
      tone(buzz_pin, 1500);
      tone(buzz_pin, 800);
    }

    else {

      digitalWrite(red_led_pin, LOW);
      digitalWrite(blue_led_pin, HIGH);
    }
  }
}

I don't undersand, what has changed. I tried to import again the libary https://www.arduino.cc/en/guide/libraries by importing the *.zip file, also installing in IDE.

You have a conflict of interrupts. Both the internal tone() command and the NewPing.h use Timer 2 by default, which makes them mutually exclusive.

However you can change NewPing to not use a timer by editing the src/NewPing.h file and setting TIMER_ENABLED to be false:

    #define TIMER_ENABLED true      // Set to "false" to disable the timer ISR (if getting "__vector_7" compile errors set this to false). Default=true