NRF24L01+ (TMRH20 library): Receiver gets blank data I am working on sample Arduino project for communication over NRF24L01+ (TMRH20 library), everything is working fine with my example except one issue my Receiver gets message but that message is blank. Now i am not sure how do i debug as per serial monitor data is getting transmitted, as per receiver serial monitor it receives data but its blank.

Transmitter code -

// SimpleTx - the master or the transmitter

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

const byte slaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

char dataToSend[12] = "Msg AKSHAY";
//int dataToSend = 1;
char txNum = '0';

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000; // send once per second

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleTx Starting");

    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.setRetries(3,5); // delay, count
    radio.openWritingPipe(slaveAddress);
}

//====================

void loop() {
    currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {
        send();
        prevMillis = millis();
    }
}

//====================

void send() {

    bool rslt;
    rslt = radio.write( &dataToSend, sizeof(dataToSend) );
        // Always use sizeof() as it gives the size as the number of bytes.
        // For example if dataToSend was an int sizeof() would correctly return 2

    Serial.print("Data Sent ");
    Serial.print(dataToSend);
    if (rslt) {
        Serial.println("  Acknowledge received");
        updateMessage();
    }
    else {
        Serial.println("  Tx failed");
    }
}

//================

void updateMessage() {
        // so you can see that new data is being sent
    txNum += 1;
    if (txNum > '9') {
        txNum = '0';
    }
    dataToSend[10] = txNum;
}

Receiver code -

// SimpleRx - the slave or the receiver

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

const byte thisSlaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN);

char dataReceived[10]; // this must match dataToSend in the TX
bool newData = false;

//===========

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleRx Starting");
    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.openReadingPipe(1, thisSlaveAddress);
    radio.startListening();
}

//=============

void loop() {
    getData();
    showData();
}

//==============

void getData() {
  if ( radio.available() ) {

       radio.read( &dataReceived, sizeof(dataReceived) );
      Serial.println(dataReceived);
       newData = true;
   } else {
       Serial.println("No radio available");
   }
   delay(100);
}

void showData() {
    if (newData == true) {
        Serial.print("Data received ");
        Serial.println(dataReceived);
        newData = false;
    }
}

Below is the output TX1 (Transmitter ) and RX1 is Receiver. You can see that Transmitter even gets acknowledgment also..

Both of my devices are arduino nano and below is wiring diagram between arduino and nrf24l01.

I also saw few post where people suggested using 100uf capacitor in NRF24L01 (GND & VCC), this helped me with accuracy in connection but data is still missing.

A couple of clarifications first

At the time instant 22:38, the receiver isn't detecting any available radio devices but at the transmitter side, an acknowledge is received. How is that possible? How is your tx getting an ack without the rx getting connected.
I have not seen slave adresses being set as - const byte slaveAddress[5] = {'R','x','A','A','A'}; For the record, NRF24L01 adresses are 5 bytes long by default and not 1 byte long as you have defined. While defining the pipe addresses, the first 4 bytes of the adresses should be same among all the pipe addresses. Only the last byte should be unique. Pipe addresses can be 0xF0F0F0F0A1, 0XF0F0F0F0B1, 0XF0F0F0F0C1, 0XF0F0F0F0D1, 0XF0F0F0F0E1 Try setting the pipe addresses as uint_64t address[5] = {0xF0F0F0F0A1LL, 0XF0F0F0F0B1LL, 0XF0F0F0F0C1LL, 0XF0F0F0F0D1LL, 0XF0F0F0F0E1LL};Do the same declaration at the receiver end too. And btw, you can specify any byte you want in the last byte of the address. Here I have defined the last bytes as A1, B1, C1, D1, E1.
To make sure that communication is successful, set some custom ack byte and compare it with the received ack. If both match, you can be sure that the rx did get the data. Sometimes, the NRF24L01 can pickup garbage values from stray signals present around and it can consider it as data sent by the receiver. So to avoid false triggering, its better to make a fool-proof ACK mechanism.


RS485 Multimaster Communication with collision avoidance I'd like to know if there is an easy way to implement communication between multiple arduinos that avoids collisions using the RS485 module.

My setup would have multiple masters that send messages to only one slave that performs a task upon been given the message.

I've tried researching some libraries for this, but they normally don't fulfil the multimaster requisite, nevertheless I found this library which apparently does implement what I need, but I haven't been able to understand how it works.

My current options are either finding an easier library that is capable of doing what I need, learning how to make the linked library work (which I have already tried) or building my own serial communication protocol that implements collision avoidance and a multiple master configuration.

What path should I follow? Can you give me any recommendation for any of the paths I'm suggesting? Is there a better way of implementing this type of communication?

There is a ready out the box solution documented in https://github.com/MichaelJonker/HardwareSerialRS485/wiki (This wiki describes the library you referred to).

The problem is quite complex: collision avoidance, collision detection and message retrial, message priority and message filtering. But the library solves it all. The software even provides a solution to interface a host (PC or Android) to the RS485, providing the same features.

In ‘understanding the library’ there are two aspects: how it works, and how to make it work.

The library itself is non-trivial (because the problem is also non-trivial), so to understand how it works is also non-trivial (Majenko, in his answer, gave a nice functional description of some of the features that are implemented by the library. The actual implementation has additional complications due to the direct interaction with the USART at interrupt level.). I guess you do not want to know (in first instance) how it works in such details.

However, the author (me) went to quite some detail to document how to make it work. But I reckon that documentation may be difficult to follow if the documentation does not match the expectations of the reader.

So I would be very interested to improve the documentation and to match the expectations of new users. However, here I need your help (or anyone interested) in pointing me out what and where I can improve.

The preferred way to contact me on these matters is by creating an issue on my Github project page:

https://github.com/MichaelJonker/HardwareSerialRS485/issues

BTW one of the issues addresses the same topic.

I guess that you need to create Github account in order to submit issues. Alternatively, you can contact me through this site (However, I might be less reactive through this channel).

Best regards

MichaelJonker

I thinks the easiest way for software is not use any software do this at all, using a hardware controller chip/module instead which dedicated to support multi-master and arbitration for RS485 (the same way as CAN bus).

There is a protocol, named CDBUS, witch has stand-alone controller to do the work for you, which is very simple, I can even transfer video stream through it, details:

https://github.com/dukelec/cdbus_doc (Introduction)
https://github.com/dukelec/cdbus_ip (Protocol details & FPGA IP core)

You can also achieve this protocol by software only, if you don't care the speed or CPU usage.

Update: connect the CDCTL-Bx controller to an Arduino:


How to avoid that my arduino clicks eternally? I have accidentally implemented a program that imitates the click of the mouse.

The problem is that now I can´t delete the program because each time that I connect the USB, the computer starts clicking everything and it is not possible to upload a new program.

Can I solve this problem?

Hold the RESET button as you plug the Arduino in and keep it pressed all the time it's plugged into your computer.  Load Blink.ino into the IDE and compile it.  Press the UPLOAD button in the IDE and move the mouse to somewhere "safe".  Release the RESET button.

Do those last three steps in rapid succession and you should be fine.

A less obvious option is to just buy a new one. They are so cheap, you will never make up the time spent to fix the problem. Best keep some in stock.

But Majenko's answer is still cool and sophisticated, so trying to ask on SE doesn't hurt.


Can't detect I2C displays with Arduino Nano All cables tested and work:

SCL - A5
SDA - A4
VCC - 5V
GND - GND

I'm using an Arduino Nano board and an I2C display - I've tried everything to get it to work and I'm now convinced it's a hardware fault. Using the Arduino I2C address scanner, it is unable to find a device, even though it is wired correctly (I've checked multiple times).

This is the code I used, i2c_scanner, and this output:

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

Scanning...
No I2C devices found

... is all I get.

Any suggestions, or is my board output fried?

You seem to have two issues here:

As already pointed out, you have the white wire connected to the wrong pin on the Arduino
Also, you need to solder the headers on the Arduino. There is no solder on the pins, which means that there is no connection. You need to solder those headers on; it looks like you just set the Arduino on top, which won't work with headers

That white wire is connected to VIN instead of GND on your Arduino board. You need to move the wire over one slot in the breadboard.


External Flash Memory File System I'm building a weather data collector and I want to be able to dump that weather data somewhere. I've considered the options, and since I'm going to be storing a fairly small amount of data (in the megabyte range) I don't want to use SD cards (also SD cards are expensive). I've heard of use of NAND flash memory chips (like the W25Q32), and I was hoping that I could possibly interact with them in a simple way (since most ways require writing to each individual address). Is there possibly a way to build a file system within one of these small flash memory chips and interact with them as simply as interacting with an SD card?

TLDR: I want to interact with a flash memory chip easily to store basic ASCII data

I don't think you need a file system: that is usually needed when you want to manage many files. Your weather data log sounds like a single file.

What you seem to need is to access EEPROM as a stream, exactly like you would for an open file. There are stream wrappers around some EEPROM libraries, e.g. this one for ESP. I suggest you check it out and see if you can adapt it to the EEPROM library you use.

There is a way to do this. Using a $2 adaptor from eBay, you can hook it up to a micro sd card. An sad card for $4 can store 128mb of data, which is plenty for you.

Arduino Storage Tutorial with weather

128mb Micro Sd card


Watchdog timer stuck in restart loop? (green led flashing) I am trying to set up a way to reboot arduino on command. The code below should do that but it seems like my arduino just get's stuck in some sort of a loop where I cant upload or get any serial output. The green led (pin 13) flashes very fast. The only way to stop this is to cut power to the device, even reset button does not work. This happens only when "R" is received via serial or if wdt_reset() function is commented out.

#include <avr/io.h>
#include <avr/wdt.h>

int ledPin = 3;

void setup()
{
  MCUSR=0;
  wdt_disable();
  Serial.begin(57600);
  Serial.println("BOOT!");
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  delay(500);
}

void loop(){
  if (Serial.available() > 0){
    char cmd = Serial.read();
    if (cmd == 'R'){
      Serial.println("R received!");
      wdt_enable(WDTO_1S);
      delay(2000);
      Serial.println("1 SEC.");
    }
  }
  wdt_reset();
  digitalWrite(ledPin, HIGH);
}

What am I doing wrong?

One of the most obvious issues here is that you are enabling the watchdog timer with a delay of 1S and then you are asking the micro controller to sleep for 2S, printing something and then going back into the loop. This, in theory, should be fine(your wdt should trigger a reboot during the 2 second wait) but I've seen it cause issues.

Additionally some bootloaders(notably the Optiboot bootloader on Uno and newer boards) can have issues with watchdog timers causing the wdt to remain enabled after reset even though the setup loop disables it. To start with - try increasing the wdt time to something greater than 2S(you should be able to do WDTO_8S) and see if the issue persists.

EDIT - The OP is using an Arduino Pro Mini clone. The included bootloader on the Arduino Pro Mini does not support system restarts by the WDT. Essentially, on a device with a bootloader that does not support WDT restarts, the board will restart but the timer / reset will not causing the board to continuously reset on reboot. There are alternative bootloaders for Arduino boards that may resolve this issue. Another solution is to use a different method to reboot the board.

You can restart the Arduino with this command:

asm volatile ("  jmp 0");


Controlling 2 DC Motors with L293D and 6 V battery pack? Sorry if my question looks newbie, but I'm just starting to delve into robotics and electronics, and my first project was building a small arduino collision-avoidance robot with a ultrasonic range finder, one servo and two dc motors. Right now I'm using a 6V battery pack to power both DC motors, another 6V just for the servo, and a 9V battery for the arduino.
But I'm in doubt if the power supply for the DC motors is enough. I'm using an L293D IC to control both motors, but the robot can barely move under load (and the total weight of the robot is not that much. I already reduced all the weight I could). So, how much power, typically, I should supply for the L293D to control those motors?

The L293D can handle two motors at a time and as per the data sheet the maximum voltage that you can give to the motor as a supply (on pin 8) is 36 volts.


WS2812 - First are white and then they turn red/yellow/orange near the end I'm trying to power about 150 WS2812 LEDs from my ESP8266 NodeMCU board (running NeoPixel Arduino code). The first few LEDs are white, but about half way down, the LEDs turn yellow, then they turn orange, and at the end they're basically red.

Could this be caused because of the power draw? The strip itself is currently drawing about 900 mAh, and I am powering the ESP8266 with a 1.5A 5v supply. The LEDs are running off 3.3v directly from the ESP8266.

Also, after like 2 minutes, the LEDs turn off completely. The board never disconnects from my WiFi. They just turn off. I can turn them on again right after.

See Powering NeoPixels.

  Each individual NeoPixel draws up to 60 milliamps at maximum brightness white (red + green + blue).

  ...

  To estimate power supply needs, multiply the number of pixels by 20, then divide the result by 1,000 for the “rule of thumb” power supply rating in Amps. Or use 60 (instead of 20) if you want to guarantee an absolute margin of safety for all situations. For example:

So you need at least 3 amps or even 9 amps for absolute safety.

  The LEDs are running off 3.3v directly from the ESP8266.

I doubt it is designed for that. The internal traces won't be designed to handle maybe 5 amps.

To avoid colour degradation through the strip you could use multiple power supplies (to avoid the voltage dropping due to the resistance over the strip). You would connect the grounds (and connect the data wires of course) but break the +5V line in the middle and insert another power supply.

However one (fairly powerful) supply directly connected to the NeoPixels might do the trick. That is, not through the ESP8266.

Also see NeoPixels Revealed: How to (not need to) generate precisely timed signals.

On that page:

  Q: In the video, when the entire strip is lit full white, it looks like the far end has a orange tint to it. Is this an artifact of the camera or something?

  A: Wow, you are very perceptive! Yes, the string did start to get orange at the end at full power. I actually didn’t just run out of apartment when making this long string – I also ran out of power supplies. I had 3 supplies, each 10amps. This is almost enough, but not when every single LED is full brightness white. When that happens, the voltage at the very end of the strip starts to get too low and the LEDs start looking pallid. Why orange? Because blue LEDs need the highest voltage drop to light so when the voltage sags they are the first to go followed by the greens – leaving yellows to oranges and ultimately red.

(He had 1000 pixels). So this guy used 3 separate 10 amp power supplies!

Just incase anyone else has the problem,

You need to connect the strip as a ring by returning the tail end to the psu,

Electricity basics !!!!


EEPROM put and get not working on ESP8266 (NodeMCU) The Arduino documentation provides two examples to store data in the EEPROM.

https://www.arduino.cc/en/Reference/EEPROMPut stores data in the EEPROM and the EEPROMGet example reads the data back and writes it out.

These examples work fine on my Arduino Uno, but on my ESP8266 (NodeMCU) the EEPROMGet example code is unable to retrieve the data EEPROMPut should have stored previously. Instead it's just returning some random bits and bytes.

Any ideas? I haven't found anything about known incompatibilities related to the ESP8266 boards...

The ESP8266 doesn't have any EEPROM. Instead it emulates it using Flash.

In order not to wear out your flash you have to "commit" changes to the flash once they have been queued for writing - otherwise they will be lost.

Instead of using the Arduino examples you should be using the ESP8266 specific examples included with the ESP8266 EEPROM emulation library (but also here).

EEPROM.write(ss, rr);
EEPROM.write(ssc , rrc);
**EEPROM.commit();**

must be..


help compiling code for flora project I'm working on the Adafruit Firewalker shoes.

I can't make my code compile to test my flora project.

This is my error message:

Arduino: 1.6.7 (Windows 10), Board: "Adafruit Flora"

C:\Users\Devi\Documents\Arduino\test_2\test_2.ino\test_2.ino.ino:1:29: fatal error: Adafruit_NeoPixel: No such file or directory

 #include <Adafruit_NeoPixel>

                             ^

compilation terminated.

exit status 1
Error compiling.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

https://learn.adafruit.com/firewalker-led-sneakers/test-circuit

    #include <Adafruit_NeoPixel.h>

const int analogInPin = A9;  // Analog input pin that the potentiometer is attached to
Adafruit_NeoPixel strip = Adafruit_NeoPixel(10, 6, NEO_GRB + NEO_KHZ800);
int sensorValue = 0;        // value read from the pot

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(9600);
 pinMode(9, INPUT_PULLUP);
   strip.begin();
  strip.show(); // Initialize all pixels to 'off'

}

void loop() {
  // read the analog in value:
  sensorValue = analogRead(analogInPin);
  // print the results to the serial monitor:
  Serial.print("sensor = " );
  Serial.println(sensorValue);

if (sensorValue < 100){
  Serial.println("leds triggered");
colorWipe(strip.Color(255, 0, 0), 25);
colorWipe(strip.Color(0, 0, 0), 25);
}

}

void colorWipe(uint32_t c, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(wait);
  }
}

I had the same problem, you just have to download the Adafruit Neo Pixel library:

i think issue is in your this path
C:\Users\Devi\Documents\Arduino\test_2\test_2.ino\test_2.ino.ino:1:29: fatal error: Adafruit_NeoPixel:

make new arduino file and copy the same code and save it on other folder on desktop or other drive then compile it

Compilation
I compiled you same code and my stored path of .ino file is
C:\Users\Muhammad Hassaan\Documents\Arduino\sketch_mar04a


How many clients can connect to an ESP32? I am using an ESP32 as my master and 10 ESP8266-07s are connected to the master that is in AP mode.

But I need at least 12 clients.
Please help me to increase the number of clients the ESP32 can handle in AP mode.

I have read this article but it did not help me
ESP32 AP max connections: 4 or 10?

The SDK API documentation from Espressif directly notes:

uint8_t max_connection
Max number of stations allowed to connect in, default 4, max 4

EDIT
However, another area of the API documentation (The API Guide) notes:

max_connection
Currently, ESP32 Wi-Fi supports up to 10 Wi-Fi connections. If
max_connection > 10, soft-AP defaults the value to 10.

If you use softAP, you can set the max number of connections to 16 I believe.

WiFi.softAP(const char* ssid, const char* passphrase, int channel, int ssid_hidden, int max_connection);


Marlin Firmware troubles:  error I am trying to upload the Marlin Firmware to my 3D printer's Arduino Mega 2560 and I am experiencing a problem. It keeps saying:

qr_solve.cpp:7:18: fatal error: time.h: No such file or directory
 #include <time.h>
                  ^
compilation terminated.
Error compiling.

Please help as I'm lost as how to fix it, because I try to scroll up to see what is highlighted in red and I can't find anything.

From Gerben's link to the googlegroups's thread, Delta robot 3D printers › compiling jcrocholl's Marlin (Ubuntu), as Francis Mallet points out, at the bottom of the thread, it is necessary to change <time.h> to "Time.h":

  I copied the content of the Time library right in the Marlin folder, then changed line 7 of qr_solve.cpp from #include  to #include "Time.h"

  The code compiled and everything seems to be working ok.

So, to iterate, the line in qr_solve.cpp:

#include <time.h>

becomes

#include "Time.h"

Now, Marlin.ino should compile as expected.

Note that the latest version of Marlin, from github.com/MarlinFirmware/Marlin no longer suffers from this issue, but older versions of the software, such as github.com/gpfwestie/kossel_2020_sintron will do, due to line 7, in qr_solve.cpp.

As Gerben points out, the solution is to change  to "Time.h".


Debugging a RadioShack Arduino motor/sensor shield I bought a cheap "Make" kit at RadioShack, which includes some sort of proprietary Arduino Uno compatible motor/sensor shield. Naturally, the documentation is pretty bad. The documentation and Arduino code for the kit is here:

https://github.com/RadioShackCorp/2770168-MakeItRobotics-Starter-Kit

It includes a circuit schematic (2770168-CorePCB_schematic.pdf), but I'm still having trouble mapping the pins to the Arduino's pins. Can anyone help me make sense of this?

What I've made out so far is the shield's screw terminals appear to be connected to quadruple h-bridges. However, there are several other pin headers that I can't quite make out. I think it also directly exposes 4 of the Uno's ADC pins and 4 DIO pins. There are four pins for dual IR line sensors, but there's a lot of circuitry between these and any Arduino pins. Almost everything feeds into a DC6688F2SCN chip, but I can't find a datasheet anywhere, so I have no idea what it does.

The manual says jumpers on J16 need to be removed in order to connect to the Uno over USB, so it looks like I can't use the shield with the board and debug via USB at the same time. Is this board worth investigating or should I trash it?

There is a bit of info on the DC6688F2SCN here: Chip Selection Guide, but Chris is 100%. Without the firmware, all you can do is look at the source code for the Arduino side.

If you look closely at the top of the board, you can see that one side of J16 goes to pins 2 & 3 and the other to 0 & 1. On the schematic, there are some other components hooked in there as well. The serial is definitely going using 0 & 1. I'm not sure why they have them wired to 2 & 3. It's probably a good idea not to put anything on any of these four pins.

That's pretty good though. Compare it to the SainSmart L293D shield, which is significantly cheaper but eats up eight digital pins when driving four motors. Also, the L293Ds can only put out 600 mA per channel while the Bs can do a full Amp.

The documentation isn't very good and the supporting code also has some issues; but, overall, this is a pretty decent package. It comes with the erector set pieces as well. You also get three IR sensor channels.

A google search for DC6688F2SC  returns spec sheet under Dragonchip (here). It's actually a rather nice chip when you look up the specs on it.


Making two points on a tm1637 display blink [ Solved ] Hello! In my project, using a display controlled by a TM1637, I want to make the two points on the middle of the screen blink (as every clock does).
The following example, provided by the library I'm using, makes the two points blink as I want (tm1637.point(POINT_ON/POINT_OFF); is what enables/disbales the point):
#include <TimerOne.h>
#include "TM1637.h"
#define ON 1
#define OFF 0

int8_t TimeDisp[] = {0x00,0x00,0x00,0x00};
unsigned char ClockPoint = 1;
unsigned char Update;
unsigned char halfsecond = 0;
unsigned char second;
unsigned char minute = 0;
unsigned char hour = 12;

#define CLK 2//pins definitions for TM1637 and can be changed to other ports
#define DIO 3
TM1637 tm1637(CLK,DIO);

void setup()
{
  tm1637.set();
  tm1637.init();
  Timer1.initialize(500000);//timing for 500ms
  Timer1.attachInterrupt(TimingISR);//declare the interrupt serve routine:TimingISR
}
void loop()
{
  if(Update == ON)
  {
    TimeUpdate();
    tm1637.display(TimeDisp);
  }

}
void TimingISR()
{
  halfsecond ++;
  Update = ON;
  if(halfsecond == 2){
    second ++;
    if(second == 60)
    {
      minute ++;
      if(minute == 60)
      {
        hour ++;
        if(hour == 24)hour = 0;
        minute = 0;
      }
      second = 0;
    }
    halfsecond = 0;
  }
 // Serial.println(second);
  ClockPoint = (~ClockPoint) & 0x01;
}
void TimeUpdate(void)
{
  if(ClockPoint)tm1637.point(POINT_ON);
  else tm1637.point(POINT_OFF);
  TimeDisp[0] = hour / 10;
  TimeDisp[1] = hour % 10;
  TimeDisp[2] = minute / 10;
  TimeDisp[3] = minute % 10;
  Update = OFF;
}

I tried to do it as it was the famous "blink", but nothing works.
Here's what I have done:
#include "TM1637.h" // Library for the 4-Digit Display
#include "RTClib.h" // Library for the RTC
#include <SoftwareSerial.h>

#define CLK 6
#define DIO 7

TM1637 tm1637(CLK,DIO);
RTC_DS1307 RTC;

const int fotoRes = 2;

SoftwareSerial mySerial(10, 11);

void setup()
{
  pinMode(fotoRes, INPUT);

  RTC.begin();
  RTC.adjust(DateTime(__DATE__, __TIME__));

  tm1637.init();
}
void loop()
{
  DateTime now = RTC.now();

  tm1637.display(0,now.hour()/10);
  tm1637.display(1,now.hour()%10);
  tm1637.display(2,now.minute()/10);
  tm1637.display(3,now.minute()%10);

  tm1637.point(POINT_ON); //Like blink example.
  delay(500);
  tm1637.point(POINT_OFF);
  delay(500);
}

EDIT: tm1637.set(0-7) ONLY set the brightnes of the screen. What makes the two pints appear is tm1637.point(POINT_OFF/POINT_ON). I'm asking how can I do to make these two points blink. Thanks.
Arduino UNO R3, DigitalTube library by Grove

Calling the point() method only updates a flag; you see the effect the next time you try to display a number. You can use something like this:

void show_time(DateTime &t){
  tm1637.display(0,t.hour()/10);
  tm1637.display(1,t.hour()%10);
  tm1637.display(2,t.minute()/10);
  tm1637.display(3,t.minute()%10);
}

void loop() {
  DateTime now = RTC.now();

  tm1637.point(POINT_ON);
  show_time(now);  // changes take effect here
  delay(500);
  tm1637.point(POINT_OFF);
  show_time(now);
  delay(500);
}

I haven't used the TM1637 code, but I (think I) understand how it works.

In the original code is the following:

void setup()
{
    tm1637.set();
    tm1637.init();

But in your code you only do the following:

void setup()
{
    ...
    tm1637.init();

Have you tried adding the tm1637.set(); line in?


Sketches won't upload to Uno Today I tried to update the sketch on my Arduino Uno, but was unable to due to this error:

Sketch uses 1,870 bytes (5%) of program storage space. Maximum is 32,256 bytes.
Global variables use 188 bytes (9%) of dynamic memory, leaving 1,860 bytes for local variables. Maximum is 2,048 bytes.
D:\Users\User\Desktop\arduino-1.6.10\hardware\tools\avr/bin/avrdude -CD:\Users\User\Desktop\arduino-1.6.10\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\User\AppData\Local\Temp\build2f7b4a32c3810b2d8e42648954faba05.tmp/nes_controller.ino.hex:i
An error occurred while uploading the sketch

Nothing will upload to the board now. I tried uploading a simple sketch with empty setup() and loop() functions, I've tried different PCs and gotten the same error, I've swapped USB cables, I've double-checked that I'm using the right COM port, I've disconnected every wire from the Arduino pins - nothing has helped.

The old sketch is still running fine on the Uno. It was uploaded a few days ago using the exact same setup I'm trying right now.

The Arduino IDE doesn't even indicate any errors, everything compiles and looks good until "An error occurred while uploading the sketch"

You can set the verbosity level in the Arduino IDE:

File menu
Preferences
Settings tab
"Show verbose output during" => check "upload"
Click OK

Upload again, and note the additional output telling you what is wrong.

It should also point you to this URL, which points out the most occurring issues.

The issue I have most, is that I forget to switch between Micro and Uno board (as I deploy my sketch on both boards).

right click on computer, manage, device manager and disable the usb driver and enable it again.


End stops for stepper motor I need to add some end stops to this stepper motor code. I'm using one axis of a joystick to control a carriage that goes back and forth on a long screw. I have hall switches for both ends, I just want it to stop going in that direction when it triggers the switch.
I didn't write this code but it would work great if I could just add the end stops. If I have the switches connected to pins 2 and 3.
How could I write something like: if pin 2 goes high, stop motor in that direction, and then the same for pin 3 in the opposite direction?
#include <AccelStepper.h> // accelstepper library
AccelStepper stepper(1, 8, 9); // direction Digital 9 (CCW), pulses Digital 8 (CLK)

//Pins
const byte Analog_X_pin = A0; // x-axis readings
const byte enablePin = 7;

//Variables
int Analog_X = 0;             //x-axis value
int Analog_X_AVG = 0;         //x-axis value average
  //----------------------------------------------------------------------------
void setup() {
  Serial.begin(9600);
  //----------------------------------------------------------------------------
  //PINS
  pinMode(Analog_X_pin, INPUT);
  pinMode(enablePin, OUTPUT);
  //----------------------------------------------------------------------------
  InitialValues(); // averaging the values of the 3 analog pins (values from potmeters)
  //----------------------------------------------------------------------------
  // Stepper parameters
  // setting up some default values for maximum speed and maximum acceleration
  stepper.setMaxSpeed(2000);     //SPEED = Steps / second
  stepper.setAcceleration(1000); //ACCELERATION = Steps /(second)^2
  stepper.setSpeed(1000);
  delay(1000);
}

void loop() {
  ReadAnalog();
  stepper.runSpeed(); // step the motor (this will step the motor by 1 step at each loop indefinitely)
}

void ReadAnalog() {
  if (abs(Analog_X-Analog_X_AVG) > 50) {
    digitalWrite(enablePin, HIGH);  // enable the driver
    stepper.setSpeed(5*(Analog_X-Analog_X_AVG));
  } else {
    digitalWrite(enablePin, LOW);   // disable the driver
    stepper.setSpeed(0);
  }
  // Reading the potentiometer in the joystick:
  Analog_X = analogRead(Analog_X_pin);
  // if the value is 25 "value away" from the average (midpoint), we allow the update of the speed
  // This is a sort of a filter for the inaccuracy of the reading
  if (abs(Analog_X-Analog_X_AVG) > 50) {
    stepper.setSpeed(5 * (Analog_X-Analog_X_AVG));
  } else {
    stepper.setSpeed(0);
  }
}

void InitialValues() {
  //Set the values to zero before averaging
  float tempX = 0;
  //----------------------------------------------------------------------------
  // read the analog 50x, then calculate an average.
  // they will be the reference values
  for (int i = 0; i<50; i++) {
    tempX += analogRead(Analog_X_pin);
    delay(10); //allowing a little time between two readings
  }
  //----------------------------------------------------------------------------
  Analog_X_AVG = tempX/50;
  //----------------------------------------------------------------------------
  Serial.print("AVG_X: ");
  Serial.println(Analog_X_AVG);
  Serial.println("Calibration finished");
}

This is what I came up with. Note that the ReadLimits function is called after ReadAnalog and before runSpeed. In that order the stepper will not move in the direction of the limit switch, if it is pressed.
PS since you used setAcceleration, don't you need to call run instead of runSpeed?
void loop()
{
  ReadAnalog();
  ReadLimits();
  stepper.runSpeed(); //step the motor (this will step the motor by 1 step at each loop indefinitely)
}

void ReadLimits()
{
  if( digitalRead(2)==LOW && stepper.speed()>0 )//read input, assuming they have pull-up resistors.
  {
    stepper.setSpeed(0);
  }

  if( digitalRead(3)==LOW && stepper.speed()<0 )//read input, assuming they have pull-up resistors.
  {
    stepper.setSpeed(0);
  }
}

edit to avoid some confusion; here is the entire code with my suggestion embedded:
#include <AccelStepper.h> // accelstepper library
AccelStepper stepper(1, 8, 9); // direction Digital 9 (CCW), pulses Digital 8 (CLK)

//Pins
const byte Analog_X_pin = A0; // x-axis readings
const byte enablePin = 7;

//Variables
int Analog_X = 0;             //x-axis value
int Analog_X_AVG = 0;         //x-axis value average
  //----------------------------------------------------------------------------
void setup() {
  Serial.begin(9600);
  //----------------------------------------------------------------------------
  //PINS
  pinMode(Analog_X_pin, INPUT);
  pinMode(enablePin, OUTPUT);
  //----------------------------------------------------------------------------
  InitialValues(); // averaging the values of the 3 analog pins (values from potmeters)
  //----------------------------------------------------------------------------
  // Stepper parameters
  // setting up some default values for maximum speed and maximum acceleration
  stepper.setMaxSpeed(2000);     //SPEED = Steps / second
  stepper.setAcceleration(1000); //ACCELERATION = Steps /(second)^2
  stepper.setSpeed(1000);
  delay(1000);
}

void loop()
{
  ReadAnalog();
  ReadLimits();
  stepper.runSpeed(); //step the motor (this will step the motor by 1 step at each loop indefinitely)
}

void ReadLimits()
{
  if( digitalRead(2)==LOW && stepper.speed()>0 )//read input, assuming they have pull-up resistors.
  {
    stepper.setSpeed(0);
  }

  if( digitalRead(3)==LOW && stepper.speed()<0 )//read input, assuming they have pull-up resistors.
  {
    stepper.setSpeed(0);
  }
}

void ReadAnalog() {
  if (abs(Analog_X-Analog_X_AVG) > 50) {
    digitalWrite(enablePin, HIGH);  // enable the driver
    stepper.setSpeed(5*(Analog_X-Analog_X_AVG));
  } else {
    digitalWrite(enablePin, LOW);   // disable the driver
    stepper.setSpeed(0);
  }
  // Reading the potentiometer in the joystick:
  Analog_X = analogRead(Analog_X_pin);
  // if the value is 25 "value away" from the average (midpoint), we allow the update of the speed
  // This is a sort of a filter for the inaccuracy of the reading
  if (abs(Analog_X-Analog_X_AVG) > 50) {
    stepper.setSpeed(5 * (Analog_X-Analog_X_AVG));
  } else {
    stepper.setSpeed(0);
  }
}

void InitialValues() {
  //Set the values to zero before averaging
  float tempX = 0;
  //----------------------------------------------------------------------------
  // read the analog 50x, then calculate an average.
  // they will be the reference values
  for (int i = 0; i<50; i++) {
    tempX += analogRead(Analog_X_pin);
    delay(10); //allowing a little time between two readings
  }
  //----------------------------------------------------------------------------
  Analog_X_AVG = tempX/50;
  //----------------------------------------------------------------------------
  Serial.print("AVG_X: ");
  Serial.println(Analog_X_AVG);
  Serial.println("Calibration finished");
}

This is what I tried:
#include <AccelStepper.h> //accelstepper library
AccelStepper stepper(1, 8, 9); // direction Digital 9 (CCW), pulses Digital 8 (CLK)
//Pins
 const byte Analog_X_pin = A0; //x-axis readings
 const byte enablePin = 7;
 const byte leftSwitch = 2;
 const byte rightSwitch = 3;
//Variables
 int Analog_X = 0; //x-axis value
 int Analog_X_AVG = 0; //x-axis value average

void setup()
{

  //SERIAL
  Serial.begin(9600);
  //----------------------------------------------------------------------------
  //PINS
  pinMode(Analog_X_pin, INPUT);
  pinMode(enablePin, OUTPUT);
  //----------------------------------------------------------------------------
  InitialValues(); //averaging the values of the 3 analog pins (values from potmeters)
  //----------------------------------------------------------------------------
  //Stepper parameters
  //setting up some default values for maximum speed and maximum acceleration
  stepper.setMaxSpeed(2000); //SPEED = Steps / second
  stepper.setAcceleration(1000); //ACCELERATION = Steps /(second)^2
  stepper.setSpeed(1000);
  delay(1000);
}
void loop()
{
  ReadAnalog();
  ReadLimits();
  stepper.runSpeed(); //step the motor (this will step the motor by 1 step at each loop indefinitely)
}

void ReadLimits()
{
  if( digitalRead(2)==LOW && stepper.speed()>0 )//read input, assuming they have pull-up resistors.
  {
    stepper.setSpeed(0);
  }

  if( digitalRead(3)==LOW && stepper.speed()<0 )//read input, assuming they have pull-up resistors.
  {
    stepper.setSpeed(0);
  }

  ReadAnalog();
  stepper.runSpeed(); //step the motor (this will step the motor by 1 step at each loop indefinitely)
}
void ReadAnalog()
{
  if(abs(Analog_X-Analog_X_AVG)>50)
  {
      digitalWrite(enablePin, HIGH);  // enable the driver
      stepper.setSpeed(5*(Analog_X-Analog_X_AVG));
  }
  else
  {
      digitalWrite(enablePin, LOW);   // disable the driver
      stepper.setSpeed(0);
  }
  //Reading the potentiometer in the joystick:
  Analog_X = analogRead(Analog_X_pin);
  //if the value is 25 "value away" from the average (midpoint), we allow the update of the speed
  //This is a sort of a filter for the inaccuracy of the reading
  if(abs(Analog_X-Analog_X_AVG)>50)
  {
  stepper.setSpeed(5*(Analog_X-Analog_X_AVG));
  }
  else
  {
    stepper.setSpeed(0);
  }
}
void InitialValues()
{
  //Set the values to zero before averaging
  float tempX = 0;
  //----------------------------------------------------------------------------
  //read the analog 50x, then calculate an average.
  //they will be the reference values
  for(int i = 0; i<50; i++)
  {
    tempX += analogRead(Analog_X_pin);
    delay(10); //allowing a little time between two readings
  }
  //----------------------------------------------------------------------------
  Analog_X_AVG = tempX/50;
  //----------------------------------------------------------------------------
  Serial.print("AVG_X: ");
  Serial.println(Analog_X_AVG);
  Serial.println("Calibration finished");
}


Can I use string and int in Serial.println together? I just yesterday started programming on Arduino, and I have a little problem.

I want to print "#S|SKAITYMAS|[1]#" in one line, except instead of "1" I would like to use an int value. However, this one doesn't work:

Serial.println ("#S|SKAITYMAS|[",LINENR,"]#");

Any hint or tips would be appreciated.

The answer by canadiancyborg is fine. However, it is always better to avoid using String objects if at all possible, because they use dynamic memory allocation, which carries some risk of memory fragmentation. Simple and safe:

int answer = 42;
Serial.print("The answer is ");
Serial.println(answer);

The only drawback is that the constant string ("The answer is ") takes some RAM. This can be avoided by embedding it in the F() macro, which means “keep this in Flash memory only”. Then, the most memory-friendly idiom is:

int answer = 42;
Serial.print(F("The answer is "));
Serial.println(answer);

It can be done the C way:

sprintf() can be used to generate a formatted string, and then Serial.println() to send the string

char buf[32];
sprintf(buf, "#S|SKAITYMAS|[%d]#", LINENR);
Serial.println(buf);

or with String class as explained here:

https://www.arduino.cc/en/Tutorial/StringAdditionOperator

  String str = "#S|SKAITYMAS|["
  str += LINENR;
  str += "]#";
  Serial.println(str);

Do not do everything in just one line, as explained on the page link above.


Sending struct from Arduino to Raspberry Pi - wrong types I'm using Raspberry Pi and Arduinos for my home automation project where Raspberry Pi is the controler of Arduino nodes.
I use nRF24 wireless transceivers to communicate.

My problem is that when I was sending a structure like following

struct TempSensorData

{
      uint32_t result;
      uint32_t temperature;
      uint32_t humidity;
    };

From Raspberry to Raspberry everything went fine but now when I use Arduino as sender I get very strange results:

received: status: 335544320, temperature: 754974720 degrees, humidity: 0%

While on Raspberry it was

received: status: 0, temperature: 22 degrees, humidity: 44%

Can this be a problem with types? Or with different type of architecture (like different sizes on 3-2bit and 64-bit arch)?

EDIT:

Code on Raspberry:

if (radio.available())

{
        // dump the payloads until we've got everything
        Message receivedData = {0};
        radio.read(&receivedData, sizeof(Message));
        TempSensorData data = receivedData.msgData.tempSensorData;
        std::cout << "received: status: " << data.result << ", temperature: " << data.temperature << " degrees, humidity: " << data.humidity << "%" << std::endl; //TODO here we have some strange numbers - check if we have proper types
    }

Before that I have:

radio.begin();
radio.setPALevel(RF24_PA_LOW);
radio.setChannel(0x4c);
radio.openReadingPipe(1, RASPI_READ_ADDR);
radio.openWritingPipe(RASPI_WRITE_ADDR);

radio.enableDynamicPayloads();
radio.setAutoAck(true);
radio.powerUp();
radio.startListening();

And on Arduino:

Header header = {thisNodeId, thisNodeType, 0, static_cast<uint8_t>(MsgType::TEMP_SENSOR_DATA), 12345, Status::ok};
TempSensorData dhtData;
dhtData.result = DHT.read11(DHT11_PIN);
dhtData.humidity = (int)DHT.humidity;
dhtData.temperature = (int)DHT.temperature;
Message message = {0};
message.header = header;
message.msgData.tempSensorData = (dhtData);
radio.stopListening();
radio.write(&message, sizeof(message));
radio.startListening();

I also use a common header with defined structures for both Arduino and Raspberry, which contains:

#define RASPI_WRITE_ADDR 0xF0F0F0F0F0LL
#define RASPI_READ_ADDR 0xF0F0F0F0E1LL

struct TempSensorData {
  uint32_t result;
  uint32_t temperature;
  uint32_t humidity;
};

enum class Status : uint8_t

{
        ok,
        error,
        fail
    };

enum class MsgType : uint8_t {
    INITIALIZATION,
    RESET_REQUEST,
    ACK_NACK,
    TEMP_SENSOR_DATA,
};

struct Header {
  uint8_t nodeId;
  uint8_t nodeType;
  uint8_t location;
  uint8_t msgType;
  uint16_t checksum;
  Status status;
};

union MsgData {
  InitMsgData initMsgData;
  AckNack ackNack;
  TempSensorData tempSensorData;
};

struct Message {
    Header header;
    MsgData msgData;
};

radio is an item of RF24 class from https://github.com/TMRh20/RF24/

Unfortunately the RF24 repo is 64 commits ahead of what I use.

EDIT2:

Maybe the problem lays in that

enum class Status {};

which I use in both files.

I must add that I use g++-4.7 when compiling on Raspberry and when compiling on Arduino I use avr-g++-4.8.2

It is not a size problem: uint32_t is always 32 bits. Converting the
numbers to hex gives:

Raspberry to Raspberry: 0x00000000, 0x00000016, 0x0000002c
Arduino to Raspberry: 0x14000000, 0x2d000000, 0x00000000

There seems to be an offset between the two. You may just have lost one
byte when the Arduino is the sender. There may be also a byte order
issue, but your test is not sufficient to say. You can, e.g., send a
series of 0x12345678 to know for sure.

You need to devise a way of synchronizing the communication, i.e. to
identify, in the byte stream, which is the first byte of the packet.

Edit: Let me illustrate how this can happen both with and without
and endianness issue. I'll assume you are transmitting
{status: 0, temperature: 20, humidity: 45} and the first byte(s) of
the first packet are lost. On the receiving side, you combine the
remaining bytes of the first packet with the first byte(s) of the second
packet, and interpret the whole as a single packet. You get:
{status: 335544320, temperature: 754974720, humidity: 0}.

In a little endian to little endian scenario, you only need to loose one
byte:

original data:     0x00000000, 0x00000014, 0x0000002d
transmitted bytes: 00 00 00 00 14 00 00 00 2d 00 00 00
received bytes:    00 00 00 14 00 00 00 2d 00 00 00 00
received data:     0x14000000, 0x2d000000, 0x00000000

In a big endian to little endian scenario, you get the exact same result
if you loose 4 bytes:

original data:     0x00000000, 0x00000014, 0x0000002d
transmitted bytes: 00 00 00 00 00 00 00 14 00 00 00 2d
received bytes:    00 00 00 14 00 00 00 2d 00 00 00 00
interpreted data:  0x14000000, 0x2d000000, 0x00000000

I believe this could be because the Raspberry pi is big endian and the arduino is little endian.

Learn about Endianness here!


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

I have my source code organized like this:

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

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

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

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

But it returns this error:

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

What's causing this error?

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

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

Take the .h and the .cpp files and zip them together. Go to your Arduino sketch and click Sketch>Include Library> Add .ZIP library and import your library.

Again go to Sketch>Include library and select your library on the list. Some #iport lines will appear in the C++ code editor. Your library will be imported into the sketch.

For more information, take a look at:
https://www.arduino.cc/en/Guide/Libraries


Air data rate nRF24L01 I'm using two nRF24L01 to communicate with each other. I did the right setup and they worked fine, however I wanted to change the air data rate to a lower value, for more stability, as the datasheet says.

How can I setup the configuration for this?

After a small research I knew that you can change this using RF_DR
to change the value of the transmission, but I didn't really know how I could exactly write the correct code for this.

Another question: does this effect the range of the module? Or does it only affect the stability? And if not, then which code can I use to extend the range of these two modules ?

Increasing stability will increase the (usable) range. At least a bit. You could try decreasing the packet size, to make it even more reliable. There is no way to increase the output-power (only decrease).

You could try different channels, and see which one gives you the best range in your application.

After that you have to get NRF24 modules, with external antennas and amplifiers.

The documentation for the function you want is here.

Reducing the speed doesn't directly increase the range, but increased stability will have the knock-on effect that the fringes of transmission distance will be more reliable, making it appear that you have slightly greater distance.


How can I connect an 8-relay board without using 8 digital pins? I'm looking to connect an 8-relay board to an Arduino Uno. A board like this one. However, I don't really want to use up 8 digital outputs if I don't have to. Is there some intermediate circuitry I can either buy or build that would do this?

For example, can I connect something to the serial so that sending '3' would result in binary 00000011 and thus turn on relay's 1 and 2?

Alternately, and probably more lazy, is there an extension board that would just give me a pile more digital pins?

A likely solution is to use the Arduino SPI interface and the Arduino SPI library to control a SPI relay board.  Here is a 6 year old thread talking about such a board. And another more recent relay thread where SPI is brought up.

You can use a MUX/DEMUX. Check out the link. Basically, you can select the output pin by a series of commands that you can do with the Arduino. The relay inputs will be hooked up to the IC's outputs

https://www.sparkfun.com/datasheets/IC/cd74hc4067.pdf


Not able to send SMS to Mobile using GSM900A and Arduino Uno I tried the code shown below (found here)

void setup()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+919449835011\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Test SMS -Jay\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}
void loop()
{
}

I interfaced my GSM SIM900A module to the Arduino UNO (connections - GSM Tx to Arduino Rx, GSM Rx to Arduino Tx, GSM provided with supply (12V) using external adapter, GSM gnd to Arduino gnd).

I dumped the code into Arduino and then opened the Arduino IDE serial terminal. In the serial terminal, I get AT+CMGF=1AT+CMGS="+919449835011"Test SMS -Jay\r being displayed and I am not receiving any sms to my phone. I am not sure if its a problem with the code or connections.

looks like you should be using Serial.begin(2400);

also, I'm assuming your sms phone number isn't actually 919449835011 and that that's not actually the number you used in your code

Switch to these pins:

SoftwareSerial mySerial(10, 11); // RX, TX


Right PIN to activate a wireless relay with ESP8266 ESP-01 I'm trying to program an ESP8266 ESP-01 module to let it connect to my personal wifi network and activate a wireless relay that I've bought.

No problems with Wifi connection so I've omitted the code about it, my problem is to find what is the right PIN to set to LOW/HIGH to control my relay.
Setting relayPin to 1 as shown in this code works and with it I can see the embedded LED turning on and off.

const int relayPin = 1;

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

void loop() {
    Serial.println("Close Relay for 100 ms and then Open");
    digitalWrite(relayPin, LOW);
    delay(100);
    digitalWrite(relayPin, HIGH);
    delay(200);
}

Surfing the web I've found the following diagram about the ESP8266 ESP-01 module:

I've tried to set relayPin to 0 or to 2 but the relay doesn't activate/deactivate.

So, what is the right PIN number to set in my relayPin constant to control the GPIO0 port?

The relay works succesfully if I give him +3.3V on GPIO0 with an external power.

Thanks in advance

Looking at better pictures of the PCB on ALIExpress it looks like GPIO0 is used to switch the relay.

What that pin maps to, though, depends on what board you have selected in the IDE.

You can use any pin of the esp-01
You may want to tell the TX and Rx pins though to behave like regular I/O with the pinMode/Function_3 command as described here:

https://arduinodiy.wordpress.com/2018/06/14/simple-wifi-relay-board-or-diy-sonoff-sv-sonoff-4-channel-2/


Multiplication, division. What is wrong? const unsigned long C1 = 30 * 1000;
const unsigned long C2 = (300 * 1000)/C1; // must be = 10

void setup() {
  Serial.begin(57600);
  Serial.println("\n-------");
  Serial.print("C1 = "); Serial.println(C1);
  Serial.print("C2 = "); Serial.println(C2);

  unsigned long V1 = (300 * 1000)/C1;   // must be = 10
  Serial.print("V1 = "); Serial.println(V1);

  long V2 = (300 * 1000)/30000; // must be = 10
  Serial.print("V2 = "); Serial.println(V2);

  int V3 = (300 * 1000)/30000; // must be = 10
  Serial.print("V3 = "); Serial.println(V3);
}

void loop() {
}

Arduino UNO printed in monitor console:

C1 = 30000   (ok)
C2 = 143164  (must be = 10)
V1 = 143164  (must be = 10)
V2 = 0       (must be = 10)
V3 = 0       (must be = 10)

What is wrong?

300

and

1000

are integers.

What

long V2 = (300 * 1000)/30000;

really does is take the integers 300 and 1000 multiply them. This calculation overflows, and equals -27680. Dividing that by 30000 yields 0. What you added in your comment isn't a hack, it's the proper solution. By including the suffix L or UL you tell the compiler that you want longs, not ints.

This is my code for your problem:

unsigned long mul(long num1, long num2)
{
  unsigned long res, add = 0;
  while (num1 > 65000)
  {
    num1 -= 65000;
    add++;
  }
  res = unsigned(num1 * num2);
  while(add)
  {
    res +=65000;
    add--;
  }
  return (res + add);
}


Does sharing code on Arduino Create automatically grant any license rights? I have code I am happy to share under a GNU GPL License and which is marked accordingly. Before I upload it to Arduino Create Web Editor I want to check whether in doing so I inadvertently grant additional license rights. I have searched for any terms and conditions which may inform me but not found any as yet.

Arduino Create doesn't assume any licensing of any form. Sharing isn't a public thing. You have to specifically provide someone with a link to your sketch. If you choose to post that link publicly then that is your concern.

Any licensing should be included with your sketch.

You should read the GPL License terms with respect to any rights you are concerned about, but in general, GPL licensed software is available to anyone to do anything with, as long as they keep it public and perpetuate the GPL License. Note: IANALawyer. If you wish to protect any specific rights, you should probably consult one.


Is there a way to play .mp3 files from an SD card on Arduino? Is there a way to have mp3 files on an SD card in the SD card shield for the Arduino and play an mp3 file on that SD card with a buzzer?

If possible also with something like:

playmp3(thismp3.mp3);

So that if I execute that command, the Arduino will play thismp3.mp3 through a buzzer.

Thank you.

If you're not specifically trying to make the arduino itself do the decoding and playback, you can get something like the Mini DFPlayer which would let you do essentially what you're asking for and offloads the decoding and playback so your arduino can do something else while the audio is playing.

I believe MP3 uses licensed software that is implemented on decoder chips like VS1053.
Usually one would use a board like this, with an SD card for holding the massive amount of info that makes a sound.
http://www.oddwires.com/mp3-decoder-module-vs1053-for-arduino/?gclid=EAIaIQobChMInKS7lJGm2QIVE4_ICh1kTQa4EAQYAiABEgIKH_D_BwE
You then send commands to the unit to tell it to start, stop, advance, etc.


Where in datasheet is the warning about unreliability of reading PINxn? I use atmega32u4 (but believe it applies to all models). Here is the datasheet.

Consider the following C program (I use AVR-GCC 5.4.0):

#include <avr/io.h>
int main(void)
{
  PORTB |= 1 << PB5; /* pullup */
  DDRB |= 1 << PB0; /* LED */
  if (!(PINB & 1 << PB5))
    PORTB |= 1 << PB0; /* turn on LED */
  while (1) ;
}

There are two situations:

connect a 10cm wire to PB5 pin (the other end of the wire is in the air): the result is that sometimes after poweron the led is on, sometimes the led is not on.
do not connect anything to PB5 pin: the result is that after poweron led is never on.

I have a standard setup. Nothing tricky. If it does not work reliably, this gotcha MUST be documented in datasheet. This setup is supposed to deal with a stupid button. But sometimes it detects a keypress while there is no keypress.

The question is: where in datasheet there is a warning about this gotcha?
And did somebody come across such case, or I'm the first in the world?

EDIT See also this question.

did somebody come across such case, or I'm the first in the world?

You are not the first. I recently got bitten by the very same issue.

However, unless you are close to an unusually strong radio source, I do
not think it has anything to do with electromagnetic interference. In my
experience, the internal pullup is perfectly reliable for reading
switches and push buttons, even on a breadboard with jumper wires acting
as antennas. If you use pinMode() and digitalRead() instead of
direct port access, you too will find the internal pullup is perfectly
fine.

Before I give you the answer (suspense...), let's look closely at what
your code does. The disassembly looks like this:

main:
    sbi  PORTB, PB5 ; turn on pullup on PB5
    sbi  DDRB,  PB0 ; set LED pin as output
    sbis PINB,  PB5 ; read PB5, if it is LOW then:
    sbi  PORTB, PB0 ;   turn on LED
0:  rjmp 0b         ; hang in an infinite loop

In the situation when the LED turns on, every instruction there executes
in two CPU cycles, save for sbis, which takes a single cycle in this
case. Now, let's look at the timings, and specifically at the states of
the pullup and the input circuitry during each of the first seven CPU
cycles:

cycle   instruction   pullup latch PINB5
----------------------------------------
   1   sbi PORTB, PB5   off    X     X
   2      cont.         off    X     X
   3   sbi DDRB,  PB0   on     X     X
   4      cont.         on    LOW    X
   5   sbis PINB, PB5   on     X    LOW
   6   sbi PORTB, PB0   on     X     X
   7      cont.         on     X     X

In the table above, “X” means “don't care”. Each instruction takes
effect at the beginning of the next CPU cycle, when the clock's rising
edge commits the result of the instruction to the affected flip-flops.
That's why the pullup turns on only at the beginning of cycle 3.
Now, since the pin did read LOW, that means the PB5 flip-flop was LOW
while the CPU was reading it, during cycle 5. This in turn means
that the synchronizing latch before that flip-flop was LOW during
cycle 4.

Your expectation was for the pin to read HIGH. So let's see: how fast
should the pin voltage have risen in order for the pin to indeed read
HIGH? Since the input latch is transparent during the first half of each
cycle, this means that the voltage should raise past the Schmitt
trigger's threshold during cycle 3 and the first half cycle 4.
So the rise time should be less than 1.5 cycles. Or rather
1.5 cycles minus the combined propagation delay of the PORTB5
flip-flop and the logic that controls the pullup from that flip-flop's
output. Probably around 90 ns. That's short!

By now you have probably guessed: the culprit is not electromagnetic
interference, it's stray capacitance. A simple calculation will show you
that about three picofarads is enough to produce the effect you are
seeing. This is the kind of stray capacitance you will find everywhere,
even between the PCB traces of your Arduino board. Note that
electromagnetic noise can add some unpredictability to what you see, as
the pin is susceptible to it when it's completely floating, i.e.
before you turn on the pullup, which makes the initial voltage (at the
beginning of cycle 3) unpredictable. But once the pullup is on and
the pin has settled, you won't care about noise anymore, unless it's
unusually strong.

The solution to your problem is simply to wait for the pullup to charge
the stray capacitance. A microsecond delay should be enough to fix the
issue. Alternatively, use the Arduino functions instead of direct port
access: they are so slow that you will not need any extra delay.

  where in datasheet there is a warning about this gotcha?

In section 18.2.4 – Reading the Pin Value: “[The synchronizing latch] is
needed to avoid metastability if the physical pin changes value near the
edge of the internal clock, but it also introduces a delay.”
(emphasis mine).

Edit: In a previous version of this answer, I incorrectly stated
that sbi is a single cycle instruction, which required the voltage to
rise in half a cycle instead of 1.5 cycles. The corrected timing is
still short enough for stray capacitance to be a valid explanation of
the observed behavior.

In summary:

The stray capacitance attached to the pin, together with the pullup
resistor, for an RC circuit.
As the pin is initially floating, it's initial voltage is
unpredictable.
When the pullup is turned on, the voltage starts to rise from whatever
initial value it had to 5 V.
After some time, which can be typically of the order of the RC time
constant, the input Schmitt trigger turns HIGH.
After some extra delay introduced by the synchronizer, the PINxn
flip-flop turns HIGH.
If the CPU reads the PINx register before that happens, it gets a LOW
reading.

This actually is documented in the datasheet and illustrated by the logic diagram of the typical GPIO, to see what is really going on behind your compiled code you need to look at the generated assembly code and which registers are being accessed:

When you change one bit of an IO port, you are either modifying the 8 bit register on which that bit is mapped using the WRx signal or just the 1 bit register for the pin alone using the WPx signal.  When you use the WPx signal to set or clear the bit, you don't need to know the states of the other pins so the discussion ends here.  However, when you use the WRx signal to MODIFY a single bit, you need to know the states of the other 7 bits which means that your need to read the 8 bit port.  You can either read the port LATCH using the RRx signal or you can read the actual physical pins using the RPx signal.  Now when using the RRx signal, no amount of loading or noise on the pins themselves will affect what is read from the output of the port latch but when using the RPx signal, if a previous write to the port is followed by a read of the port, any parasitics or noise on the OUTPUT pins may cause a pin that you think that you just set to a one suddenly becomes a zero.

The reason this happens is because of how opcodes are pipelined.  Writes to ports happen at the end of the last instruction clock but reads happen at the beginning so that there is essentially zero time between when you set that bit to a 1 and when you change some other bit (Read-modify-write fashion) so that bit is still a zero when it is read and then immediately written as a zero.

As illustrated below, this can be rectified by inserting a delay between write and read-modify-write opcodes to let the pin states stabilize.  The delay must take into account the capacitive loading and noise environment


Arduino ADS1115 PGA settings I am trying to use an external ADC with my UNO for very precise measurement of my signal.
The ADC which I am using is ADS1115.

http://henrysbench.capnfatz.com/henrys-bench/arduino-voltage-measurements/arduino-ads1115-module-getting-started-tutorial/

This is the site which I am referring to.It says the default reference voltage of the PGA gives a resolution of 188microvolt per bit.It also indicates towards changing the reference voltage to 2.048, to still increase the resolution per bit.

Can you please guide me in how to achieve this 2.048V.

Update:
https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0ahUKEwiFpq3P89vNAhXJro8KHa6IC04QFggpMAI&url=https%3A%2F%2Fcdn-learn.adafruit.com%2Fdownloads%2Fpdf%2Fadafruit-4-channel-adc-breakouts.pdf&usg=AFQjCNGhdMw47MRlXolMiMoHdsTwKMwMow

It seems that by adjusting the gain (page number 16-17 of 18) we can achive it.

WHat I need to know now, is where should I put that piece of code

      ads1115.setgain(...)

in void loop() or in void setup()

Thanks

Anupam

Reference voltage inputs are usually high impedance requiring little current.  So you can get by with simple circuits like a resistor and zener diode.  Here is just one I happened across:

Do some research to find out more about this.

For your specific case, you should read the ADS1115 specification sheet.  As this ADC chip has it's own built in voltage reference.

In the Arduino paradigm, tasks that are to be executed once at the beginning of a program are placed in the setup() method.  Tasks which are to be executed repeatedly are placed in the loop() method.  As setting the gain of the ADC appears to only be done once (consult the ADS1115 PDF linked to above), it appears to fall into the former category.

Added later...

I changed the circuit diagram after I realized it was a bad example for creating an Analog to Digital Converter voltage reference.

setup() runs once at the beginning after the program is run.  However, loop() runs continuously after that.

The setgain() instruction is needed once at the beginning, so it should be in setup() function.

good luck!


Code to obtain PWM output I tried code to obtain 100KHZ PWM output with a 41.66% duty cycle by reading an analog value from A0, which is compared with a reference 5V value for obtaining PWM value.

Can someone help me with the code? Any help is very much appreciated.

Here is my code.

int Pwmpin=9;//Pwm Output Pin
int Fchange= A0;//Frequency change through Potentiometer

void setup() {
  pinMode(Pwmpin, OUTPUT);//Pwm pin as Output
  Serial.begin(9600);
  TCCR1A=_BV(COM1A1)|_BV(COM1B1);//Non-inverted Mode
  TCCR1B=_BV(WGM13)|_BV(CS11);//Prescalar 8
}

void loop(){
  float freq=0;
  float count=10000,countt=0,Pinput=0;
  while(1){
    ICR1=count;//variable Frequency
    countt=16*count;
    freq= int(16000000/countt);
    OCR1A=int(count/2);
    Serial.print("Pwm Freq =");
    Serial.println(freq);
    count=10000;
    Pinput=analogRead(A0);//Read input value
    Serial.print("adc value is:");
    Serial.println(Pinput);
    Pinput=(Pinput/0.0113);
    Serial.print("pwm value is:");
    Serial.println(Pinput);
    count=count+Pinput;
    if(count>=100000) {
      count=10000;
    }
    delay(1000);
  }
}

Read the datasheet.
Figure out which pen mode works for you and which prescaler and top you need.
Set timer1 to that mode.

After that all you need is to load the duty cycle register with the desired value.

For your application leave the top value alone.

Your code is far from that.


Arduino LCD Display drawing image issue I am playing with 3,5" (400x240) TFT display which is placed into Arduino Mega 2560 R3 board.

My final goal is taking .raw data from SD card and drawing it on display.

What I have done so far:

- My drawing method in the sketch:

void LoadImage(File& file)
{
    for (int y = 0; y < SCREEN_HEIGHT && file.available(); y++) {
        uint16_t buf[SCREEN_WIDTH];
        for (int x = SCREEN_WIDTH - 1; x >= 0; x--) {
            byte l = file.read();
            byte h = file.read();
            buf[x] = ((uint16_t)h << 8) | l;
        }
        myGLCD.drawPixelLine(0, y, SCREEN_WIDTH, buf);
    }
}

- For reference drawPixelLine method's implementation from UTFT library:

void UTFT::drawPixelLine(int x, int y, int sx, uint16_t* data)
{
    unsigned int col;
    cbi(P_CS, B_CS);
    setXY(x, y, x+sx-1, y);
    for (int tc=0; tc<sx; tc++)
    {
        char* p = (char*)&data[tc];
        LCD_Write_DATA(*(p + 1), *p);
    }
    sbi(P_CS, B_CS);
}
void UTFT::setXY(word x1, word y1, word x2, word y2)
{
    if (orient==LANDSCAPE)
    {
        swap(word, x1, y1);
        swap(word, x2, y2)
        y1=disp_y_size-y1;
        y2=disp_y_size-y2;
        swap(word, y1, y2)
    }
        LCD_Write_COM(0x2a);
        LCD_Write_DATA(x1>>8);
        LCD_Write_DATA(x1);
        LCD_Write_DATA(x2>>8);
        LCD_Write_DATA(x2);
        LCD_Write_COM(0x2b);
        LCD_Write_DATA(y1>>8);
        LCD_Write_DATA(y1);
        LCD_Write_DATA(y2>>8);
        LCD_Write_DATA(y2);
        LCD_Write_COM(0x2c);
}

My current rendering:

Desired image:

TFT Lcd and Mega Board

UPDATE1

I ran henningan test from utft library, drawing sin/cos graph and simple squares

Here is attempt to render yellow square 100x100 raw data

I'have the same LCD from mcufriend and it doesn't work with original UTFT library.

Try modified version from https://github.com/dgolda/UTFT and use:

myGLCD(NIC35WS,38,39,40,41); //3.5" TFTLCD for arduino 2560 from mcufriend.com

it is too difficult for starters.maybe you can try this UART TFT LCD.
tutorial:http://blog.iteadstudio.com/product-preview-nextion-in-an-arduino-project-2/


Arduino Uno with CC3000 WiFi Shield cannot be initialized I am working on an Arduino Uno and CC3000 WiFi shield. I interfaced it over my Arduino and added the SparkFun library SFE_CC3000_Library. Then I opened the TestBoard example, but it hangs on setup in the first command wifi.init().

How can I solve this problem, and how can I enable debug mode?

Here's the code

#include <SPI.h>
#include <SFE_CC3000.h>
#include <utility/netapp.h>

#define DEBUG     1
// Pins
#define CC3000_INT      2   // Needs to be an interrupt pin (D2/D3)
#define CC3000_EN       7   // Can be any digital pin
#define CC3000_CS       10  // Preferred is pin 10 on Uno

// Constants
#define FW_VER_LEN      2   // Length of firmware version in bytes
#define MAC_ADDR_LEN    6   // Length of MAC address in bytes

// Global Variables
SFE_CC3000 wifi = SFE_CC3000(CC3000_INT, CC3000_EN, CC3000_CS);

void setup() {

  int i;
  unsigned char fw_ver[FW_VER_LEN];
  unsigned char mac_addr[MAC_ADDR_LEN];

  // Initialize Serial port
  Serial.begin(115200);
  Serial.println();
  Serial.println("----------------------------");
  Serial.println("SparkFun CC3000 - Board Test");
  Serial.println("----------------------------");

  // Initialize CC3000 (configure SPI communications)
  if ( wifi.init() ) {
    digitalWrite(13, HIGH);
    Serial.println("CC3000 initialization complete");
  } else {
    Serial.println("Something went wrong during CC3000 init!");
  }

  // Read and display CC3000 firmware version
  if ( wifi.getFirmwareVersion(fw_ver) ) {
    Serial.print("Firmware version: ");
    Serial.print(fw_ver[0], DEC);
    Serial.print(".");
    Serial.print(fw_ver[1], DEC);
    Serial.println();
  } else {
    Serial.println("Could not read firmware version from CC3000");
  }

  // Read and display CC3000 MAC address
  if ( wifi.getMacAddress(mac_addr) ) {
    Serial.print("MAC address: ");
    for ( i = 0; i < MAC_ADDR_LEN; i++ ) {
      if ( mac_addr[i] < 0x10 ) {
        Serial.print("0");
      }
      Serial.print(mac_addr[i], HEX);
      if ( i < MAC_ADDR_LEN - 1 ) {
        Serial.print(":");
      }
    }
    Serial.println();
  } else {
    Serial.println("Could not read MAC address from CC3000");
  }

  // Done!
  Serial.println("Finished board test");

}

void loop() {

  // Do nothing
  delay(1000);
  Serial.println("Loop_Problem");

    }

Solved it, the problem was because the SparkFun library was not working with my shield. I replaced it using the Adafruit_CC3000_Library and now it works fine.

I was having the same problem with the ethernet shield (and i still have it). In my case it was caused by the network router. When my modem/router couldn't connect to the net (bad weather etc...) the shield couldn't take an IP and the initialaization was failing every time just because i was disconnected from the internet. The library works almost the same way. Basicaly you have to make sure it can connect.


How Arduino UNO differentiate between program/flash and serial terminal data I am excited to know how Arduino UNO or nano differentiate between program data that is to be burned into its flash when we press Upload Sketch and serial terminal data when we press Send? Is there any special sequence to identify those? How it will be identified by Bootloader?
And I have this understanding can anyone correct if I am wrong or anything you want to add will be helpful:

When we press Upload Sketch then a RST signal is sent.
ATmega controller when it receives RST signal jumps to Bootloader section of flash and waits for a perticular sequence from UART
If it receives then starts to write the data buffered from UART to flash. This process is handled by Bootloader.
If it doesn't receive the sequence waits till timeout and then jumps to flash section and starts to execute from 0x0000

Unlike out kids it does what it is told, not what we thought we told it to do.  Different instructions do different things. Serial.print("Hi"); is stored in RAM will print from Ram, however if you Serial.print(F("Hi"); it will print from flash. The "F" macro tells it where to print from. The Serial.print("Hi"); is stored in flash but moved to RAM and stored there while your program is started and is running whether you print it or not. The "F" macro keeps it in flash not using RAM. Everything that happens when it starts either in your code or the boot loader is code that has been programed and stored in the flash. The Boot loader decodes the code data stream when uploading and stores it in the specified location. It does not know what it is it just reads it and stores it. I do not know what it is called here but there use to be a program module called "CSTART" that upon reset got control; initialized all the memory and set up the variables before turning control over to the user program. Arduino does the same thing, data has to be placed in the right place before starting.


Arduino IDE / Teensy 3 on Ipad Does anyone know a good IDE for Ipad to write Arduino code and compile it for teensy 3 ?

Answers with different alternatives would be appreciated

I don't know of any way to compile it on an iPad, but Textastic should do the trick for writing the code if you set the syntax highlighting to C++.


0.96" OLED and Arduino UNO usage error I have Arduino UNO with 0.96" OLED display with 128(width)*32(height). It is said that I have to edit Adafruit_SSD1306.h for my 128*32 OLED, okey I did it from 128*64 to 128*32 but I still get the compiler error:

ssd1306_128x32_i2c.ino:54:2: error: #error ("Height incorrect, please
fix Adafruit_SSD1306.h!");

Yes, I fixed the Adafruit_SSD1306.h file, but now, it is still gives me a compiler error:

C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h: In member
function 'uint8_t TwoWire::requestFrom(uint8_t, uint8_t, uint8_t)':
C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h:47: error:
too many arguments to function 'uint8_t twi_readFrom(uint8_t,
uint8_t*, uint8_t)'
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:85: error: at
this point in file
C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h: In member
function 'uint8_t TwoWire::endTransmission(uint8_t)':
C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h:48: error:
too many arguments to function 'uint8_t twi_writeTo(uint8_t, uint8_t*,
uint8_t, uint8_t)'
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:140: error: at
this point in file
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp: In member
function 'virtual size_t TwoWire::write(const uint8_t*, size_t)':
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:195: error:
invalid conversion from 'const uint8_t*' to 'uint8_t*'
C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:195: error:
initializing argument 1 of 'uint8_t twi_transmit(uint8_t*, uint8_t)'

How can I use my four-pin OLED display with no errors?

May I suggest the following. I found this fork of the Adafruit library which works better than the one they have on their website Adafruit_ssd1306syp. The original Adafruit_ssd1306 library doesn't play nice with SPI and when you want to have your OLED running on i2c and use the SPI for something else. This is a great resource. Download, unzip to your libraries directory. Then run this sketch:

#include <Adafruit_ssd1306syp.h>

#define SDA_PIN A4
#define SCL_PIN A5

Adafruit_ssd1306syp display(SDA_PIN, SCL_PIN);

void setup() {

  display.initialize();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  printM("Starting Demo...");

}

void printM(String mess) {

  display.println(mess);
  display.update();
}

void loop() {

  printM("working");
  delay(1000);

}

You may wanna try this lib: https://github.com/olikraus/u8glib

Supports many devices and is very well documented!

Cheers


What are the fundemental differences of different Bluetooth modules for beginners? I'm a beginner to microcontrollers and electronics, albeit not really to computers and programming.

Starting out with the Arduino, I came to a point whereby I'm really interested in getting my prototype to talk to a mobile device or a computer to send and receive data (for example, send sensor data or receive commands).

Looking out, I've found out that there are different bluetooth modules with varying pricing points. Further research into differences did not reveal much to me as being a beginner, I am struggling to understand what to look out for or how to choose.

My question here is:

What are the fundemental differences of different Bluetooth modules for beginners, such as:

HC-05
HC-06
HC-07

And what should one look for when buying a simple Bluetooth module for Arduino?

As far as simplicity is concerned, HC05 would be the way to go. It is by far the most popular and there are a tonne of tutorials on using it (just a quick google search).
As for the differences:

The HC-05 module can build a connection to other modules. E.g. a Robot being a master and connecting to slave bluetooth module. Or in slave mode to make a wireless bridge to a notebook.
The HC-06 module only can be a slave. This makes it only useful for say connecting a notebook as a master to a robot with a slave module e.g. for a wireless serial bridge.
As for the HC07, support seems low so I would recommend sticking with HC05 or HC06

At the end of the day it comes down to your requirements. If you are only wanting to talk between the phone and your arduino than the HC06 would work fine, however if at some point in time you want to talk to another arduino, than hc05 would be the way to go.

It is possible to use the HC-05 to upload your programs wirelessly, although it requires extra wiring from the HC-05 to the arduino.

Wireless uploading can be a useful alternative when access to the arduino is cumbersome or if you don't feel comfortable wiring your computer to an arduino that is powered or wired to something else, achieving the same you would get with say an optocoupler.


Need to cycle through LED brightness So this is pretty much explanatory.  I am new to arduino, and i am learning the best i can.  I need to sketch a code in which will cycle through 5 different brightness settings of an led.  One push will cycle through the five, another push of the button will turn the led off, and another push will restart the cycle.

const int led =11;
const int BUTTON = 7;
boolean lastButton = LOW;
boolean currentButton = LOW;
int ledLevel = 0;

void setup()
{
  pinMode(led,OUTPUT);
  pinMode(BUTTON,INPUT);
}
boolean debounce(boolean last)
{
  boolean current = digitalRead(BUTTON);
  if (last != current)
{
  delay(5);
  current = digitalRead(BUTTON);
}
return current;
}

void loop()
{
  currentButton = debounce(lastButton);
  if (lastButton == LOW && currentButton == HIGH)
  {
    ledLevel = ledLevel + 51;
  }
  lastButton = currentButton;
  if (ledLevel > 255) ledLevel = 0;
  analogWrite(led, ledLevel);
  analogWrite(led, ledLevel + 51);
  delay(200);
  analogWrite(led, ledLevel + 102);
  delay(200);
  analogWrite(led, ledLevel + 153);
  delay(200);
  analogWrite(led, ledLevel + 204);
  delay(200);
  analogWrite(led, ledLevel + 255);
}

The code above turns the led on and cycles brightness, like it should it however for some reason it does disable the button.  Take the analogWrites out except for the first one, and the button will cycle the led. any suggestions on what i could do?  Im very new at this.

Something like this, with variable declarations & setup() left to you.  All time elements are of type unsigned long.

pwmValue {} = [51, 102, 153, 204, 255];

void loop(){
  if (digitalRead(startButton) == LOW && pwmCycling == 0){
    // start button pressed, and not already running
    startTime = millis(); // capture the time of the button press
    pwmCycling = 1; // keep track of the running state. 0 for off, 1 for on.
    }
  if (pwmCycling == 1){ // cycling is running
    // this is where the blink without delay is:
    currentTime = millis(); // capture the time now
    elapsedTime = currentTime - startTime; // see how much time went by
    if (elapsedTime >= eventDuration){  // enough?  start next brightness
      currentTime = startTime; // set up for next event time
      brightNumber = brightNumber +1; // keep track of brightness level
      if (brightNumber >= 5){ brightNumber = 0; } // reset after the last level
      analogWrite (ledPin, pwmValue[brightNumber]); // write the LED pin
      }
    }
  if (digitalRead(startButton) == LOW && pwmCycling == 1){
    // start button pressed while LEDs are cycling, stop them
    pwmCycling = 0;
    analogWrite (ledPin, 0);
    brightNumner = 4; //reset the brightness level to the end
    delay (100); // little bit of dumb debounce delay
    }
}

All the delay(200) lines keep the sketch from reading button presses.

You need to learn about Blink Without Delay so your sketch can do things other than sit there blindly letting time pass.


Sending to Arduino UNO multiple values from Python code I'm starting to learn how to work with Arduino, particularly communication between a Python code running on a PC and an Arduino Uno.

So I decided to start with what I thought to be a easy task. That is, sending the user input from Python. There are 2 values, one delay between Arduino LED (port 13) and the servo angle.

It didn't work and I couldn't find any answers, hope you can help me.

Arduino Code -

#include <Servo.h>

const int ledPin = 13; // pin the LED is attached to
int incomingByte = 1000;      // variable stores  serial data
int pos = 0;
int incoming[2];
Servo myservo;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
  myservo.attach(9);
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
   digitalWrite(ledPin, HIGH);
   myservo.write(180);
   delay(1000);
   digitalWrite(ledPin, LOW);
   myservo.write(0);
}

void loop()
{

  if (Serial.available()>=2)
  {
     for (int i = 0; i < 1; i++)
     {
      incoming[i] = Serial.read();
     }
    digitalWrite(ledPin, HIGH);
    delay(incoming[0]);
    digitalWrite(ledPin, LOW);
    myservo.write(incoming[1]);
  }
}

Python (3.7) code -

import serial
import time

ser = serial.Serial('COM5', 9600, timeout=1)

user_input = '1'
while user_input != 'q':
    user_input = input("'Blink time is or q = quit' : ")
    servo_input = input("What position servo go? ")
    byte_command = str.encode(user_input)
    ser.write(byte_command)
    servo_command = str.encode(servo_input)
    ser.write(servo_command)
    time.sleep(0.5)

print('\nq entered. Exiting the program')
ser.close()

Well I did it in the simplest way.

I just sent a string to C++ and deconstructed it with sscanf().


Arduino Uno suddenly not recognized in Windows 8.1 (code 43) I had my Arduino Uno connected to an external 12 V supply for 2-3 hours as I was working on other parts of my project. Suddenly the voltage from pin 9 which I was monitoring in the oscillator dropped down to 0 approximately.

I went on removing the external supply. The board was very very hot. I then connected the USB to my laptop and I got an error 43 (Windows did not allow the device to connect because it was reporting problems). I can't load any program of course. The 5 V pin works but it outputs a voltage lower than usual (at about 3.9 V). When I connect the external supply the 5 V pin outputs full voltage.

Any idea? Any fix?

Something is shorted out.

When you connect via USB, the USB port cannot supply enough current because of the short. The output drops to 3.9V and the USB port on your computer reports an error, probably due to over current.

When you connect the external power supply, it has enough power to supply the short. The output remains at 5V.

You can think of power supplies as having a very small internal resistance (R_p), and the board as being a resistive load (R_b). This forms a voltage divider, but because R_b >> R_p the voltage seen by the board is basically the same as that of the power supply. With a short, R_b is often < R_p, and thus the voltage seen by the board is much lower than the power supply voltage.

The fix will depend on which component is getting hot. Plug in the external power supply and check which one it is. Note: The component will get hot enough to burn your finger after a few seconds. One way is to check one component at a time, disconnecting the power between each check. Start with the big ICs.

If either the Atmega328P or the smaller ATmega8u2 (?) are hot, they will have to be replaced.

Finally, boards don't short out by themselves. Something is wrong with your circuit or you may have placed the board down on some conductive surface. If you post you circuit we might be able to spot the problem.

SOLVED!!!
I was having the same problem but none of the solutions here was working so I just tried this random idea of just powering the Arduino Uno board with the DC jack and hitting reset, and then when I unplugged it from that and connected to the computer via USB all of a sudden its working just fine! :D


How to send HTTP request to specific port using Ciao? I currently have a working REST client on my arduino, but the requests always go to port 80, how do I make it send the request to a specific port?

This is my current code:
/*
File: RestClient.ino
This example makes an HTTP request after 10 seconds and shows the result both in
serial monitor and in the wifi console of the Arduino Uno WiFi.

Note: works only with Arduino Uno WiFi Developer Edition.

http://www.arduino.org/learning/tutorials/boards-tutorials/restserver-and-restclient

#include <Wire.h>
#include <UnoWiFiDevEd.h>

void setup() {

    const char* connector = "rest";
    const char* server = "download.arduino.org";
    const char* method = "GET";
    const char* resource = "/latest.txt";

    Serial.begin(9600);
    Ciao.begin();

    pinMode(2, INPUT);

    delay(10000);
    doRequest(connector, server, resource, method);
}

void loop() {

}

void doRequest(const char* conn, const char* server, const char* command, const char* method){
    CiaoData data = Ciao.write(conn, server, command, method);
    if (!data.isEmpty()){
        Ciao.println( "State: " + String (data.get(1)) );
        Ciao.println( "Response: " + String (data.get(2)) );
        Serial.println( "State: " + String (data.get(1)) );
        Serial.println( "Response: " + String (data.get(2)) );
    }
    else{
        Ciao.println ("Write Error");
        Serial.println ("Write Error");
    }
}

If I add for example :8080 to the end of the server variable, it does not work.

So how do I make that request go to a specific port?

You can find a portdefinition on your arduino in this path:

/usr/lib/python2.7/ciao/connectors/restserver/restserver.json.conf

{
 "name" : "restserver",
 "description" : "REST server connector for the Ciao Core",
 "authors": ["Arduino Team <swdev@arduino.org>;"],
 "repository" : "https://github.com/arduino-org/Ciao",
 "version" : "0.0.2",
 "params" : {
            "port" : 80
             },
 "log" : {
         "level" : "info"
         }
}

The confusing part is that your Arduino has a server client connection on it self from the cpu/linino server to the mcu/arduino client.

https://www.arduino.cc/en/Reference/CiaoRestServer


Sending information via USB/Serialport Am I able to send instruction from my computer, from another compiler, via the Arduino USB port?

To put this in context, I'm doing some vision processing on my computer, with Visual Studio, and I want to send some motor output via USB for the Arduino to execute.

I imagine Code Gorilla's given you the proper, specific answer you needed. I simply wanted to address your first (more general) ask,

  Am I able to send instruction from my computer, from another compiler, via the Arduino USB port?

... and mention some other ways I've done this before. As long the Arduino's listening to the serial port for some specific (or any) input coming in, you can use whatever you'd like to send a message to the COM port your Arduino's using.

You absolutely are not hemmed into using solely the Arduino IDE (or it's serial monitor) for serial communication.

For instance, I wrote a Python script that communicated with an Arduino R3 (Rx/Tx) via the COM port it was assigned via the PySerial library - before coming to Python, I'd been doing this through a MS Visual C# WPF that was connected to the COM port and communicating with the Arduino (Rx/Tx) (you might need to adjust baud rates here or there, if I recall). Just to give you some ideas.

Assuming your project is along the lines of "finding something and pointing at it".

This youtube video shows an eye mounted on a stalk apparently controlled by servo motors (a type of positioning motor).  The title infers an Arduino controls the motors and is in turned controlled by desktop computer running a program making use of OpenCV libraries.  However no details are given.

An Arduino Uno is perfect for controlling servo motors as it contains a dedicated Atmel embedded processor. And there are Arduino servo libraries which make use of the Arduino processor's PWM hardware. This means controlling a servo can be as simple as several line of Arduino sketch code.

myservo.attach(2);  // attaches the servo on pin 2 to the servo object
myservo.write(0);   // sets the servo position to 0
delay(1000);        // waits for a second
myservo.write(90);  // sets the servo position to 90
delay(1000);        // waits for a second
myservo.write(180); // sets the servo position to 180

The USB port of an Arduino Uno normally implements serial port protocol layer inside the USB layer.  Many computers can deal with this easily.  So sending messages to an Arduino Uno is possible.  Here is a project (Arduino Playground - Simple Servo Control tutorial) where a (desktop) computer is controlling servo motors connected to an Arduino over the Arduino's USB port.


Writing C Program outside of Arduino IDE? I like the idea of using the Arduino IDE for simple projects and for getting started with Arduino, but the consensus I've gotten so far is that it is for those who are new to Arduino and/or programming in general.

My understanding is that it is possible to write a C program from scratch, completely outside of the Arduino IDE, and then use a tool like AVRDUDE to upload it to an Arduino MCU. This option, albeit appealing and interesting, leaves me with a few concerns:

What Arduino libraries would need to be imported/linked by such a "raw C" program? I assume that when an Arduino IDE-based program executes a digitalWrite(...) it is really calling a C lib, probably provided by Arduino, under the hood. I am concerned about making sure all these "underlying libs" get included with my C program. Thoughts?
Is anything else "lost" by flying solo and venturing outside the Arduino IDE? Any capabilities/features that I would now have to "roll my own"?

You're absolutely right about needing to link against other libraries. However, you don't necessarily need to worry about all of the details yourself, unless you want/need to do something unusual. Several alternative IDEs already support Arduino, typically via plugins which handle a lot of the details automatically.

I normally recommend Eclipse as it's a very widely used IDE for various purposes. However, there are several other possibilities. See this question for more information:

What are the other IDEs for Arduino?

ESP8266 + Arduino IDE 1.6.4 Portable - Full Quick Install Guide
www.instructables.com/.../ESP8266-Arduino-IDE-164-Portable-F...

All your Arduino IDE v 1.6.4 files, including ESP8266 extension, sketches, installed libraies, etc should be located only under the new created "arduino-1.6.4" folder.


PWM doesn't work with my sketch I have a weird problem. again. This time it's the PWM. I have used PWM before and I used to work the way I am doing it now. But now it just wont work. The Fading sketch from example works. When I compile a code with the similar code it doesn't work. Everything with respect to compilation is same.

The code that works:

int ledPin = 3;    // LED connected to digital pin 9

void setup() {
  // nothing happens in setup
}

void loop() {
  for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
    analogWrite(ledPin, fadeValue);
    delay(30);
  }
  for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
    analogWrite(ledPin, fadeValue);
    delay(30);
  }
}

The code that doesn't work.

#define FAN1 3
#define FAN2 5

void setup() {
  //EMPTY
}

void loop() {
  int speed1 = 25;
  int speed2 = 127;
  analogWrite(5, speed1);
  analogWrite(3, speed2);
  delay(10000);
}

Why doesn't the second code work?

EDIT 1:

By not working I meant No output on Second Code and Expected Output on First one. Currently I'm using ISIS for simulation and Oscilloscope to view the output along with a L239D with motors attached.

In the first code the motor starts and stops as expected, with the expected PWM Waveform.

In second code, nothing. No waveform, no motor movement.

One omission from your code which might be causing the problems is the fact that you haven't set the pinMode. You need to set the pins as OUTPUT in setup()

#efine FAN1 3
#define FAN2 5

void setup() {
    pinMode(FAN1, OUTPUT);
    pinMode(FAN2, OUTPUT);
}

void loop() {
  int speed1 = 127;
  int speed2 = 25;
  analogWrite(FAN1, speed1);
  analogWrite(FAN2, speed2);
  delay(10000);
}

I am curious to know why you declared FAN1 and FAN2, but didn't use them - I'd recommend changing the analogWrite statements to use them instead of referring to the pin numbers directly.

Also, the way you're using the pin and speed means that you're using speed2 for FAN1 and vice versa, I've switched these in my example so FAN1 and speed1 go together.

Because the first analogWrite() is immediately overridden by the 2nd analogWrite().


How to communicate with ESP8266 ESP01 by sending data through softwareserial on Arduino Uno? I am able to send AT commands when connecting to the software through the TX/RX pins (1, 0) and the ESP01 communicates perfectly. However, as soon as I start doing that same thing with code I can't get the ESP01 to respond whatsoever. All I'm trying to do is get an OK back from the serial monitor. I changed the baudrate on the ESP01 as well as my serial monitor from 115200 to 9600, 19200 using this command:

AT+UART_DEF=9600,8,1,0,0

Troubleshooting steps taken:

Tried upping the voltage in case it wasn't getting enough current.
Tried different ESP01s.
Tried switching TX and RX pins.
Tried using different pins on the Uno (2 and 3, 10 and 11, 7 and 8).
tried changing myESP.println("AT"); to myESP.write("AT\n\r");.

Nothing works. I've done a ton of research and I haven't found anything wrong with what I'm doing, do you guys have any ideas?

#define TX 3
#define RX 2
String ssid = "*****";
String password = "******";

#include "SoftwareSerial.h"

SoftwareSerial myESP(RX,TX);

void setup() {
  pinMode(RX, INPUT);
  pinMode(TX, OUTPUT);
  myESP.begin(19200);
  Serial.begin(19200);
}

void loop() {
  myESP.println("AT");
  delay(5000);
}

Schematic is as follows:
TX -> pin 3
RX -> pin 2
Vcc -> 3.3v
GND -> Ground
CH_PD -> Vcc

How about this:

void loop() {
  while(Serial.available() > 0) {
     myESP.write(Serial.read());
  }
  while(myESP.available() > 0) {
     Serial.write(myESP.read());
  }
}

That code will continue to load data to and from the software serial not just one byte. You can also use string concatenation:

String data = "";
while(Serial.available() > 0) {
   data += Serial.read();
}

Or arrays:

int data_max = 4096;
int data_size = 0;
char data[data_max];
while(Serial.available() > 0) {
   if(data_size < data_max) data[data_size++] = Serial.read();
}

RX from Arduino goes to TX on EXP, and
TX from Arduino goes to RX on ESP, BUT

Why not just put ESP01 in program mode and upload adruino code directly to it doing away with the AT commands