NodeMCU 12E V2 Power Saving I'm powering a NodeMCU with 4 x AA batteries (6v, ~9,600mAh).  I am running  ESP.deepSleep([milliseconds]) to minimize power consumption.  Even with deepSleep I am seeing a precipitous drop off in battery voltage.  I've gone from 6.00v to 5.62 in 28 hours.  Does this make sense?  I was expecting the board to consume SIGNIFICANTLY less power and I'm at a loss.

I have the reset/wakeup pins (D0, D3, and D4) set connected to 3.3v with resistors and I've jumped the reset pin to D0 to make the wakeup call.  Nothing else is connected!  Does this power draw make any sense??

As far as the operation goes, it's waking up and posting data just fine.

I've researched various power saving techniques and the best description I've found is here.  I really don't want to start hacking up ESPs though.  That is time consuming and presents a real opportunity (ahem...guarantee) for me to destroy a lot of boards!

My questions:
1.) Are there other SW-based methods for improving power use on the NodeMCU 12E?
2.) Where do I probe a 12E to read current draw with a multimeter
3.) Are there "dumber" ESP8266 modules that have a reset pin, a few? GIPOs and a VIN capable of handling a 6v input with either a 5v and/or 3.3v output?  Product recommendation...I know...I'm hard up though and need some guidance.

I'll make these separate questions if necessary.

I am going to by an in-line current reader.  I need to stick with a multimeter for now.

If you can't do anything about the hardware you're using (lower powered USB interface, etc) then the top thing you can do is run the wifi radio as little as possible. The radio uses a lot of power, so the less time it's on for and the less network traffic you send, the less power you'll use.

When the board comes out of deep sleep and reconnects on wifi again, it performs a DHCP exchange to find out its IP address. Configuring a static IP address, network mask and router address will avoid this and let the radio stay on for less time.

The ESP8266 SDK also automatically saves wifi credentials to flash every time you call WiFi.begin(). This is probably not what you want. Disabling this will also help save power.

The new wifi connect code would look something like this:

IPAddress ip( 192, 168, 0, 1 );
IPAddress gateway( 192, 168, 0, 254 );
IPAddress subnet( 255, 255, 255, 0 );

WiFi.forceSleepWake();
delay( 1 );
WiFi.persistent( false );
WiFi.mode( WIFI_STA );
WiFi.config( ip, gateway, subnet );
WiFi.begin( WLAN_SSID, WLAN_PASSWD );

You'd need to replace the specific IP address, gateway (router) address and subnet mask with ones that work for your network. And you'll need to allocate a static IP address either from a range that your router sets aside, or you'll need to configure your router to permanently allocate the address - how you do this totally depends on the router you're using.

The other way to save wifi-related power is to use as lightweight a protocol as possible and do as little work while wifi is on as possible.

For instance, suppose you need to compute a complicated piece of data that you're transmitting over wifi. Maybe it's a chunk of XML or a JSON string. Or you need to read a slow sensor. Do all that work before you enable wifi, and have the data ready to transmit.

Or if you're receiving data, if at all possible, finish receiving the data and turn off wifi before you do any work with the data.

If you have any choice in the matter, use as simple a protocol to transmit the data as possible. UDP is ideal - you can transmit a single packet (but you won't know if it's been received). TCP requires several packets of handshake at connection startup and shutdown. If you use a secure (SSL) connection over TCP that's even more data and computation.

If your very top priority is battery life, UDP is ideal though it's not reliable and not secure.

There's a great series of articles on power saving at

https://www.bakke.online/index.php/2017/05/21/reducing-wifi-power-consumption-on-esp8266-part-1/

https://www.bakke.online/index.php/2017/05/21/reducing-wifi-power-consumption-on-esp8266-part-2/

https://www.bakke.online/index.php/2017/05/22/reducing-wifi-power-consumption-on-esp8266-part-3/

Part 1 is about measuring power use; part 2 is about switching the wifi radio on and off and part 3 gets partly into the stuff I talked about above.


Developing Standalone Arduino GUI Controller I am rather new to using an Arduino.
As a part of my Graduate-Level Chemistry research, I am trying to further the development of a cheap DIY, open-source, Flow Chemistry Syringe pump system.

The device utilizes Stepper Motors, Step Motor control boards, an Arduino Uno, and a 3D printed Pump frame. Simple code was previously developed using the Arduino IDE. I have expanded on this a bit to allow for more customization (syringe size, mostly). The limitation here, is that the Serial Monitor inputs will be taxing to the users. I need to develop a simple GUI that allows for all of the inputs I need (syringe size, flow (step) rate, start and stop functions, etc.). I need this gui to be a standalone application that can be easily shared (no need to download anything extra, no installations, deploy-able on at LEAST Win and Mac).

Our labs goal is to develop a system that is easy to use and distribute, reducing the costs associated with using Flow Chemistry. I have a decent understanding of Arduino IDE, and I am willing to learn whatever I need to make this work.

I have seen a few things about Python, and 'Processing', but they seem to require the simultaneous use of Arduino IDE which would make deployment too complicated.

How should I approach this? What language do I need to learn? What advice do you have?

The Uno is connected to the PC with a Serial interface (emulated over USB). The program on the PC only sees the Serial interface. It is not important, if there is really an Arduino at the other end. Nearly every programmung language can be used for interfacing a Serial interface, each gives advantages and disadvantages. But you will not have a single portable program file, that you can start on different OS without installing anything. Either you need to compile the program for each OS individually, or you can use a portable programming language, where you first need to install it's framework on the OS (for example python).

I would propose a different solution (that I'm currently also working on): Depending on your lab situation you could extend your project with a network interface, either Wifi or LAN. Then you can present a webinterface to the user. When writing HTML/javascript websites, it is easy to have them display correctly on most mayor browsers.

That way the GUI is really independent from the OS. For adding the network connection, you could use a LAN shield, Wifi shield, or directly change the microcontroller from an Arduino Uno to an ESP board, which has Wifi build in and is also has more computation power and memory.

The webinterface can be interactive by the use of javascript (since you cannot run php or similar on the Arduino or ESP).

Wether you want to use a companion application, that you write for the PC, or a webinterface is up to you and depends on your exact lab situation.


Reading sensor data, massaging it and performing operation based on transformed data This is the outline of my project:

interpret environment data (sensor, motor, etc..).
Modify this data into a more usable form,
send it back to the same motor for further operation from modified data.

As an example (this is not the project, but just an example to make sure I am being clear).

A motor moves a conveyor belt with various size flasks on it, some large other small. Depending on the reading of the position of the motor (from encoder) another process (filling the flasks) will take place.  If the first motor encoder data indicated the flask was small then the amount of liquid poured will be small. If large, the amount of liquid dispensed will be large.

More generally, read the location of an item based on motor encoder feedback.  Modify this data. Send this modified data back to a different motor so that it does something specifically as a function of the first motor encoder data.

I am able to send the original encoder feedback to a file, manually massage it and paste it into an Arduino script, compile and have everything work great. I just want to remove the manual steps (cut & paste) and data massaging (I'm looking to an Arduino program to do that).

To further complicate things, I want this process to be part of a distributable package that does not require further compiling. Reading from a sim card is fine.  Also, I am not too price sensitive as the Arduino is a small portion of the total cost of the final product.

I hope someone can give me some insight or pathway to a solution.
All the very best, John.

Here's a back-of-envelope sketch, off the top of my head:

Conveyor belt driven by stepper motor, controlled by the Arduino.  Each step is a known distance.

Bottles are either of exactly two heights, at random.  Two beam break sensors, one to determine where a bottle starts and one to determine whether it's tall or short.

Some sort of valve to control the water flow - I presume you have some idea how this can be controlled.  I don't, but washing machines have electrically-controlled valves so something broadly along those lines.  Controllable on/off by the Arduino.

Software on the Arduino steps the motor until it sees the start of a bottle (first beam broken).  Then uses second beam to determine whether the bottle is large or small.

Arduino switches on the water valve (outlet positioned exactly right to be above the bottle) for either 2s or 4s accoriding to bottle size, then off again.   (Water pressure and flow rate regulated independently, perhaps fed from a header tank).

Arduino steps motor more until it sees another bottle.

No string concatenation in there, nor sorting of lists or need for a Raspberry Pi.  It's not clear to me why you'd need those things for the application described.

I'm not aware that you can program the Arduino in Python unfortunately.  Someone may know better.  C isn't hard though - get an Arduino and some LEDs or whatever, go through some tutorials, you'll get the hang of it.


Changing Text Arduino inkShield I have just received inkshield purchased from Nerd Creation Labs, I stacked inkshield on my Arduino Mega and uploaded THIS CODE provided by the creator of inkshield,and it works pretty well.
I can print text ;)

Questions :

1: The code given above can only print text in a single Font. Can i add multiple Fonts in a single code.?

2: How can i change the Font to something like Times New Roman, Arial,calibri or more stylish Fonts like snell RoundHand and Zapfino.?

Please help

Thank you

The fonts are the little bitmaps starting at line 50. Each 16 bit value is 1 column of the letter to be printed. There are 10 columns of pixels per character (the rowsPerChar value). The least significant bit is the bottom row.

So to change the font all you need to do is change those bitmaps.


how to solve Varing duty cycle value while using Pulsein() Well im new to coding, but i do have the basic knowledge.
I'm using an UNO to measure a duty cycle.
The source of pulse is a Tektronic signal generator (Duty cycle set to 50.000 with frequency of 2khz).
my code is as follows,

byte PWM_PIN = 3;
float pwm_value_H;
float pwm_value_L;
float D;

void setup() {
    pinMode(PWM_PIN, INPUT);
    Serial.begin(115200);
}

void loop() {
    pwm_value_H = pulseIn(PWM_PIN, HIGH);
    Serial.println(pwm_value_H);
    pwm_value_L = pulseIn(PWM_PIN, LOW);
    Serial.println(pwm_value_L);
    D = ((pwm_value_H) / (pwm_value_H + pwm_value_L)) * 100.0;
    Serial.print("D=");
    Serial.println(D);
    Serial.print("D=%");
}

but the problem is that my output value of "D" keeps on varying between 49.71, 49.90, 50.00 and 50.7
Is this because of PULSEIN() function ineffiency?
or can anyone suggest a better way to measure the duty cycle with +/- 0.01 accuracy.

Regards,
Cj

I would start by removing Serial interrupts from the pulseIn period.

void loop() {
    pwm_value_H = pulseIn(PWM_PIN, HIGH);
    pwm_value_L = pulseIn(PWM_PIN, LOW);
    Serial.println(pwm_value_H);
    Serial.println(pwm_value_L);
    D = ((pwm_value_H) / (pwm_value_H + pwm_value_L)) * 100.0;
    Serial.print("D=");
    Serial.println(D);
    Serial.print("D=%");
    Serial.flush();
}

For higher accuracy I would then look to the Timer based Input Capture.

Cheers!


TX,RX,ON,l LEDs were red at all time First of all Thank you for reading my broblem.Before coming this erro I did a project in my Uno board by using a Bluetooth module.after that; when I powered the board to uploade another programe ;4 LEDs (l,tx,Rx,on) were went red without blinking.so now ,at the all time when I powered my Uno board without any connection with any of pins previously mentioned 4 leds were red coloured at all the time.looking for quick response.

If you can upload sketches, I don't think it is that big of a deal but if you can't, check the TX and RX pin tracks since if those tracks are shorted, they can keep the indicator lights on for ever due to the Serial code on the Arduino. To get further help, please tell me what happens if you try uploading code.


Digital Reading from a array without using the exact element Is it possible to read a digital input from an array without using the exact element? Such as

   while(digitalRead(myButtonArray[i]))
     digitalWrite(myLEDArray[i], HIGH);

Reading the myButtonArray one by one and turning on the led one by one doesnt make for clean written code. The following is just an example code. When button on pin 2 which is element 0 is pressed turn on led on pin 7 and turn off when released. When button on pin 3 is pressede turn on led on pin 8 and turn off when released and continue on in the same fashion with the rest of the buttons and leds as well.

 int myButtonArray[] = {2,3,4,5,6};
 int myLEDArray[] = {7,8,9,10,11};

 void setup() {
   for(int i = 0;i<5;i++){
     pinMode(myButtonArray[i], INPUT);
     pinMode(myLEDArray[i], OUTPUT);
   }

 }

 void loop() {
 while(digitalRead(myButtonArray[0]))
      digitalWrite(myLEDArray[0], HIGH);

 while(digitalRead(myButtonArray[1]))
      digitalWrite(myLEDArray[1], HIGH);

 while(digitalRead(myButtonArray[2]))
      digitalWrite(myLEDArray[2], HIGH);

 while(digitalRead(myButtonArray[3]))
      digitalWrite(myLEDArray[3], HIGH);

 while(digitalRead(myButtonArray[4]))
      digitalWrite(myLEDArray[4], HIGH);
 }

In your question you wrote

  and turn [the LED] off when [the corresponding button is] released

and yet you never turn the LEDs off in your code. Then, I assume the
code in your question is irrelevant, and you just want the LEDs to show
the states of the buttons at all times. This can be done by writing to
the LEDs the values you read from the buttons. Do this for each
button/LED pair, and loop over the pairs:

void loop() {
    for (int i = 0; i < 5; i++)
        digitalWrite(myLEDArray[i], digitalRead(myButtonArray[i]));
}


control Arduino board using Android sensors and wifi? i am thinking about building a Quadcopter that can be controlled with a computer via Wifi . but the problem is that with a lack of components and limited resources , i have been thinking of using my available components ( Arduino uno + smart phone + quadcopter frame with 4 brush-less motors and 4 speed control )
so i am asking you guys if it is possible to read smartphone sensor values using Arduino usb and control the quadcopter using smartphone wifi ??

Is it possible?  Yes, it's certainly possible.  You can read the sensor values from within an Android program. It's possible to get Android to communicate with the Arduino through the USB.  The Arduino can be programmed to respond to what it gets through the serial.

Is it easy? Well, that depends on how good you are at Android programming.

One good place to start might be the ArduinoFirmata-Android project.  Don't worry about programming the Arduino, just install Firmata on it.  Then it's all down to how you program the Android device.  The Arduino just becomes a peripheral to your phone.


Having issues with Arduino + Bluetooth I am working with a combination of Teensy++ 2.0 and Sparkfun Bluetooth Modem.

The Arduino program, inside the loop, continuously reads a sensor value. If the value read is above a threshold, the Arduino transmits a "CHARACTER" over Bluetooth for any receiver.

So, inside the same loop, I check for the availability of data, and print the received character. The problem is, the received character is not what is transmitted. The received character is some garbage value.

Please let me know what is going wrong here.

#include <SoftwareSerial.h>

#define bluetooth Serial1

#define BAUDRATE 9600

// Analog read 0 is pin 38
int sensorValue = 0;
int SENSOR_ANALOG_READ_PIN = 0;
int LED = 17;

char toPrint = '\0';
bool sent = false;
char state = ' ';

void setup()
{

// put your setup code here, to run once:

  pinMode(LED, OUTPUT);

  Serial.begin(BAUDRATE);

  bluetooth.begin(BAUDRATE);

}

void loop() {

  // put your main code here, to run repeatedly:

  sensorValue = analogRead(SENSOR_ANALOG_READ_PIN);

  if(value > 500)

  {
      //Serial.println("HIGH");

      digitalWrite(LED, HIGH);

      bluetooth.write(state);

      bluetooth.flush();

      sent = true;

      digitalWrite(LED, LOW);

  }

  else

  {

      delay(100);

  }

  ///////////////////////////////////////////////////////////
  if((bluetooth.available()) && (sent == true))

  {

        Serial.println("printing : ");

        toPrint = (char)bluetooth.read();

        Serial.println((char)toPrint);

        sent = false;

   }

}

Output:

printing :
1
printing :
ˆ
printing :
Ì
printing :
¦
printing :
È
printing :
Ì
printing :
Ì
printing :

Is the device on the other side of the bluetooth connection running at 9600 baud too ?

You say you transmit the state of the sensor - which BTW is only ever a space ' ', and never changes.

So that value gets written out via the bluetooth connection.

But then you read data in from the other party to the bluetooth communications.

It sounds like you expect the data written to the bluetooth output serial line to also be echoed back from the bluetooth input.  The serial transmit and receive are separate channels.  You are receiving on the bluetooth.read() whatever the device connected to it is sending, not what you write yourself.

What you are sending goes only to the other side of the conversation.  The remote device would need to echo whatever it sees back for it to work how you describe.


Is it possible to use LCD (the 16 pins) without potentiometer? look, I don't have any potentiometer lying around, and I don't have any variable resistor.
So is it possible to instead use a fixed resistor for the LCD display ?

Sure. You can use two resistors in series to be a "fixed value" potentiometer.

The "wiper" of the potentiometer is the junction between the two resistors.

I can't tell you what values to use, so you'll have to experiment. You want them to add up to somewhere in the tens of kilo-ohms though, ideally, though the value isn't that critical - it's the ratio between the two values that is of interest, and it's that which gives you your contrast setting.


Is the Uno Vin pin protected by the voltage regulator? I guess it's all in the title. When using Vin as input, does it go through voltage regulator, or must I feed it precisely 5V?

If you look at the schematic you'll see Vin is connected to the input of the voltage regulator. Just like the barrel-jack (except for the diode).

So the same input-voltage of    7-12V applies to Vin.


Arduino to breadboard with LM35 temp sensor I have moved the MCU of the Arduino to a breadboard using these steps https://www.arduino.cc/en/Main/Standalone then interfaced it with an LM35 temperature sensor to the ADC0. But I can't get proper values from the LM35. I think it's because of the Aref or AVcc. Both are just connected to +5?
Here is my code:

float tempC;
float reading;

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

void loop()
{
    reading = analogRead(0);
    tempC = (reading * 0.4882815) + 5;
    Serial.print(tempC);
    delay(1000);
}

I get hex values and sometime high values. What to do with Aref and AVcc?

EDIT: I get values like these
€
Œ

Check the baud rate of your serial monitor matches what you have set in your setup() function.  In the above code that is 9600.  If the baud rate is incorrect you typically get rubbish output in the serial monitor.

You may also want to change the Serial.print(tempC) to

Serial.println(tempC,2);

To get some decimal places.

As for the circuit ~

You don't need ARef connected.
The LM35 VCC should be connected to Arduino 5V
The LM35 GND to Arduino Gnd (any of them)
Finally LM35 signal (Vout) to Arduino A0.


Typing into ESP8266 with a USB keyboard I need to be able to connect a USB keyboard, like a tiny Xbox keyboard, or a nice wireless one, into an ESP8266-based thing to type passwords into the MCU. Adapting the PS2 lib for AVRs (PS2==USB pinouts for KBs) proved unreliable, so I tried a fake Pro Mini.

It worked much better, perfect with PS2, but only with a subset of my USB keyboards, namely a 104 Das Keyboard and an old-school Dell one. My 2002-era Mac keyboard doesn't work, none of my 5 wireless keyboards work, and neither do Xbox or foldable keyboards. Nothing that presents as a composite device works (like a keyboard with USB slots), only dead-simple (no fancy keys/knobs) keyboards seem to work.

Would a USB host module (like the Uno shield, but not a shield) let me read from more than just basic PS2-emulating USB keyboards?
Is the code to read basic alphanumeric keys consistent among different keyboards, or will each model need special instructions? (much like a driver would provide an actual OS)
If it's anything but "plug and play", what would be a simple way (no soldering) to securely input passwords into an MCU?

EDIT:

Early USB keyboards and PS2 keyboards have the same pinout and behavior, so you can use a Pro Mini and the Arduino ps2keyboard demo to read such USB keyboards, either with a passive USB keyboard to PS2 male adapter for less than $1 USD, or via a female USB wired the same. Fancier keyboards don't work as such, at all, hence the possible need for a USB host module.

My 2002-era Mac keyboard doesn't work,

That doesn't surprise me - modern Macs have never needed PS/2 support.

  none of my 5 wireless keyboards work,

That's because they're not keyboards, they're wireless transceivers that provide USB HID interfaces.

  and neither do Xbox or foldable keyboards.

Too modern, and of course XBox has never needed PS/2 support.

  Nothing that presents as a composite device works (like a keyboard with USB slots), only dead-simple (no fancy keys/knobs) keyboards seem to work.

Of course, they aren't PS/2 keyboards, they're USB devices.

Older keyboards provided dual operation - USB and PS/2. This is a function provided by the keyboard, not the USB standard. Mac keyboards, since the Apple computers never had PS/2 ports (since PS/2 is an IBM standard from the PS/2 computers back in the 80s & 90s). Modern keyboards that provide more than just a simple keyboard functionality cannot really provide PS/2 as well since that can't provide the other features of the keyboard. The same goes for composite devices, or wireless devices - they facilities they provide are in excess of what PS/2 can provide, so it would be illogical trying to provide PS/2 support - especially as PS/2 ports are getting rarer on computers now.

  Would a USB host module (like the Uno shield, but not a shield) let me read from more than just basic PS2-emulating USB keyboards?

Sure, if you can get the libraries working on the ESP8266, which may well be a huge challenge in- and of itself.

  Is the code to read basic alphanumeric keys consistent among different keyboards, or will each model need special instructions? (much like a driver would provide an actual OS)

All USB keyboards are class-compliant HID devices. They send HID reports in a standard format, maybe with custom additions. The basics are always the same though.

  If it's anything but "plug and play", what would be a simple way (no soldering) to securely input passwords into an MCU?

It'd be far from "plug and play" getting a USB host interface working with the ESP8266.  Consider other more simple routes, such as using serial, or configuring the ESP8266 as an access point and using a web browser to configure it.


HC-06 RX pin usefulness I have a HC-06 bluetooth module. The module has an RX and TX pin (the RX pin receives data and TX transmits data) which connect to the TX and RX pin of an Arduino respectively (in my case an Arduino pro mini).

My question is in what scenario would someone use the RX pin of the module(basically for what purpose would the bluetooth module receive a signal from the Arduino)?

For example let's say i have a simple LED that i turn off and on. I just sent the signal from my phone to the module and the module sends the signal to the Arduino. So basically i've connected the TX pin of the module (which transmits the data) with the RX pin of the Arduino (which receives the data).

In order to connect the RX pin of the module with the TX pin of the Arduino i have to use a voltage divider as the module only accepts 3.3 volts of signal while the Arduino transmits 5 volts of signal. I want to avoid that because in my project i need the PCB to be quite small.

So if someone only wants to transmit data from the module to the Arduino, is there a reason on why would he connect the other two pins?

If you never want to change the configuration of the module either, then no, you don't need to connect the module's RX pin.

However many people want bi-directional communication. Not only the ability to send a signal to turn the LED on or off, but also the ability to get the current state of the LED - is it on or off?

Or maybe to send an analog reading. Or the data from some sensor.

The HC-06 is a bi-directional module. If you choose to use only one direction then you only need to wire in one direction. However, tie the RX pin to 3.3V with a 10KΩ resistor to stop it floating and consuming extra power or causing random noise to be transmitted to your phone.

In fact, it's just like a phone. You can call someone up and just speak to them without listening to what they are saying. That's fine if all you want to do is call Mom and say "Pick me up in 5 minutes" and hang up. But if you want to ask your Mom "Can you pick me up in 5 minutes?" you have to actually listen for her answer "No, walk home you lazy oik!".


Connecting CAT5 robustly between portable Arduino and more portable sensors Newbie wiring question. I’m building a lightwand of some sort, involving an RGB LED and a few pushbuttons that I want to wave around (the “remote”), while staying connected over ~0.5 - 3m to an Uno (the “head”).

In a portable incarnation, the remote might be on your finger and the battery-operated head in your backpack. I’m hoping to use stranded CAT5 for the connection between them (“the bridge”) — it’s the right number of conductors, good flexibility, I have lots of it.

My question is: how should I best mate the CAT5 to both ends — pins on the Arduino at the head, and pins or bare wire off my LED and switches at the remote?

At the head, I like the idea of an RJ45 jack (“NOT ETHERNET”), both for modularity and as I’m a bit worried about strain on the cable pulling wires out of Arduino pins. (The jack basically gives me a good interface at the enclosure level.) I could get an RJ45-to-wiring-terminal-block, and then run solid jumpers from the block to the pins, but they’re expensive. I could try a keystone jack and just try using solid jumpers rather than more CAT5 going between the jack’s wire-breakout and the Arduino board — but I worry the jumpers won’t be the right “size” for the jack, and I’m worried about flimsiness. (If the entire head enclosure is in your backpack, it’s going to get jostled. I want something durable.)

I see some examples of an RJ45 jack soldered directly to a board. What sort of RJ45 is that, and could I do that and solder straight to the board pins on a cheap shield, with relatively novice soldering skills? Or is this at risk when people yank the cable inadvertently?

As I said: I’m a newbie, don’t know what’s reasonable, and keep coming up with overcomplicated architectures where the CAT5e connects to a jack to a block to jumpers to pins,  etc. etc.

At the remote, I think I’m better off. Things need to be as small/portable as possible, so I think I bring the bare stranded wire out of the CAT5e onto a tiny bit of board, and just solder the strands directly to the leads coming off my buttons and LED, and wrap some tape around it, then attach the whole thing to a glove or a bracelet to keep it relatively immobile at the end of the cable. Ok or terrible?

Thanks for suggestions, directions, and other help. I’ve looked around and don’t see questions at this level of ignorance. One of the answers to this mentions that “people wire a RJ45 sock directly to an Arduino” (my head problem) but doesn't say exactly how.  How can I attach sensors without a shield for a wearable project? is doing what I want, but also underspecified...

Certainly go for RJ45 sockets.  Not only does it help protect the wire, but it gives you a really easy way of swapping the wire for different lengths should you want to.

You can't solder an RJ45 socket directly to a normal prototyping board. The pins aren't in the right pattern.  So, you could go for something like this

That can then either be soldered to wires or, since the pins are now in a normal 0.1" pitch, solder the whole module to a prototype board or shield.

Be sure you get a vanilla RJ45 socket, not a "MagJack", which contains extra Ethernet-specific electronics inside it.

If you do want to solder the wires directly to a PCB simply drill a couple of holes just in from one edge of the PCB, run the cable between them, and strap a cable tie around it.  Here's an example:

That PCB has specially shaped slots designed into it for the cable tie.

Also, for soldering, you want a good quality cable. A cheap one from eBay will most likely be made of aluminium with a thin plating (if you're lucky) of copper. A better quality one will be made entirely of copper. Aluminium cables don't solder well. Fine for crimping to an RJ45 plug, but rubbish for soldering.


Moisture sensor data will not output data to Serial Monitor? I am making a Soil Analysis system with an Arduino Uno, but I have run into a problem and was wondering if /r/learnprogramming could help!

The moisture sensor section of my code will not output the data to the Serial Monitor in Arduino 1.7.1 IDE. I am not sure why it's not working. Running the moisture sensor code by itself works, and I just copied and pasted that code into my combined code file since I'll I am running 4 sensors at once with my Arduino Uno.

These are the four values I need to output data on one baud rate:

pH value
EC
DHT temperature reading
Moisture Sensor Value
I am currently missing Moisture Sensor Value when I run Combined1.ino

Here is the Combined1.ino code of the code from four sensors together that's uploaded to the Arduino:
Combined Code Link
Moisture Sensor Link

Any help would be much appreciated!

Your second print section will always fail.

You have:

if(millis() - printTime > printInterval)   //Every 800 milliseconds, print a numerical, convert the state of the LED indicator

However, a bit before then you have:

if(millis()-printTime>=printInterval)
{
  printTime=millis();

So millis() - printTime can never be greater than printInterval since you have just set printTime to millis(). So millis() - printTime will always be somewhere between 0 and printInterval - 1.

Consider combining your different printing routines into one single printing routine so you are comparing (and changing) the printTime only once.


Connect arduino nano and ESP32 with I2C on the GPIO7 and GPIO8? I made a mistake connecting SD0 (GPIO7) and SD1 (GPIO8) with the SDA and SCL on my arduino nano. I got confused with GPIO21 and pin21 and GPIO22 and pin 22!

Since I made a PCB prototype, I would avoid to add some wires and cut the traces, so I would ask if I could use these pins (GPIO7 and GPIO8) as SDA and SCL.

If the answer is affirmative, using Arduino library how could I assign them?

Wire.begin (7,8)?

Another question, I would use a dedicate 2x4.7K pull up resistors. On the arduino side I wrote:

digitalWrite(SDA, 0);
digitalWrite(SCL, 0);

It is correct to do the same thing on the ESP32 side?

Update November 01:
After the question from Majenco I think I need more help for the I2c setup.

I designed the PCB having in mind that the esp32 was 5V tolerant, so at the moment I pull-up the SDA, SCL from the 5V that I input in the esp power pin. Note that this 5V doesn't come from the Nano due to the high current required by the esp. I take my 12V power supply input and regulate it to 5V with a 7805, only dedicated to the esp (I know, a lot of dissipation! In the next PCB version I have to change the things, having in mind that I need both 12V and 5V in my circuit).

Now, I read that the esp32 is not 5V tolerant. In order to avoid level shifter can I pull up the SDA and SCL from the 3.3V line (the arduino 3.3V or esp32 one?)?

I would use the esp32 as master.

Thanks.

Since I made a PCB prototype, I would avoid to add some wires and cut the traces, so I would ask if I could use these pins (GPIO7 and GPIO8) as SDA and SCL.

No, you can't. Those pins are used by the internal flash chip. If you connect things to them you will end up not being able to read the flash and thus won't be able to run any code.  In other words, the chip will not boot. So you will have to bite the bullet and cut traces and add bodge wires.

  Wire.begin (7,8)?

Yes. That will control the bus matrix to route the I2C through different pins - but of course you can't use those pins, as noted above.

  On the arduino side I wrote:

  digitalWrite(SDA, 0); digitalWrite(SCL, 0);

  It is correct to do the same thing on the ESP32 side?

No. That exploits a quirk in the AVR GPIO system that doesn't exist in the ESP32. In the ESP32 the pins are configured with:

pinMode(sda, OPEN_DRAIN | PULLUP | INPUT | OUTPUT );

and

pinMode(scl, INPUT | PULLUP);

so you could try replicating that in your code but without the PULLUP flag. However the effect of this is unknown, so YMMV.

However, if your external pullups are pulling up to 3.3V then you really don't need to do anything on the ESP32. All you end up with is a large resistance in parallel with your 4.7kΩ, which will just cause your resistance to drop slightly (and since 4.7kΩ is arguably too high any way that's a good thing).


Cannot read from 2 I2C slaves consecutively I am currently trying to communicate between 3 Arduinos using I2C. One of them acts as a master, while the rest act as slaves.

I can request data correctly from the master. But if I were to do 2 consecutive requests, I will only get data for the last request. Please assist.

Master:

#include <Wire.h>

#define BLUNO_SLAVE 0x09
#define BLUNO_SLAVE_2 0X0A

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Serial.println("Initialized as Master");
  Serial.println("Reading from slave 1 now..");
  //Wire.beginTransmission(BLUNO_SLAVE);
  Wire.requestFrom(BLUNO_SLAVE, 25);  //char occupy 1 byte
  //Wire.endTransmission();
  Serial.println("Reading from slave 2 now..");
  Wire.requestFrom(BLUNO_SLAVE_2, 30);
}

void loop () {
  while(Wire.available()) {
    char c = Wire.read();
    Serial.print(c);
  }
}

Slave 1:

#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin(0x09);  //slave address
  Serial.println("Serials initialized");
}

void loop() {
  Wire.onRequest(returnData);
}

void returnData() {
  Wire.write("received master's request");
}

Slave 2:

#include <Wire.h>

void setup() {
  Serial.begin(115200);
  Wire.begin(0x0A);  //slave address
  Serial.println("initialized!");
}

void loop() {
  Wire.onRequest(returnData);
}

void returnData() {
  delay(60000);  //60 * 1000 = 60 seconds
  Wire.write("Lat: 103.123456, Lon: 1.098765");
}

Output on the master:

Initialized as Master
Reading from slave 1 now..
Reading from slave 2 now..
Lat: 103.123456, Lon: 1.098765

On top of that, I do not understand why the 1 minute delay was not executed before the slaves write the GPS coordinates.

I figured out from http://playground.arduino.cc/Main/WireLibraryDetailedReference
that each call to the requestFrom() method, RESETS the read buffer. I looked at my code back and I saw a silly mistake on the master code. So, I corrected the master code:

#include <Wire.h>

#define BLUNO_SLAVE 0x09
#define BLUNO_SLAVE_2 0X0A

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Serial.println("Initialized as Master");
  Serial.print("Slave 1: ");
  Wire.requestFrom(BLUNO_SLAVE, 25);  //char occupy 1 byte
  readData();
  //each call to requestFrom, RESETs the read buffer index
  Serial.println();
  Serial.print("Slave 2: ");
  Wire.requestFrom(BLUNO_SLAVE_2, 30);
  readData();
}

void loop () {
}

void readData () {
  while(Wire.available()) {
  char c = Wire.read();
  Serial.print(c);
 }
}

But still, I don't understand why slave2 writes the data immediately instead of waiting for 1 minute?

I recommend you to just set a semaphore inside your handler. When your handler is called, set it, nothing more. In your main loop, poll for this semaphore and do your communication when true. When you receive this semaphore you can easily wait as long as you like without breaking interrupt handling. As interrupt service routines should always be as short as possible, both in terms of time and code, it is generally a bad idea to do complex communication from within or wait for something.

And don't forget the "volatile" keyword for your semaphore.


Arduino Button interference With a push button on an Arduino (or Raspberry Pi), instead of wiring a high voltage (5v) through a button and to a pin to read the input, you often want your input pin set to HIGH (high impedance) and wired through a switch to ground to avoid interference like EM waves. My question is what exactly does setting the input pin to HIGH do (besides making it high impedance)? Does it make the circuit less sensitive to EM interference? I like to understand more of the physics behind circuit design.

In Arduino, just setting the pin as input already makes it high impedance.
Writing HIGH on an input pin actually enables its internal pull-up resistor.
This way, the voltage at the pin is always defined (instead of floating when the switch is open).
Just search for "pull-up resistor" if you need more information.
Note that this code:

pinMode(n, INPUT); // set as input, high-impedance
digitalWrite(n, HIGH); // activate the internal pull-up resistor

is equivalent to this (in recent Arduino IDEs):

pinMode(n, INPUT_PULLUP)


Connect Arduino Uno RX/TX to 3.3v NEO-M8N gps module I'd like to connect an M8N gps module to an Arduino Uno. From what I understand

the Arduino pins 0-RX/1-TX work on 5V
the M8N RX/TX work on 3.3v
the sensor-TX sending to the Arduino-RX should work (3.3v is “good enough” to drive the Arduino-RX-pin)
the Arduino-TX sending to the sensor-RX is problematic because of the 5v (could break the sensor)
During USB-programming, the Arduino-RX sensor can be at 5v (so suddenly the current flows in the "wrong direction"- which could break the sensor)
A level-converter could be used to “translate” the voltages in each direction.

Assuming we don’t use a level-convertor

Could we use a schottky-diode (which as I understand blocks current in 1 direction) to block the 5V from the ArduinoRX going into the sensor?
But then the 3.3V from the sensor-TX would pass (correct direction ), but the diode will drop the voltage "a bit more"… is this still enough to drive the arduino RX-pin?
And it works, why not also use a schottky-diode to also protect the Arduino-TX to sensor-RX connection ( just to be safe, since some people were saying one some Arduino they needed to connect RX-RX and TX-TX to get the communication to work.. ? ).

As an alternative to the schottky ( or maybe in addition to it)
- Could we simply take 2 voltage dividers (for one for both RX-TX and TX-RX) ?

We can use a “resistive voltage divider” to lower the Arduino-TX 5v to 3.3 V
- I understand to get from 5V to 3.3V we need “x” and “2 * x” resistors-values, so e.g 1K Ohm and 2K Ohm… but how do I know which values would be appropriate ( I mean, we could also take 10K Ohm and 20K Ohm, would also lead to 5V to 3.3v) but at a different current (Amps)… ?

And what about a voltage-divider with a resistor and a capacitor (see https://en.wikipedia.org/wiki/Voltage_divider, low-pass RC filter)?
What would be appropriate values for that solution for the resistor and capacitor?

Please be patient, electronics-beginner here trying to make sense of this…

Buy some of these, it's a simple hardware solution to your problem then.

https://www.amazon.co.uk/gp/product/B0148BLZGE/ref=oh_aui_detailpage_o01_s00?ie=UTF8&psc=1

I know you said you don't want to use a level converter but it's the simplest way around the problem.
You stated that you're an electronics beginner AS AM I, which is exactly why when I came up against the same problem i just spent the money.
It was only £3.99 for 5 of them and as far as I'm aware you should be able to buy single ones off amazon too, haven't searched but i'd have thought you'd be able to.

Or if you need to do it with resistors you can use this calculator here

http://www.ohmslawcalculator.com/voltage-divider-calculator


External 5V Power and USB Serial I have a Chinese Arduino nano clone, but I don't know if it's possible to connect the Arduino to external (5v) power and have a USB serial connection ongoing. I'm trying to make a PC controlled LED Strip that can also work on its own.

For example: the PC controls the Arduino sets it to a specific mode and I turn off the PC, but the Arduino should still be running even when the PC is turned off.

I'm new to the world of arduinos.

I'm planning to use this to control addressable LED RGB Strips and am planning to use a 4000mA max power supply.

Having used counterless Arduinos and clones, I can tell you that you can connect both without worrying about any danger. Unless you have a very faulty board, your pc won't be damaged, almost surely neither will the board, as is should select the most powerful source, between your usb or a battery/external PS, while leaving untouched the serial line.


Choosing wireless tech for lowest possible lag I am drafting a pub quiz project, where the Referee gives a signal and multiple players push their buttons. The first to push wins the right to give an answer.

I want all buttons (referee's + X players) to be wireless. Since the best quiz players can click a button within 10ms of the signal, it is very important that there is a very, very little variance in ping between different buttons. I cannot have players shouting "my button is laggy!" On the other hand, I don't want to use more expensive/complex tech than needed.

SO, what would be the optimal wireless tech to use? Please share your experience from similar projects (or just theoretical knowledge :) Here's what I researched so far (correct me if I'm wrong):

Bluetooth 4 LE (as in RFduino)
Pros: 3-6ms latency (advertised), low energy
Cons: cost, not more than 7 buttons to the device
Wi-fi
Pros: 2ms latency (I justed pinged my wi-fi router), dozens of buttons if need be
Cons: cost, power-hungry
RF data tranceiver
Pros: dunno, cost seems to be a bit smaller
Cons: multiple buttons at the same frequency will probably create a lot of noise
Simplest "Radio remote"
Pros: zero lag since it's all electromechanical, no data
Cons: multiple buttons at the same frequency won't work

So, did I miss anything? I appreciate any guidance.

I've used NRF24L01+ chipset 2.4GHz wireless modules with Arduino before, and found them to be great, and super cheap (~$10 for 10 of them on ebay!). They have 3 modes of transmission: 250kbps, 1Mbps, and 2Mbps. The range decreases accordingly with higher bitrate, but the time spent sending a message does too. There are multiple Arduino libraries (e.g. RF24, Mirf, RadioHead) and tutorials for using the modules (see http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01). They also have built-in mesh networking modes which may or may not be of use.

Versions with an RP-SMA antenna connector and an advertised range of up to 1000m are also available for about $5 each. I would recommend using one of these for the referee's button at least, depending on the range you need.

According to Charles Hallard of hallard.me, The non-amplified chips can get 30m line-of-sight range in 250kbps mode, and I have verified this in my own testing.

According to user sporadic on diychristmas.org, sending a 32 byte payload in 250kbps mode takes 1432µs from the start of Tx mode on the transmitter to receiving the full message on receiver. This decreases to 444µs on 1Mbps mode and 283µs on 2Mbps mode.

Given these statistics, they fall well within 2ms latency for triggering, suitable for your application, and they use very little power. It's up to you to work out the best balance of latency, range and expense.


Throughput and BER test with nRF24L01+ radio and Teensy microcontroller I am trying to modify the example given in the this page to a basic throughput and BER test with two nRF24L01+ and Teensy 3.0 modules.

I want to modify the nrf24l01_send_string example in a way that I can remove the powerUp powerDown and delay and transmit the next packet purely based on the ACK received from the receiver. The problem is RF24 class does not seem to have a method to transmit ACK (not ACK+Payload) and the datasheet does give any information on the structure of the ACK message. The example works when powerUp and powerDown are removed, but I need to modify it to measure throughput by removing the delay.

@Gerben remarked:

  You can't send the ACK manually. The module itself sends the ACK
  automatically (if enabled that is), once it receives the package. This
  way the sending module only need to be listening for the ACK for the
  shortest amount of time, reducing power usage. To attach data to the
  ACK package you need the writeAckPayload function. But you have to
  prepare this before any package is received


Looking for link to Double Pole Single Throw (DPST) relay for Arduino Need to find a DPST relay that is 'Arduino' friendly and that is capable of 30A at 240VAC. Anyone can share links ?

Not looking for recommendation, just ideas on what you saw or used in the past.

Thanks.

A relay that can switch 30A on mains voltage is not going to be able to switch directly from 5V. Getting something that can switch from 24V is much more realistic.

High amp relays are often called contactors. 4-pole ones are not uncommon for industrial motor applications. 3 high-amp poles are for 3-phase power and a low-amp one for a control signal.

You can buffer up the signal using a transistor (you'd need one anyway to supply the coil amps) or another relay.


Cannot bootload again after changing the board? We are so tired and would like to get help with this. We are trying to bootload using the arduino Uno.

We have an atmega 328p smd , that we are trying to bootload. We have connected all the right pins, added to the boards.txt the  "Atmega328 on a breadboard(8mhz internal clock)".

Then I have chosen from the "board" menu, this option (internal clock), and uploaded the program. it worked .

Later, I wanted to try and bootload for external clock so I chose from the boards menu the pro mini with 5v board.(is it wrong?)

Not only that I got an error, now, I can't bootload the internal clock again !!

Why can't we bootload again? Did we damage something? Can it be reset again?
How can you bootload for external 16Mhz ??

error :

avrdude: Yikes!  Invalid device signature.
         Double check connections and try again

Not only that I got an error, now, I can't bootload the internal clock again !

You need an external clock source, such as a crystal and two capacitors. Once you switch the fuses to the external clock it won't work any more unless you have such a clock.

I have a bootloader uploader sketch that also provides a clock signal if you need it.


Recommendation for a projector module or approach? I am looking to create a projector effect similar to one seen in projector alarm clocks like
https://www.amazon.com/Mooas-White-Projection-Alarm-Projector/dp/B07Q6W53LK/ref=asc_df_B07Q6W53LK/?tag=hyprod-20&linkCode=df0&hvadid=343191208006&hvpos=&hvnetw=g&hvrand=4354131467724049360&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9019795&hvtargid=pla-758051396522&psc=1&tag=&ref=&adgrpid=68752454603&hvpone=&hvptwo=&hvadid=343191208006&hvpos=&hvnetw=g&hvrand=4354131467724049360&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9019795&hvtargid=pla-758051396522
and I am looking for some module that would accomplish it
https://www.mouser.com/ProductDetail/Texas-Instruments/DLPDLCR2000EVM?qs=BZBei1rCqCAQetmBz0G1xQ%3D%3D&gclid=Cj0KCQiA-rj9BRCAARIsANB_4ABW01iyq1W96Kd3piCLku3MSKib7xc_TspaZIa364hTXtJ_kYPSg0AaAvSAEALw_wcB
This is the closest thing I can find to what I am looking for but it's very pricey I would think given how popular these sorts of alarm clocks are there would be something much cheaper and easy to get your hands on out there.

As written in the comments, the linked projector is a DLP  projector with 640x320 pixels. Of course, that is expensive. It is a complete pixel display, which can display anything (with the max resolution of 640x320). That is way more, than the projector watches.
The watches often use one of two possibilities:

A bright 7 segment LED display, which is projected to the wall via a lens. The seven segment display needs to be bright enough, depending on the intended brightness of the projection and how big the projected image should be.

An LCD display, which is illuminated from behind by a bright LED. That is then also projected to the wall with a lens. I would guess, that this is, what the linked watch is doing.

How to build that yourself? You can always salvage one of these watches. But when building it yourself, you should also follow one of the above possibilities. Which one depends on your requirements.
Using a standard 7 segment display will be the easiest. Though that might be not bright enough. You could look for especially bright 7 segment displays and test, if that is enough for you.
The second possibility would be more hacky. Most LCD displays, that you can buy, have a LED lit plane in the back as a backlight. You would need to remove that plane, so that the display gets transparent. Also you most likely would need to rotate the polarizing filter on the top of the LCD, because as standard a driven segment of the LCD gets more opaque, while you want it to get transparent. A new filter (up to a few cm) can be salvaged from the passive 3D glasses from a movie theater.
In both cases you install the display inside a tube together with a fitting lens. Look, what you can get from your location and then experiment with it.

can you link to parts

No, we are not really doing that here, because that is really dependent on your location, on your price- and other requirements. Also such part suggestions are usually very fast outdated. But you can look at the electronics shops, that you have at your location and search there for the general description of the parts (for example "7 segment display").


SPI transactions in Arduino I have a task where I should do SPI transactions in interrupt mode. Means I have to handle data in IRQ handler (both for tx and rx bytes). How should I approach?
I have a arduino board (2560) and a CAN shield (seeed studio) with SPI interface.
Edit:
From the website: https://www.arduino.cc/en/reference/SPI

With most SPI devices, after SPI.beginTransaction(), you will write
the slave select pin LOW, call SPI.transfer() any number of times to
transfer data, then write the SS pin HIGH, and finally call
SPI.endTransaction()

My question is - the function SPI.transfer() is handled in what way?
Are the bytes transfered/received in interrupt handler or by polling?

I have a lengthy reference question about SPI which may help you.
To transfer outwards you do not need to use an interrupt. Nor is it polled. The data is simply placed in the SPI register and the hardware clocks the data out at the defined SPI rate.
To transfer inwards you are just reading the register. However to know when you need to read it, you would probably put the reading inside an interrupt routine.
I suggest you read the link above, and then if you want, you might expand your question more.
The source for the SPI transfer which I think applies to the Atmega2560 is as follows:
// Write to the SPI bus (MOSI pin) and also receive (MISO pin)
  inline static uint8_t transfer(uint8_t data) {
    SPDR = data;
    /*
     * The following NOP introduces a small delay that can prevent the wait
     * loop form iterating when running at the maximum speed. This gives
     * about 10% more speed, even if it seems counter-intuitive. At lower
     * speeds it is unnoticed.
     */
    asm volatile("nop");
    while (!(SPSR & _BV(SPIF))) ; // wait
    return SPDR;
  }

You can see that there is brief polling (the "while" line) for the register which the processor maintains to show whether the transmission has ended. Then the register is read and returned. So yes, there is polling there.
Now if you use an interrupt (see link above) then you will know that the flag has been set, and therefore there will be no delay (in the polling).


Use a Unicode surrogate pair character in Arduino IDE I'm writing a sketch for a Wemos D1 Mini to display a web page. This works and I can get Unicode characters to display, but if I try to use ones with surrogate pairs like 🔊 I get a compile error;

  s += "\uD83D\uDD0A";

Error

  \uD83D is not a valid universal character

How can I get this character in my code?

There is a nifty new feature in C++11 called string literal, this example shows how to use it with any single line or multi line or utf8 text. You just define starting and ending sequence, in following case --- (starting sequence becomes R"---( and ending sequence )---") and make sure that this sequence does not appear in encapsulated text. This is great for integrating websites into arduino projects:

static const char _index_html[] PROGMEM = R"---(
<html>
<head>
<link rel="icon" type="image/png" href="/favicon.png"/>
</head>
<body>
...
</body>
</html>
)---";


Thermocouple and multimeter I've put together this script that should allow my Arduino Mega to be show thermocouple readings on the serial monitor, whilst also showing readings of voltage and ohms across a given component. I'd be grateful for any advice on how it can be improved/streamlined:

#include <SparkFun_MCP9600.h>
MCP9600 tempSensor;
int analogPin = 0;
int raw = 0;
int Vin = 5;
float Vout = 0;
float R1 = 220;
float R2 = 0;
float buffer = 0;
float volt = 0;
int input = 0;

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Wire.setClock(100000);
  tempSensor.begin();

  if (tempSensor.isConnected()) {
    Serial.println("Device will acknowledge!");
  }
  else {
    Serial.println("Device did not acknowledge! Freezing.");
    while (1); //hang forever
  }

  if (tempSensor.checkDeviceID()) {
    Serial.println("Device ID is correct!");
  }
  else {
    Serial.println("Device ID is not correct! Freezing.");
    while (1);
  }

  pinMode(A4, INPUT);
}

void loop() {

  input = analogRead(A4); //analogRead function is used to receive analog data
  volt = (input * 5.0) / 1024.0; //formula using for perform action

  if (tempSensor.available()) {
    Serial.print("Thermocouple: ");
    Serial.print(tempSensor.getThermocoupleTemp());
    Serial.print(" °C   Ambient: ");
    Serial.print(tempSensor.getAmbientTemp());
    Serial.print(" °C   Temperature Delta: ");
    Serial.print(tempSensor.getTempDelta());
    Serial.print(" °C");
    Serial.println();
  }

  raw = analogRead(analogPin);
  if (raw)
  {
    buffer = raw * Vin;
    Vout = (buffer) / 1024.0;
    buffer = (Vin / Vout) - 1;
    R2 = R1 * buffer;
    Serial.print("Vout: ");
    Serial.println(Vout);
    Serial.print("R2: ");
    Serial.println(R2);
    Serial.print("voltage is:");
    Serial.println(volt);
    Serial.print("current is:");
    Serial.println(volt / R2);
    delay(1000);
  }
}

Your code is not very long, but I already see a few things that I would change.

int analogPin = 0;
[...]
pinMode(A4, INPUT);

These usages of pins are inconsistent. I personally prefer settings at the beginning of the file, so I'd expect

int analogPin = 0;
int whateverPin = A4;  // I don't have a good name yet

While you have

pinMode(A4, INPUT);

there's no

pinMode(analogPin, INPUT);

The main loop is doing 2 things: a) show temperature reading and b) show the component specs. This would be more obvious if written like this:

void loop() {
  input = analogRead(A4); //analogRead function is used to receive analog data
  volt = (input * 5.0) / 1024.0; //formula using for perform action

  showTemperatureReadings();
  showComponentReadings();
}

Now, that looks a bit strange, don't you think? What about the stuff before these two big show...() methods? These two lines clearly belong into showComponentReadings().

Now, a lot of variables are declared outside of methods. This makes them global variables. It's possible to change them from anywhere in the code. When the project grows, side effects are evil. Let's remove as many of them as possible.

You can get rid of:

int input = 0;
float volt = 0;
float buffer = 0;
float R2 = 0;
float Vout = 0;
int raw = 0;

After this change, I think the setup() method could be more concise. A lot of stuff just deals with the temperature sensor. I would extract a method as well.

The error messages like

  Device did not acknowledge! Freezing.

could not mean very much to the user. A message like

  Temperature sensor did not acknowledge! Check the wiring and press the reset button to retry.

could give more meaningful instructions.

The final code with these suggestions applied:

#include <SparkFun_MCP9600.h>
MCP9600 tempSensor;
int analogPin = 0;
int whateverPin = A4;
float R1 = 220;
int Vin = 5;

void setupTemperatureSensor() {
  tempSensor.begin();
  if (tempSensor.isConnected()) {
    Serial.println("Temperature sensor acknowledged.");
  }
  else {
    Serial.println("Temperature sensor did not acknowledge! Check the wiring and press the reset button to retry.");
    while (1); //hang forever
  }

  if (tempSensor.checkDeviceID()) {
    Serial.println("Temperature sensor ID is correct.");
  }
  else {
    Serial.println("The temperature sensor ID does not have the expected value. Do you use a different sensor type? Use a SparkFun MCP9600.");
    while (1);
  }
}

void setup() {
  Serial.begin(115200);
  Wire.begin();
  Wire.setClock(100000);

  setupTemperatureSensor();

  pinMode(whateverPin, INPUT);
  pinMode(analogPin, INPUT);
}

void showTemperatureReadings() {
    if (tempSensor.available()) {
    Serial.print("Thermocouple: ");
    Serial.print(tempSensor.getThermocoupleTemp());
    Serial.print(" °C   Ambient: ");
    Serial.print(tempSensor.getAmbientTemp());
    Serial.print(" °C   Temperature Delta: ");
    Serial.print(tempSensor.getTempDelta());
    Serial.print(" °C");
    Serial.println();
  }
}

void showComponentReadings() {
  int input = analogRead(whateverPin); //analogRead function is used to receive analog data
  float volt = (input * 5.0) / 1024.0; //formula using for perform action
  int raw = analogRead(analogPin);
  if (raw)
  {
    float buffer = raw * Vin;
    float Vout = (buffer) / 1024.0;
    buffer = (Vin / Vout) - 1;
    float R2 = R1 * buffer;
    Serial.print("Vout: ");
    Serial.println(Vout);
    Serial.print("R2: ");
    Serial.println(R2);
    Serial.print("voltage is:");
    Serial.println(volt);
    Serial.print("current is:");
    Serial.println(volt / R2);
    delay(1000);
  }
}

void loop() {
  showTemperatureReadings();
  showComponentReadings();
}

With code folding active, I'd say it's now very simple to get an overview of what the code is doing and what can be configured:

Edit:

After you linked to the schematics, I would

rename whateverPin to voltageDividerPin.
change the calculation float volt = (input * 5.0) / 1024.0; to a mapping, because it maps the 1024 input values to 5V, so float volt = map(voltageReading, 0, 1024, 0, Vin);
remove analogPin completely, because it's not used in the original code as well.

I also hope that read the article and you understood the consequences of using a 220 Ohm resistor.


SdFat library Change output style of sd.ls(LS_R) I'm using the SdFat Library's sd.ls(LS_R) function to give me a serial output stream of all files on an SD card. My issue is that I would like to have it use a different character than '\n' at the end of each line as I'm using it as a termchar for my overall comms protocol. How can I get it to print a : or (another symbol that doesn't appear in file names) instead of a \ln

I am currently trying to have fun Modding my own sd.ls().

Worst way, modifying the library:

Go into FatFilePrint.cpp

(Suggestion: Create yourself a new 'flag' like LS_COMMA)

Find the line

void FatFile::ls(print_t* pr, uint8_t flags, uint8_t indent) { ...

add your flag

if (flag & !LS_COMMA) {
   pr-->write(':');
} else {
    //original library set of
    // pr->write(stuff);
}

--> SuperClass version # (prefered )

this will override the original ls() method by creating a new Class inheriting from the original one.

rather then invoking it from "volume",
    sd.ls( your params);

invoke it from a directory file instead.

superFatFile rootDir;
rootDir.open("/");
rootDir.ls( __your_params__);

Place this superClass declaration in your .h
don't hesitate to remove any of the "flags" related code if YOUR requirement never calls for them.

class superFatFile : public FatFile {
    public:
    void ls(print_t* pr, uint8_t flags /* = 0 */, uint8_t indent /* = 0 */){
        superFile file;
        rewind();
        while (file.openNext(this, O_READ)) {
            if (!file.isHidden() || (flags & LS_A)) {
                // adds 'spaces' indent for dir level
                for (uint8_t i = 0; i < indent; i++) {
                    pr->write(' ');
                }

                if (flags & LS_DATE) {
                    file.printModifyDateTime(pr);
                    pr->write(' ');
                }

                if (flags & LS_SIZE) {
                    file.printFileSize(pr);
                    pr->write(' ');
                }

                // prints filename
                if (!file.isDir()) {
                    file.printName(pr);
                    pr->write('\r');
                    pr->write('\n');    // HERE IS YOUR SEPARATOR CARACTERS !!!
                }

                // execute recursivly if LS_R flag was set
                if ((flags & LS_R) && file.isDir()) file.ls(pr, flags, indent + 2);

            }

        }
        file.close();
    } // end of new LS method
}; // end of superClass


BLDC geared motor with encoder - How to wire the encoder? (6 wires) I am quite a newbie to arduino and currently stuck with an encoder.
I have a BLDC geared motor with encoder, all I want to do is to get values from the encoder.
There are 6 wires, out A, out B, out Z, +V, 0V, F.G
How should I wire those six of them correctly?
Encoder specification says 5VDC is ok to power it, and I want to make a circuit to power encoder using Arduino Mega board.

This should be in the documentation of the motor or encoder, and that is the first place to look.
If you don't have any documentation, here is my best guess:
ABZ suggests it is an incremental encoder with channel A and B for quadrature encoding (giving direction and speed), with Z as the index pulse for getting absolute position once every rotation. FG is most probably Frame Ground, or maybe be the Fault signal.
How you wire it all depends on what you want to do with it, but knowing what each signal is should make it easy enough.


Can't upload new sketch Recently I have unsoldered most connector pins there are on the arduino uno board.
However, when I now attempt to upload a new sketch (works when I upload it to another model) it gives me the following error:

> avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xfa
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xfa

I would like you take a look at my arduino board to see whether I have unsoldered important pins which might have to be connected.

Also when I try to upload a new sketch the 'L'-LED doesn't flash but the RX one.

(BTW: Yes I've set the settings to the correct board, port etc...)

Thanks for any solution attempts!

Pin 0(RX) and 1(TX) and the RESET pins are important to upload a sketch. Can you check those carefully with a magnifier ? Perhaps there is some solder that shortcuts to something else, or perhaps you damaged a copper trace.


Storing hash values from SHA256 I am using this code and I can not save the output of the hash function to an array of char. Can you help me how to do that?

#include "sha256.h"
#include <Arduino.h>
#include "./printf.h"

void printHash(uint8_t* hash) {
  int i;
  for (i=0; i<32; i++) {
    Serial.print("0123456789abcdef"[hash[i]>>4]);
    Serial.print("0123456789abcdef"[hash[i]&0xf]);
  }
  Serial.println();
}

void setup()
{ String FinalStr="1234567890";
Sha256.init();
  Sha256.print(FinalStr);
  printHash(Sha256.result());
}
void loop()
{

}

This is the code that worked for me:

#include "sha256.h"
void setup(void)
{char encoded[64];
    Serial.begin(9600);

    // this is actually the RFC4231 4.3 test

    Sha256.init();
    Sha256.print("123");
    uint8_t * result = Sha256.result();

    Serial.println("Expect: 2d711642b726b04401627ca9fbac32f5c8530fb1903cc4db02258717921a4881");
    Serial.print(  "Got   : ");
    for (int i = 0; i < 32; i++) {
            Serial.print("0123456789abcdef"[result[i] >> 4]);
            Serial.print("0123456789abcdef"[result[i] & 0xf]);

            for(int i = 0; i < 64; i+=2)
                {
                  encoded[i] = "0123456789abcdef"[result[i / 2] >> 4];
                  encoded[i + 1] = "0123456789abcdef"[result[i / 2] & 0xf];
                }
    }
    Serial.print("\n");
            for(int z = 0; z < 64; z++)
            Serial.print(encoded[z]);
}

void loop(void)
{}


delete or free on object causes Arduino to hand or reboot I've read a lot about dynamic allocation for strings or buffers, but that's not my case.

I plan to implement much blinkers types as classes, all inheriting from a base Action class.

I declare an array of 10 pointers because I want to limit to 10 blinkers simultaneously at most :

Action** actions = new Action*[10];

In the code, I will do something like :

int i = GetFreeActionID();
actions[i] = new ActionLightBlinkerMono(myPin, onDuration, offDuration);

Then the loop will call a method of the object and it works fine.

When it comes to stop the blinking, I would just destroy the object and set the pointer to zero, so the loop will not try to call the method of the object anymore :

if (actions[i]->Do() != 0)
{
  delete(actions[i]);
  actions[i] == 0;
}

Howerver, I see in the serial console that when it comes to the delete instruction, the Arduino just reboots itself ...

Tryed also free instead of delete with same result.

How could I safely free the object when it's not used anymore ?

It's an evidence I don't know what will be used at compile time, the blinkers will be started by the user (via I2C instructions) at runtime, hence instanciating different classes.

actions[i] == 0;

That statement has no useful effect. Perhaps you mean:

actions[i] = 0;


Print Byte Array in Serial monitor screen of Arduino IDE I need to print mentioned below byte array on the serial monitor screen of Arduino IDE

char b[]= {'0x7E', '0x00', '0x1C','0x90', '0x00', '0x13', '0XA2', '0x00', '0x41', '0x58', '0x1C', '0xCB', '0xFF', '0xFE', '0xC1', '0x7C', '0x00','0x0F', '0x00', '0x01', '0x00', '0x00', '0x37', '0x46', '0x46', '0x46', '0x00', '0x00', '0x00', '0xE7' };
void setup() {
Serial.begin(9600);
}

void loop() {
Serial.println(b[]);
delay(500);
}

But whenever I am trying a print, the error problem was there which was not resolved which is

C:\Users\Misha\Desktop\test\Test_2\Test_2.ino: In function 'void loop()':

Test_2:8:18: error: expected primary-expression before ']' token

 Serial.println(b[]);

                  ^

exit status 1
expected primary-expression before ']' token

Any suggestions on this will be great help.

You can’t print an array in that way.

If you want to print an array of hexadecimal value (with two digits), you have to use sprintf function and change declaration of b array.

uint8_t b[]= {0x7E, 0x00, 0x1C, 0x90, 0x00, 0x13, 0XA2, 0x00,
              0x41, 0x58, 0x1C, 0xCB, 0xFF, 0xFE, 0xC1, 0x7C,
              0x00, 0x0F, 0x00, 0x01, 0x00, 0x00, 0x37, 0x46,
              0x46, 0x46, 0x00, 0x00, 0x00, 0xE7};
int i;

void printHex(uint8_t num) {
  char hexCar[2];

  sprintf(hexCar, "%02X", num);
  Serial.print(hexCar);
}

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

void loop() {
  for(i=0; i<sizeof(b); i++){
    printHex(b[i]);
 }

 Serial.println();
 delay(500);
}

The output produced is:

  7E001C900013A20041581CCBFFFEC17C000F0001000037464646000000E7
  7E001C900013A20041581CCBFFFEC17C000F0001000037464646000000E7
  7E001C900013A20041581CCBFFFEC17C000F0001000037464646000000E7


Variables not initialized in Class Constructor I'm creating a library driver for AdaFruit's GFX library. During Constructor initialization, all the variables (set in another .cpp) are returned as zero. This code has several modular files to separate graphics functions from graphics primitives from device interfacing. What am I doing wrong?

In the Arduino sketch I call the class constructor: MB_GFX_SPI (in file MB_GFX_SPI.cpp).
In the Constructor I'm call a function: mbR.SetMatrixSize (in another file raster.cpp).
Also in the Constructor I call a function: clearScreen (in the same file MB_GFX_SPI.cpp).

The test variable  mbR.r_totNumChannels set in clearScreen is returned with 99.
All the variables set in mbR.SetMatrixSize return zero.

//Test Sketch
//Initialize both the Adafruit library and the current library.
//Instantiate an object mbGFX so all Adafruit GFX and MB_GFX add-on functions are addressed as mbGFX.xxx();
MB_GFX_SPI mbGFX = MB_GFX_SPI(Period, numCathodeLeds, numAnodeLeds, CathodeSSPin, AnodeSSPin);

//In file MB_GFX_SPI.cpp

MB_GFX_SPI::MB_GFX_SPI(int Period, int numCathodeLEDS, int numAnodeLEDS,
      int CathodeSSPin, int AnodeSSPin)
      : Adafruit_GFX(numCathodeLEDS, numAnodeLEDS) {

  mbR.SetMatrixSize(numCathodeLEDS, numAnodeLEDS);
  clearScreen(0);
}
void MB_GFX_SPI::clearScreen(uint16_t color) {
   mbR.r_totNumChannels = 99;   //test set value
}

//In file mb_raster.cpp

void mbRasterClass::SetMatrixSize(int numCathodeLeds, int numAnodeLeds){
//cathodes require 1 byte per channel
//anodes require 1 bit per channel

    int numAnodeChannels = numAnodeLeds;
    int numCathodeChannels = mbX.pin2pin * numCathodeLeds; //times 1 or 3

    r_numCathodeRegisters = (int)((numCathodeChannels+7)/8);   //select next higher number of registers
    r_numCathodes = 8 * r_numCathodeRegisters;  //must be whole 8 bit registers - is every single chatode pin
    r_numAnodeRegisters = (numAnodeChannels+7)/8;       //round up to next register number
    r_numAnodes = 8 * r_numAnodeRegisters; //must be whole 8 bit registers
    r_PWMBufferSize = r_totNumChannels = r_numAnodes * r_numCathodes;

    r_PWMBuffer = (uint8_t *) realloc(r_PWMBuffer, r_totNumChannels); //resize array for PWMBuffer
}

First, I would do what Edgar Bonet suggested, call the normal constructor:

MB_GFX_SPI mbGFX (Period, numCathodeLeds, numAnodeLeds, CathodeSSPin, AnodeSSPin);

Second, I'm not keen on what you are doing in the constructor for a variable which appears to be at global scope (mbGFX).

See What's the "static initialization order fiasco"?

Basically you cannot assume that constructors in different compilation units are called in any defined sequence, you also cannot assume that the system has been initialized yet (ie. init() called).

Thus, things that address the hardware (eg. clearScreen(0);) may not work properly, or at all.


cannot convert 'bool' to 'PinStatus' for argument '2' to 'void digitalWrite(pin_size_t, PinStatus) on Arduino Uno Rev 2 Wifi not working I am a newbie to micro controllers and struggling to figure out how to fix this issue. When using an older Arduino micro controller it works fine, but when I use a new board (Arduino Uno Rev 2 Wifi) it gives me this error:

cannot convert 'bool' to 'PinStatus' for argument '2' to 'void digitalWrite(pin_size_t, PinStatus)'

At this line :

digitalWrite(pin_enable_line, !digitalRead(pin_enable_line));

Library I am using is: ReceiveOnlySoftwareSerial.

The digitalRead method doesn't return a Boolean value. It returns an Integer.

From what I remember inside Arduino.h values of LOW and HIGH are defined as being simply Integer 0 and 1.

#define HIGH 0x1
#define LOW 0x0

I think that was changed to an Enum called PinStatus but Enum can be treated as an Integer.

This means that you have to store results of digitalRead inside Integer variable.

int value = digitalRead(8);

It was designed that way to easily cast values between Integer and Boolean. By (very smart) design choice Integer value of 0 (LOW) will be cast to false and every other value (for example 1 or HIGH) will be cast to true.

The operator ! (Boolean NOT) can be used only with Boolean variables so the compiler needs to perform several "implicit casts". When it's smart enough it will assume you are know what you are doing and it will add the cast by itself.

By reading the error I see that the issue is happening when compiler tries to convert Boolean value into Integer. So this is implicitly evaluated correctly as a Boolean value

!digitalRead(pin_enable_line)

But when you try to put it inside a place for PinStatus you get the exception

cannot convert 'bool' to 'PinStatus'

Try adding an "explicit cast" to PinStatus:

digitalWrite(pin_enable_line, (PinStatus)!digitalRead(pin_enable_line));

It should fix the issue.
But I suggest splitting the code into several lines and adding a temporary variable. It makes debugging much easier. Trust the code optimizer that's built into the compiler. It will understand what you want to do and actual machine code will be the same.


square root of large number I've got 2 int16_t numbers, say 388 and 10288, which are sensor readings from an accelerometer. I want to estimate the angle of the device on that, but seemingly there are some type overflow issues:

My final goal is this:

theta =  atan(-ax/sqrt((float)ay*ay+az*az));

The problem occurs in the bracket: ay^2 and az^2 are the 2 power of the given numbers. I recalculated with matlab and for the above example I get a^2+b^2 = 388^2+10288^2 = 105993488 what I get from the arduino however is 152848.
To be short: I don't know much about fixed point math or thelike and I couldn't find a sufficient answer to this: How do I calculate the square root term?

You need 2 typecasts. So

atan(-ax/sqrt((float)ay*ay+(float)az*az));

Otherwise it will use int16_t for the right side of the addition and overflow.

Though for speed you might want to typecast them as long (int32_t), as floats calculations on the arduino are really slow. The sqrt function will covert this double into a float for you.


Arduino not writing full NMEA sentence to SD-card file I'm currently building a small GPS-box that's supposed to track my location and write the full NMEA sentence to an sd card.
(I want to pars it afterwards at my pc)
I'm using the Arduino Nano and the NEO-6M GPS Module to get the data.

What works: getting the NMEA data from the module, writing to the SD-card.
Outputting the data to the serial output over Serial.write works fine.

Now I have the problem that it looks like the Arduino can't write the data fast enough to the SD-card and desyncs with the GPS module. This occasionally produces things like this: $G3,3,09,32,20,248,*4D

I have some ideas on how to fix this:
1. write the data faster
2. always wait till the data is fully written before acquiring the next fix
3. only write every second GPS fix

I tried to implement these but failed every time (sorry I'm new to this).

Here is my current code:

#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>

SoftwareSerial GPS_Serial(4, 3); // GPS Module’s TX to D4 & RX to D3
File GPS_File;
int NBR = 1;  //file number

void setup() {
  Serial.begin(9600);
  GPS_Serial.begin(9600);
  SD.begin(5);                  //SD Pin

  //write data to a new file
  bool rn = false;
  while (rn == false) {
    if (SD.exists(String(NBR) + ".txt")) {
      NBR = NBR + 1;
    }
    else {
      GPS_File = SD.open(String(NBR) + ".txt", FILE_WRITE);
      GPS_File.write("START\n");
      GPS_File.close();
      rn = true;
    }
  }
}

int x = 0;
int temp = 0;
char gpsData;
char buff[300];

void loop() {

  //collect data and write to buffer
  while (GPS_Serial.available() > 0) {
    gpsData = GPS_Serial.read();
    x++;
    buff[x] = gpsData;
  }

  temp = x;
  x = 1;

  GPS_File = SD.open(String(NBR) + ".txt", FILE_WRITE);

  //copy from buffer to sd
  while (x <= temp) {
    GPS_File.print(buff[x]);
    x++;
  }

  GPS_File.close();

  x = 0;
  temp = 0;
}

After trying different approaches I decided to dumb it down to its most basic level.
Without any fancy coding or buffers, I'm now just writing the data directly to the SD-card and flushing every 15 seconds which has the risk to loose up to 15 seconds of data i.e. 15 GPS-fixes (1 per second) when cutting off power.

The only other time where a potential data loss can happen is observed when the program flushes the accumulated data to the SD. This doesn't happen every time though.

To pars the NMEA-sentences into usable data I use GPSBabel. It automatically ignores the broken lines. After converting to .gpx I view it with Google Earth.

This is the "finished" code:

#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>

SoftwareSerial GPS_Serial(4, 3);  // GPS Module’s TX to D4 & RX to D3
File GPS_File;
int NBR = 1;                      //file number

unsigned long TimerA;             //save timer
bool sw = false;                  //save timer switch

void setup() {
  Serial.begin(9600);
  GPS_Serial.begin(9600);
  SD.begin(5);                    //SD Pin

  //write data to a new file
  bool rn = false;
  while (rn == false) {
    if (SD.exists(String(NBR) + ".txt")) {
      NBR = NBR + 1;
    }
    else {
      GPS_File = SD.open(String(NBR) + ".txt", FILE_WRITE);
      GPS_File.write("START\n");
      rn = true;
    }
  }
}

void loop() {
  while (GPS_Serial.available() > 0) {
    GPS_File.write(GPS_Serial.read());
  }

  //set up timer
  if ( sw == false) {
    TimerA = millis();
    sw = true;
  }

  //save every 15 seconds
  if (millis() - TimerA >= 15000UL) {
    GPS_File.flush();
    sw = false;
  }
}


max7219 chained display showing text only on the first display I'm using a max7219 like this one max7219. When I first tested my circuit, I used an 8x8 display and the code worked just fine. Now, after I modified the code and changed the display with the chained one, the text is showing only on the first matrix. I've seen someone that had another problem with the same matrix module, only that in his case the same text was printed on all the matrixes unsolved problem, in the end he didn't find a solution. Below, I'll attach my code. Please help me find the problem.

//Pin connected to ST_CP of 74HC595
int latchPin = 6;
//Pin connected to SH_CP of 74HC595
int clockPin = 7;
////Pin connected to DS of 74HC595
int dataPin = 5;

int period = 30;

byte rotl(byte n, byte b)
{
  return (n << b) | (n >> (8 - b));
}

byte X[] {

0x80,
0x80,
0x80,   //L
0x80,
0x80,
0x80,
0x80,
0xFF,

/*0x10,
0x00,
0x10, //I
0x10,
0x10,
0x10,
0x10,
0x10,

0XF0,
0x90,
0x80, //C
0x80,
0x80,
0x80,
0x90,
0xF0,

0xF0,
0x09,
0x09,
0x09,
0x09,
0x09, //A
0x09,
0xF0*/

};

void setup() {
  //set pins to output so you can control the shift register
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop()
{
  for (int i = 0; i < 8; i++)
  {
    X[i] = rotl(X[i], 1);
  }
  for(int i = period;i>0;i--)
  {
    displayX();
  }

}

void DisplayMatrix(byte numCol, byte numLine)
{
  byte numberToDisplay1 = numCol;
  byte numberToDisplay2 = numLine;

  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay1);
  shiftOut(dataPin, clockPin, MSBFIRST, numberToDisplay2);
  digitalWrite(latchPin, HIGH);
  delay(1);

}

void displayX()
{
   DisplayMatrix(X[0],1);
   DisplayMatrix(X[1],2);
   DisplayMatrix(X[2],4);
   DisplayMatrix(X[3],8);
   DisplayMatrix(X[4],16);
   DisplayMatrix(X[5],32);
   DisplayMatrix(X[6],64);
   DisplayMatrix(X[7],128);
}

Communicating with more than one MAX7219 chip when cascaded involves sending data to all the chips at once. You have to treat the cascaded sequence of chips as a single entity - an entire display in its own right.

With one chip you send an 8-bit register value followed by an 8-bit data value. To use two chips you have to send twice that - an 8-bit register and 8-bit data for the second chip, followed by an 8-bit register and 8-bit data for the first chip.

The chips have a "NO-OP" register (0x00) which can be used to ensure that nothing is done on that chip if you don't want to change anything.

So setting line 3 to 0x55 on the first display, and line 5 to 0xAA on the second display you would send the sequence \ 0x05,0xAA,0x03,0x55 / as a single transaction (lower CS \ before, raise it / afterwards).

If you only wanted to set line 2 on the second display to 0x69 you would send the sequence: \ 0x02,0x69,0x00,0x00 /

For three chips you need to send three blocks of 8+8 values. For four chips, 4 blocks of 8+8. Etc.

Note that it is important to send enough data for all the chips - you can't shortcut and only send data for the first display if that is all you want to talk to, since whatever is currently in the first display's shift register will get sent out to successive chips, and you will get the display duplication as seen in the other question.


Using the Waspmote Sensor Board Spanish company Libelium makes this pretty impressive sensor board:

http://www.libelium.com/products/waspmote/sensors/

for their Waspmote series of boards.  These are not meant for Arduino compatibility, but they are not only interesting for combining so many sensors, the availability of calibrated sensor sets makes it even more unique.

So here is the challenge: can we reasonably leverage these from an Uno or a Mega?

Too long for a comment...

Look at some of their docs for examples. seems like they have a very similar platform to Arduino.

  Their forums suggest making the connection is not trivial, but may be
  possible: http://www.libelium.com/forum/viewtopic.php?f=15&t=8811

All that's saying is you can't simply plug in a sensor into your Arduino like a shield, because it's not a shield. You'd have to hook up the connections to the right pins and then use their libraries and code to communicate with it.

That involves reading their documentation and code to figure out what pins it uses to communicate with what. You may have to modify the code slightly to work with Arduino (mainly changing pin numbers).

All in all, I wouldn't invest my time or effort into it. Don't lock yourself into a product that isn't intended to be used the way you're using it. You'll get no support from the company and there's no guarantee future versions of their product will work. Or things like this (from the forum link):

  Anyway, I'm afraid the Libelium's sales policy implies a minimum first
  order including five Waspmotes, five batteries and one Gateway.

Simply not worth the effort. You'd be much better off making your own sensor board to fit your requirements.


How to tap my thermostat's serial line This is a home heating system hack.

I want to add an arduino in-line between my thermostat and air handler; and possibly between the air handler and outdoor compressor. The long-term goal is to post long-term statistics to an RRD web page (run time, power consumption, temp, etc.) and control the blower (without the heat) automatically when we are burning our wood stove.

The product is a Nordyne IQDrive (notable in that the equipment comes with 5 separate brand logos to adhere to the equipment: Tappan, Frigidaire, Westinghouse, Nutone, and Broan).

At this stage, all I want to attempt to do is to tap the serial links and record the conversations. I would prefer not to shoot myself in the foot.

The "System Field Wiring Instructions" describe both links as "serial." The wiring diagrams label the connection points as:

air handler interface board --> [description] --> thermostat

      G --> GND --> C
      - --> DX- --> B-
      + --> DX+ --> A+
      R --> R   --> R

Googl'ing these might indicate that this is an RS485 (never heard of it).

How do I tap and record the communication?

I does sound like RS-485.

You can get cheap RS-485 transceivers from the usual sources.  These take the 0..5v TX line and convert it to RS-485 voltages, or RS-485 voltages and convert to the 0..5v RX expected by your Arduino.  You would normally enable only one direction at a time - sending RS-485 from the Arduino TX or receiving RS-485 to the Arduino.

In your case, you just want to receive, so keep the transmit side (TX to RS-485) disabled, while enabling the receive side (RS-485 to RX).

RS-485 is just an electrical standard, and they could be sending any pattern of on and off signals they want, but often they will be sending asynchronous data with one start bit, 7-8 data bits, and one stop bit per character - which the Arduino's Serial port can handle.  So it's worth testing to see if that works.

The next thing you need to know is the clock rate, or "baud rate", which is how many bits per second (including start and stop bits) it is sending.  Often you can figure this out by trying some standard rates like 1200,2400,4800,9600,19200,38400,57600,115200 (there are others) and printing the results to your screen - when you are at the wrong rate you will get nothing, or some odd garbage.  When you get the right rate, it will look more reasonable.

If no speed works, you may need to reverse A and B.

You might temporarily hook up an LED and a resistor (say 2.2K or higher) between the RX from the RS-485 and your 5v power.  This will give you an idea of when there are transmissions from or to the thermostat.  If it only transmits once a minute, say, you might have to wait a while for each speed test.  Or changing the set temperature may trigger a send.

You may be able to test the lower speeds at least using Software Serial, and then echo the received data to the hardware serial port which goes to the Serial Terminal in the Arduino IDE.

From there, you may need to figure out the protocol - the structure of the data.  Protocols vary widely.  It may be text or it may be binary; if it's binary you may want to have the arduino convert each character (values 0..255) into hexadecimal (00..FF) for printing.

Most protocols for this kind of control send data in a burst, or packet.  You will likely be able to detect the start and end by the timing (ie: a long pause between the end and the start of the next).  Of course, some protocols might send several packets continuously, but still the first character (or binary value) after a long pause will often be the packet header.

Remember that there may be packets from the themostat, and packets to the thermostat, and you will see both without knowing which is which (so long as you are just passively tapping the line).

I hope this is enough of a pointer to get you started.  Decoding protocols is a more extended subject.


Log vs linear pots and the arduino I have noticed that when I used a log pot from a guitar amp I found, it gives janky results when using it in a motor PWM sketch, but if I use it in a fade sketch, it works. why does log pots give sketchy results when using them in a PWM control sketch, like when using the map() function?

There are two associated issues here that underly your problem.

Firstly, with a log pot, you get a period of very small changes in resistance followed by a period of massive changes:

(* a "commercial" log pot is how log pots are usually manufactured - two linear traces of different resistances back to back).

So when turning you get "not much ... not much ... not much ... lots ... even more ... full".

Now couple that with how a motor works. A motor has a "stall current", which is higher than the "run current" (especially the "unloaded" run current).  This is the minimum amount of current required to overcome the inertia of the motor and start it spinning. This is, in effect, a lower threshold on the PWM value that you need to exceed before the motor will begin moving (once it's started moving you can go a little below that threshold and it will still move).

With a linear pot it's easy to get to that threshold and stay around it, increasing slowly above it, etc.  However, as you can imagine looking at the curve of the log pot above, if the "flatter" area of the pot is below the stall current threshold of the motor, the motor will do nothing until you are well into the sharper up-turn of the curve.  The effect of this is you will go from "stopped" to "quite fast" in one jump. It's very very hard to get even close to the stall current threshold.

For instance, if your motor needs a minimum of 30% duty cycle to start it running, that's about a 160 degree turn on the log pot above, compared to just 70 degrees of a linear pot, and the rest of the log pot's PWM range is compressed into a tight space.


Looking at Adafruit's website I'm confused which wallcharger I should get As the title says there are many different wall chargers to choose from.

12v, 9v, 5v, with different mA amounts...

The starter kit on Adafruit's website mentions to get the 9V 1000mA switching power adapter, so I'm curious if that's what we should get?

here is the link to all of them.

There are regular wall adapters, and these big power supplies...

http://www.adafruit.com/search?q=switching+power+adapter&b=1

I'm just looking to run some LED Strip lights from the arduino and power some joystick buttons, some rotary encoder/knobs, and a keypad to work the LED lights

Thoughts?

Thanks!

This website looks like a pretty official answer for you.
http://playground.arduino.cc/Learning/WhatAdapter

  Since you'll probably be connecting other things to the Arduino (LEDs, LCDs, servos) you should get an adapter that can supply at least 500mA, or even 1000 mA (1 ampère). That way you can be sure you have enough juice to make each component of the circuit function reliably.

And

  The Arduino's on-board regulator can actually handle up to 20V or more, so you can actually use an adapter that puts out 20V DC. The reasons you don't want to do that are twofold: you'll lose most of that voltage in heat, which is terribly inefficient. Secondly, the nice 9V pin on the Arduino board will actually be putting out 20V or so, which could lead to potential disaster when you connect something expensive to what you thought was the 9V pin. Our advice is to stick with the 9V or 12V DC adapter.


I already have a button on my Arduino board, but I don't know what pin number should I use in my code? I'm attaching a picture of my board which has the push button I want to use, but I cannot because I don't know what pin number should I write in my code.

my code:

int switchPin = Button;
int ledPin =13;

void setup() {
  // put your setup code here, to run once:
pinMode(switchPin, INPUT);
pinMode(ledPin, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
if(digitalRead(switchPin) == HIGH)
{
  digitalWrite(ledPin, HIGH);
}
else
{
  digitalWrite(ledPin, LOW);
}
}

This is a picture shows the button on the top right "green"

The schematic at makeblock.com of the mbot mcore board shows switch S3 feeding pin A7, which is an analog input pin.  Note, there is a deplorable 0.1 μF capacitor in parallel across S3, probably intended as hardware-level debouncing.

Also see the Port wiring mBot mCore board thread at makeblock, where one of the posts says there are multiple versions of the board, and provides reference links.

For example, sample code at
newinnovators.ca's “mblock-to-arduino/button-control” page shows pin 2 being used to sense the button.  You may need to run some tests.


RtcUtility.h: No such file or directory I have a problem with remaining headers. Can't seem to find the first header "RtcUtility.h". Anyone how to fix? I've provided a picture for you to see.

Error Messages:

  Arduino: 1.8.10 (Windows 7), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), 4M (no SPIFFS), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

  sample_time:6:24: error: RtcUtility.h: No such file or directory

  Multiple libraries were found for "ArduinoOTA.h"
   #include

  Used: C:\Users\user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\ArduinoOTA
                          ^

  Multiple libraries were found for "Wire.h"
  compilation terminated.

  Used: C:\Users\user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\Wire
  Multiple libraries were found for "ESP8266WiFi.h"
   Used: C:\Users\user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi
  Multiple libraries were found for "ESP8266mDNS.h"
   Used: C:\Users\user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266mDNS
  exit status 1
  RtcUtility.h: No such file or directory

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

Please add the RTC library in the Arduino as below.

Open the Library Manager and search for "Rtc by Makuna" and install.

You can also checkout the Github page for that particular library at

https://github.com/Makuna/Rtc


How to use same sketch on two different computers in two different directories I have the same sketch one that I use at my desk and in the lab, but they are in different directories on the different computers.  This means that I have to change the paths to the includes which I have to fixup every time I transfer back and fourth.  Is there a way to put in a #ifdef that I can set at the start of the build that would include correct path.

Open preferences.txt in C:\Users\YourUserName\AppData\Roaming\Arduino and change the path of sketchbook.path=C:\Users\YourUserName\Documents\Arduino to sketchbook.path=YourDesiredPath.


Vin & VU pins of NodeMCU V3 Can we use the vin pin of the lolin v3 nodeMCU as a 5V supply. If yes, i checked mine with a multimeter. At max, it gives a voltage of 2V. Is my pin blown out? Also, can use the VU pin as a 5V supply? Will using it cause any problems to my laptop's USB port? Can somebody help me out?

I need 5V to drive a relay using the v3

On the NodeMCU “v3” (and only on the v3) there’s a pin called VU (Vusb) that is connected to the +5V on the USB bus of the NodeMCU socket. This pin can be used to feed external components when it’s connected to USB, within the limits of the USB power supply it’s connected to.

The Vin pin (which is available on all NodeMCUs (and not just the v3) is a +5V power input which can be used to power the NodeMCU if it is not connected to USB. It can not be used as an output and it needs a stabilized supply.


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.