text:
NodeMCU ESP8266 on Arduino IDE doesn't detect Wifi
I am using a NodeMCU 1.0 v3 and I am trying the example sketch (wifiscan) but it just doesn't pick up any AP in the house. My phone and laptops etc are able to pick up the APs though.
Other sketches upload and work fine but the wifi aspect of it doesn't work. I even got an LCD sketch to work properly but it isn't able to find any access points or even join any access points. I have been trying to get it to work for hours now.
I first tried using the latest Arduino IDE (1.6.12), then I uninstalled and tried using 1.6.1 but no luck. My upload settings are NodeMCU 1.0 (ESP-12E module), 80Mhz, 115200, 4M (3M SPIFFS).

Your router might be using 5GHz Wifi which the ESP8266 doesn't support but your other devices likely do. Try setting your wifi network to 2.4GHz.

Thanks, I read on a forum somewhere that it could be the issue but when I checked my wifi it is indeed set at 2.4GHz. I also tested the esp8266 in an area with loads of APs so I ruled that out as an issue.

My gut feeling is that your hardware is just flakey.
I have one NodeMCU 1.0 that occasionally works, and occasionally does not.
On that one, it requires power cycling (unplugging and replugging) it a couple of times for it to start working.
The Arduino ESP8266 core is pretty solid, and wifi support should just work in it.
Just to make sure, you could post your simplest sketch which doesn't work (one that lists AP's, so that it can't be a ssid/password kind of issue), so people can check if there's a problem in the code..
Also, to be really sure, you could check your power system. NodeMCU has a 5v to 3.3v converter in it, and a usb plug, so that part should be ok. How many amps is the USB power supply rated at? If it's very low (<250ma) it could be an issue. You can also try adding a capacitor (something decent sized, >220uf at a random guess? I tend to go for ~1000uf) between gnd and 3.3v, and one between gnd and 5v pins. Watch polarity of-course, and double check, you don't want to short the power lines :)
There's a very small chance stabilizing the power in that way might help..

Thanks for the answer cranphin. I suspect it may in fact be due to a faulty unit. I used the example sketch that lists AP's but that didn't return anything. I also tried powering it separately using a 3.3v 2A supply. I think i'll just use it as I would a Arduino Pro mini because all other sketches except anything to do with wifi works. I'll add some caps as you suggested and see if it helps. Thanks again.

My DHCP table was full. I rebooted router and added more values for dhcp range (192.168.1.100-192.168.1.150) and the device now connects.... took me a day to figure this out.


text:
Multiple MuxShield 2's connected to a single Arduino Mega
I am working on a project and need alot of toggle buttons to control various things around the house. I connected 5 MuxShield 2's to my Arduino Mega. The first two will serve as inputs and the last two will serve as outputs.
The problem is when I try to loop over all the outputs (connected to LED's for now) to turn them on/off, only the first 3 rows work as expected. The LED's turn on one by one, but when the loop reaches a row number which it has already looped over on another multiplexer the LED's turn on all at once.
I think it has something to do with the arrays in the MuxShield library being shared across all multiplexers and therefor breaking all signals the second time it gets used but I'm not sure.
It's not that much code but, too much to post here so I uploaded it to GitHub.
If someone could please look over it and point me in the right direction, I'd greatly appreciate it. Thanks.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Esp8266 not working
I connected all the pins as in datasheet, except ch_pd.
But when I connect ch_pd to 3.3 V , the red light on esp8266 goes dim. I used 3.3 V, 250 mA power supply. What is the reason for this?

Link to datasheet? Link to ESP8266 device used? Image of how you have wired it up?

Recommended power supply sourcing capabilities are about 1A. In the firmware upgrading mode WiFi is possibly disabled, so it needs much less power.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Interfacing a stepper motor with arduino
I am having issues with interfacing my stepper motor, connected to a control board being this one
Due to some reason I am not able to move it, unless I remove the enable signal. I can change the direction either unless I manually change by either plug it or unplug it. If codewise change the state of the dir_pin,would the motor keep spinning in the same direction.
The control board need has a timing diagram, specifying when the en, and dir signal should be enabled.

the code I am using to interface it is as below:
stepper_motor.cpp:
#include "stepper_motor.h"

stepper_motor::stepper_motor()
{
  pinMode(BUILTIN_LED,OUTPUT);
  pinMode(step_pin,OUTPUT);
  pinMode(dir_pin,OUTPUT);
  pinMode(en_pin,OUTPUT);

  alive_bool = true;
  position_bool = false;
  step_count = 0;
}

void stepper_motor::alive()
{
  if(alive_bool == true)
  {
    digitalWrite(BUILTIN_LED,HIGH);
    alive_bool = false;
    delay(2000);
  }
  else if(alive_bool == false)
  {
    digitalWrite(BUILTIN_LED,LOW);
    alive_bool = true;
    delay(2000);
  }
}

void stepper_motor::step_pwm()
{

    digitalWrite(en_pin,HIGH);

    delay(0.005);

    digitalWrite(dir_pin,LOW);

    delay(0.005);

    while(1)
    {
      digitalWrite(step_pin,LOW);
      delay(1);
      digitalWrite(step_pin,HIGH);
      delay(1);
    }

}

stepper_motor.h
/* Class: stepper_motor
 * Info: contains the setup, and primary interface to control
 * the stepper motor
 *
 * stepper_motor(): constructor -  setup the connection to the control board
 * void step_pwm():  Moves the tilt - uses the bool to determine the direction.
 * bool alive_bool: Is either high (1) or low (0), used for the alive void.
 */

#ifndef stepper_motor_h
#define stepper_motor_h

#include "Arduino.h"
#include "pins_arduino.h"

#define step_pin  D1
#define dir_pin   D2
#define en_pin    D3
#define max_step  200

 class stepper_motor
{
  public:
    stepper_motor();
    void alive();
    void step_pwm();
  private:
    bool alive_bool;
    bool position_bool;
    int step_count;
};

#endif

main:
#include "stepper_motor.h"

stepper_motor motor;
int state = 0;
void setup() {
  // put your setup code here, to run once:
}

void loop() {

      motor.step_pwm();
}

The motor moves, so the step signal seem to be correct.
But enable and dir seem to incorrect, or are pretty sure that they are.
So what is wrong with those signal? do they not follow the required timing?

Check this statement "delay(0.005);"

See http://forum.arduino.cc/index.php?topic=317628.0

delay() works but not delayMicroseconds().. delay works due to the code overhead is around 12 ms


text:
How to Factory reset ESP8266?
I want to use ESP8266 to send emails. I tried twice flashing the Firmware to a particular firmware as suggested in a tutorial. Now both my ESP are unresponsive to AT commands. Let me know the way to RESET it. CH_PD + VCC + RST (Tried this combination), No success there any thing i am missing?

Flash the correct firmware.

You are missing that this is the Arduino SE.  You might get better answers on the EE SE which covers ESP8266

AT commands are executed by the AT interpreter firmware. If you've been attempting to flash other firmware to the ESP8266 module, there is no longer any code in it that interprets AT commands. If you want to it to respond to AT commands again, you'll need to re-flash it with that firmware.

You need to reflash the "AT Firmware" you probably overwrited.
Just follow the instructions in the Espressif board to get the latest one using their "Flash Download Tool".


text:
How can the Arduino check if it is connected to a PC and the PC is on?
I have been searching around the Internet to find if there is a way to check whether an Arduino is connected to a PC or not.
For example: if my PC is turned on, the Arduino will listen to any serial commands it receives, BUT if my PC is turned off, the Arduino will receive some random characters.
How can the Arduino check if it is connected to PC and the PC is on?

Read How does this code line detect if a serial interface is connected?. If it doesn't provide a satisfactory answer, update your question to reflect your additional requirements.

You'd have to write some application on your PC, that for example, sends "PONG" when it receives "PING". You could then "ping" the PC every now and then, to check if it responds (thus is connected/on).

Alternatively, you could check the 5V USB line, that would indicatie that your PC is on (usually). But that only works if you normally run it off the barrel jack. (So doesn't really apply to Nano, but you could make an alternative circuit.) You could maybe measure resistance on the data lines, but I'm not sure if that's safe/possible.

Have you checked if the USB ports on your PC will remain powered if the PC is off?

if my PC is turned off, the Arduino will have some predetermined patterns. - what do you mean?

Is it a desktop PC or laptop?

As suggested by Paul & Gerben, you could check the 5V USB line to see if it has a voltage or not.
I am assuming from your question that the Arduino is not powered from the USB line. I am also assuming that the USB port is not powered when the PC is turned off.
All you have to do is connect VUSB to a digital input through a resistor like so:

Alternatively, you could have the computer send a pre-determined message telling the Arduino that its alive.
If the Arduino receives this message then it lights up the LED on pin 13. If the Arduino hasn't received the "I'm alive" message for a while (ie. a timeout) it then turns off the LED.
A simple PC program could be written to automate this task.

jumper reset -> ground and rx -> tx (with power disconnected)
connect power, open serial monitor in arduino ide and type anything in and input. if the serial monitor echoes what you typed in, then your connection is good and you should look elsewhere for problems.
Found this solution on the arduino.cc community site.

How does your suggestion enable the arduino to establish if it is connected and what portion of the code to run, as requested in the original post?

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Sum values, store them and print the last value
I have a mass flow meter connected to an Arduino Uno board. I have managed to read the volume flow in L/hour, but now I'm struggling to implement a code that stores the values so that I see the number of Liters used.
For instance, I can see on my monitor this:
0 L/hour
0 L/hour
And if I have some water running through,
10 L/hour
20 L/hour
20 L/hour
Then when I stop the flow it goes back to 0.
0 L/hour
Is there any ways to sum up time instances, get the total number of liters and keep it printed during every instance?
Mathematically is not that difficult (Volume = Volume Flow in L/hour * time), but I don't know how to implement this. Can anyone help with this? It can be in seconds or ms or whatever.
Paul

What you want to do is integrate the flow rate vs time curve. You have to keep track of the current flow rate. You also need to choose some unit of time measurement; this depends on how often you're sampling the flow rate. For instance, if you sample it every second, then you should convert your L/hr flow rate to L/s. This means a flow rate of 10L/hr is equivalent to 10L/3600s = 0.002778 L/s. So, if you get a reading of 10 L/hr for 10 seconds, 0.002778 L/s * 10 s = 0.02778 L of water flowed through your valve or whatever. An accumulating sum is what you need. You can try something like this:
#define INTERVAL 1000  // sampling interval in millisec
#define HR_TO_SEC 2.778E-4  // number of hours in a second

int curr_rate = 0;  // current flow rate in L/hr
unsigned long lastRead = 0;  // the last time the rate was sampled
float totalVolume = 0;

void loop(){
  if (millis() - lastRead >= INTERVAL){
    lastRead += INTERVAL;
    curr_rate = getFlowRate();   // or whatever function you call; should take << 1 sec
    totalVolume += curr_rate * HR_TO_SEC;  // update the volume
    Serial.println(totalVolume, 4);
  }
}

This rectangular method is reasonably accurate, depending on your application. If you want a better approximation, google "trapezoidal numerical integration" or "Simpson's method" if you want even better approximation.

The higher order integration methods achieve better accuracy by leveraging the smoothness of the integrand. Here, since there is a valve, the flow is unlikely to be smooth. If you want better accuracy, you only have to sample at shorter intervals.

Also, I replaced lastRead = millis(); by lastRead += INTERVAL;. Otherwise you have a systematic bias, as the average sampling interval would be larger than INTERVAL.

Thank you both for the help. I have managed to implement this code and it does indeed store the data. I have poured 1 L of water through the meter and the monitor reads 1.2 L. Not a huge difference, but  I will change the method of integration and we will see if I can correct that. Also, I had to remove "unsigned" for "float totalVolume = 0;". The code would give an error otherwise.

@Paul You can do as Edgar Bonet says and reduce the interval to 200 ms maybe. Also take care to change HR_TO_SEC to reflect that: convert your interval to hours. If this solves your problem, consider accepting it.

Okay. I will do some experiments these days and see how it goes. I will write back! Thank you

This  will be helpful.
reading is your flow meter value in L/Hour
float reading;//value of the flow meter
long startTime;
float total=0;

void setup() {
  Serial.begin(9600);
  startTime=millis();

}

void loop() {
//read your flow meter to reading variable.
 total+=reading*float((millis()-startTime))/3600000.0;
 Serial.println(total);

}

Thank you very much! I have tried with this code and it keeps giving me 0. Also, I needed to add long startTime=millis(); instead of simply declaring long startTime and then calling it. Is the "reading" function responsible for me getting 0? Does it have to be related to the signal or the pinmode?

reading is the variable..You must pass your flow meter reading to that variable as a float type.
you must enter it before Serial.println() function as I commented.
if you can give previous code,I will be  able to give full code.

The code can be found here: http://forum.arduino.cc/index.php?topic=8548.0 (It is too long to post it here). Thank you!

In a recent comment, you posted a link to a forum thread with the
code for reading the sensor. You should have provided this information
up front, because it completely changes the problem. It appears that the
flow meter sends pulses at a frequency proportional to the volume flow,
and the code uses an interrupt to count the pulses over a specified
time.
TisteAndii's answer suggests you integrate the flow readings to get a
volume. And that suggestion makes perfect sense given the limited
information he had available at the time. Now that we know how the flow
meter is read, it makes no sense anymore:

the interrupt service routine counts a number of pulses that is
proportional to the total volume that has gone through the meter
the linked code differentiates that reading in order to get the flow
you are now integrating that flow in order to get the total volume.

Instead of doing an integration on top of a differentiation, you could
just convert the raw reading into a volume. Then you do not have to
worry about any approximations done while differentiating or
integrating.
In the forum thread it is stated:

Pulse frequency (Hz) in Horizontal Test= 7.5Q, Q is flow rate in L/min.

Writing this in a more mathematically accurate form (i.e. with
unit-correctness) gives:

f/Hz = 7.5 Q/(L/min)

where f is the frequency and Q the volume flow.
Given that 7.5 Hz⋅min = 450 pulses, the above equation can be rewritten as

f = 450 pulses/L × Q

or, in terms of integrated quantities:

volume = (pulse count) / (450 pulses/L)

Here is an example code that just convert the pulse count to a volume:
// Calibration constant of the flow meter.
const float calibration = 1/450.0;  // 450 pulses per liter

// How often to print the measured volume.
const uint32_t print_interval = 1000;  // once per second

// Number of pulses counted so far.
volatile uint32_t pulse_count;

// Count the pulses inside an ISR.
void count_pulse() { pulse_count++; }

// Return volume reading, optinally resetting the count to zero.
float totalVolume(bool reset = false)
{
    noInterrupts();
    uint32_t pulse_count_copy = pulse_count;
    if (reset) pulse_count = 0;
    interrupts();
    return pulse_count_copy * calibration;
}

void setup()
{
    pinMode(2, INPUT_PULLUP);
    attachInterrupt(0, count_pulse, RISING);
    Serial.begin(9600);
}

void loop()
{
    static uint32_t last_print;
    if (millis() - last_print >= print_interval) {
        last_print += print_interval;
        Serial.println(totalVolume());
    }
}

Note that you may want to reset the count from time to time. I added an
optional parameter to totalVolume() for this purpose. If you never
reset the counter, it will overflow after approximately
9544 m3.


text:
Can't reprogram atmega328p chips using nano as ISP
Using nano clone as an ISP on a breadboard- as shown here - http://www.martyncurrey.com/arduino-nano-as-an-isp-programmer/
Previously, it worked great.  However, recently, chips that I have bootloaded and programmed have, when added to the breadboard for reprogramming, caused the USB connection to drop.  The heartbeat LED on the nano also dims slightly which makes me wonder if it's a power issue?
Either way, this means that I can't program the chip.
Does anyone know how to fix this?  The breadboard circuit will happily program new chips.
The programs on the chips that aren't working often include blink on pin 19 on the DIP chip (D13) - and when I disconnect the link from this to D13 on nano, the USB connection is restored.
But otherwise I am very confused, have got about 7 chips with the same issue and would be great to fix it.
Ideas?  Thanks

When you put a chip-to-program on your programming breadboard, are any of that chip's pins connected other than SCK, MISO, MOSI, RESET, VCC, GND, and crystal?

Aref and avcc also connected to +5v.  But other than that, no.

After replacing naked wire from D13 nano to SCK on chip with a 330ohm resistor, I was able to program 3/7 of the chips.  The others still exhibit the problem of not being recognised.  Ideas?

I don't know what the problem is or why the 330Ω resistor made a difference.  If you have a storage scope, verify that Reset is staying pulled low and that SCK transitions are clean.  See diagrams and discussion on pp. 2,3 of Atmel's AVR910: In-System Programming document.  Note, the resistors in figure 3 there are between the device being programmed and its SPI peripherals, not between the device and the programmer, so are not the same as adding a resistor like you did.  Also, have you tried any other values in series, like 100Ω or 1000Ω?


text:
Serial communication with Python
I am trying to send integer from my Python program to Arduino MEGA.
If I send 1, the LED should turn on and If  I send 0 the LED should turn off.
I was able to write Python code correctly as I think. I have configure the port and made serialWrite(val) function for send data to Arduino only if data is changed.
This not a full program. It has while loop. So, it writes data to Arduino rapidly. I used serialWrite(val) function to prevent that.
But, the LED never turns off, if I send 0. It turns on only. What are the problems in my code?
import serial as ser

prt = ser.Serial(
port='COM3',
baudrate=9600,
parity=ser.PARITY_NONE,
stopbits=ser.STOPBITS_ONE,
bytesize=ser.EIGHTBITS
)

preSerVal=0
#function for send data..data will send only val is changed
def serialWrite(val):
    global preSerVal
    if(not preSerVal == val):
        prt.write(str(val)+'\r\n')
        preSerVal=val

This is my Arduino program.
void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
}
byte incomingByte;

void loop()
{
  if (Serial.available() > 0) {
    incomingByte = Serial.read();
      if (incomingByte == '1') {
        digitalWrite(13, HIGH);
    } else if (incomingByte == '0') {
        digitalWrite(13, LOW);
    }
  }
}

UPDATE 1
I write testing program like this.
Python code:
import serial as ser
import time

preSerVal=0
prt = ser.Serial(
port='COM3',
baudrate=9600,
parity=ser.PARITY_NONE,
stopbits=ser.STOPBITS_ONE,
bytesize=ser.EIGHTBITS
)
def serialWrite(val):
    global preSerVal
    if(not preSerVal == val):
         prt.write(str(val)+'\r\n')
         preSerVal=val

while 1:
   for i in range(0,10):
        serialWrite(0)
   time.sleep(1)
   for i in range(0,10):
        serialWrite(1)

Arduino code:
void setup() {
 Serial.begin(9600);
 pinMode(13, OUTPUT);
 digitalWrite(13, LOW);
}
byte incomingByte;

void loop()
{
  if (Serial.available() > 0) {
    incomingByte = Serial.read();
  if (incomingByte == '1') {
    digitalWrite(13, HIGH);
  } else if (incomingByte == '0') {
    digitalWrite(13, LOW);
  }
 }
}

This code gives this result.
see the video bellow:
https://www.youtube.com/watch?v=utC4vo8YDVU&list=PLM5AA5oFchgC25da44Q2X900pz0eojSQJ&index=1
UPDATE 2
This is a piece of code..it sends 0..i checked it.
try:
    circles = np.uint16(np.around(circles))
    for i in circles[0,:]:
        houghCenter=(i[0],i[1])
        cv2.circle(src,houghCenter,i[2],(0,255,0),2)
        cv2.circle(src,houghCenter,2,(0,255,255),1)
        cv2.circle(drawing,houghCenter,i[2],(0,255,0),2)
        cv2.circle(drawing,houghCenter,2,(0,255,255),1)
        #print (houghCenter,"   ",contourCenter)
        dx=math.fabs(houghCenter[0]-contourCenter[0])
        dy =math.fabs(houghCenter[1]-contourCenter[1])
        if (dx>diff and dy>diff):
            serialWrite(0)
        else:
            serialWrite(1)
except Exception:
    serialWrite(0)

You need to post the Python while loop to get a more specific answer. But I'll bet you just aren't sending enough 0s between 1s, for you to notice the LED going off. You did say the while loop is fast. Perhaps you should try slowing it down with time.sleep(1) and see if anything changes.

@TisteAndii .. Thanks... I cant slow down while loop..I have checkered,0 is sent by while loop. That's OK.

please post the Python while loop. Is the Arduino code working with IDE console ?

Its huge code with some image processing code...I have update my post..plz see it..

add print("0/1") to see how fast 0 and 1 are sent on PC side. Is the code executed once or in a loop ? What is the expected behaviour and the real bahaviour ?

I previously added a print command to same place that I call serialWrite(val) function..It was very speed..that's why I used serialWrite(val) function.

I understand the serialWrite() avoids sending twice same data. Then add the print after prt.write if the 1 and 0 are wery fast you will not have time to see anything blink. If you do not describe the expected and observed behaviour I cannot help you

Let us continue this discussion in chat.

You are missing a second time.sleep(1). That is why the first loop executes correctly and the the LED flashed faster. Without any time.sleep() at all, the LED is going OFF/ON so fast that you cannot see it happen (may be it's just not so bright as usually).
while 1:
   for i in range(0,10):
        serialWrite(0)
   time.sleep(1)
   for i in range(0,10):
        serialWrite(1)
   time.sleep(1)

Its worked now...Thanks..But,How can I apply to my image processing code?

I have update my post again with piece of image processing code.what is the wrong of that?

@NSiri Try adding a delay each time you send a 0 or 1. If your algorithm can afford it.


text:
Accelerometer fix values
I use Arduino Uno with an Accelerometer ADXL345-gy-291 (the full name of the ship) i did hook it up like this

Note I'm using SPI Communication, that was the right one to use in my case.
when I plug in my Arduino here what does my serial monitor give me

as you can see, it sends back fixed values no matter the movement of the ship is.
the code I use is :
#include <SparkFun_ADXL345.h>
ADXL345 adxl = ADXL345(10);

void setup(){

  Serial.begin(9600);
  Serial.println("SparkFun ADXL345 Accelerometer Hook Up Guide Example");
  Serial.println();
  adxl.powerOn();
  adxl.setRangeSetting(16);
  adxl.setSpiBit(0);
  adxl.setActivityXYZ(1, 0, 0);
  adxl.setActivityThreshold(75);
  adxl.setInactivityXYZ(1, 0, 0);
  adxl.setInactivityThreshold(75);
  adxl.setTimeInactivity(10);
  adxl.setTapDetectionOnXYZ(0, 0, 1);
  adxl.setTapThreshold(50);
  adxl.setTapDuration(15);
  adxl.setDoubleTapLatency(80);
  adxl.setDoubleTapWindow(200);
  adxl.setFreeFallThreshold(7);
  adxl.setFreeFallDuration(30);
  adxl.InactivityINT(1);
  adxl.ActivityINT(1);
  adxl.FreeFallINT(1);
  adxl.doubleTapINT(1);
  adxl.singleTapINT(1);
}
void loop(){
  int x,y,z;
  adxl.readAccel(&x, &y, &z);
  Serial.print(x);
  Serial.print(", ");
  Serial.print(y);
  Serial.print(", ");
  Serial.println(z);
  ADXL_ISR();
}
void ADXL_ISR() {
  byte interrupts = adxl.getInterruptSource();

  if(adxl.triggered(interrupts, ADXL345_FREE_FALL)){
    Serial.println("*** FREE FALL ***");
  }

  if(adxl.triggered(interrupts, ADXL345_INACTIVITY)){
    Serial.println("*** INACTIVITY ***");
  }

  if(adxl.triggered(interrupts, ADXL345_ACTIVITY)){
    Serial.println("*** ACTIVITY ***");
  }

  if(adxl.triggered(interrupts, ADXL345_DOUBLE_TAP)){
    Serial.println("*** DOUBLE TAP ***");
  }

  if(adxl.triggered(interrupts, ADXL345_SINGLE_TAP)){
    Serial.println("*** TAP ***");
  }
}

so I wonder what was the mistake I made there?

You need to level-shift the Arduino's 5V signals to the module's I/O range of 1.7 - 3.6 V if you want to use SPI; that is, if you haven't damaged it already. I suggest you follow the tutorial here though. It employs I2C instead of SPI but is specific to your particular module. There are no level-shifters needed in this case. Simply connect VCC and CS to 3.3 V, the I2C pins to 3.3 V through 4.7k pull-ups and the GNDs together.

Those modules from Sparkfun and from Chinese suppliers already include a voltage regulator, accepting from 2.0-2.5V to 5-6V Vcc.


text:
I2C between Yun Shield (Dragino) and UNO R3 problem
I am having problems with I2C communications between my Dragino Yun and an Arduino UNO R3.
I can have the Dragino request data (using Wire.onRequest on UNO) from the UNO and it works great, however, when I have the UNO sending and the Dragino using Wire.onReceive it's not picking up any data!?
What are the SDA and SCL pins on the Dragino? Are they the same as the UNO? Are there any specific difficulties involved for this setup?


text:
Arduino code not starting at beginning after poweroff
I created a few Arduino-XBee temperature sensor nodes that send data to another XBee node.js server. I'm running into a few issues trying to write a function to initiate a handshake and receive an identifier number to start sending data (so its scalable rather than hard-coded on each) while the receiver is already communicating with pre-established nodes.
The first issue I'm having is that the Arduino nodes do not seem to start from the beginning of their code when I unplug them and then reapply power. They already think they have their identifier number if another node is running, and I have to push the reset button on them to get them to run their code fresh and establish their own handshake ID. Is there anything I can put in the code or a way that I can easily modify the circuitry to make them actually reset and start fresh when they lose power?
The circuitry I'm using is a basic thermistor voltage-divider, XBee module, and 5V battery pack. Here's what I've got so far for the code on the Arduino side:
#include <SoftwareSerial.h>
#include <math.h>

// Global variables
int AnalogPin = A2; // has much less jumpy readings than A0 (maybe A0 slightly damage from overuse)
float V_source = 4.90; // measured
SoftwareSerial XBee(2,3); // RX, TX
String identifier = "";
int receivedID = 0;

// Calculate thermistor voltage
float Voltage(float RawADC) {
  float meter_calibration = 0; // don't seem to need, matches my multimeter exactly
  float V_therm = (V_source * RawADC) / 1024.0;
  V_therm += meter_calibration;
  return V_therm;
}

// Calculate thermistor resistance
// sometimes a bit off what voltage divider eq says it should be (probably due to input impedance of ADC)
float Thermistor(float V_therm) {
  float resistance_calibration = 25; // possibly small breadboard/wires resistance
  float R_known = 560 + resistance_calibration; // measured (1% tol resistor)
  float R_therm =  ((R_known * V_therm) / (V_source - V_therm));
  return R_therm;
}

// Base conversion
float log2(float num) {
  return (log(num) / log(2));
}

// Calculate temperature
float Temperature(float R_therm) {
  float A = 0.0164872;
  float B = -0.00158538;
  float C = 0.0000033813;
  float temp_K = 1 / (A + B*log2(R_therm) + C*pow(log2(R_therm),3));
  return temp_K;
}

// Convert to Celsius or Fahrenheit
float ConvertTemp(float temp_K, char T) {
  if (T == 'C')
    return (temp_K - 273.15);
  else if (T == 'F')
    return (temp_K * 1.8 - 459.67);
}

// Setup
void setup() {
  int idStart = 0;
  receivedID = 0;
  Serial.begin(9600);
  pinMode(AnalogPin, INPUT);
  XBee.begin(9600);
  for (int i=0; i<100; i++) {
    Serial.print("\n");
  }
  Serial.println("Broadcasting...");
}

// Main
void loop() {
  delay(1000);

  // Initiate handshake
  if (identifier == "") {
      XBee.print("BROADCASTING"); // ascii text
      XBee.write("\n");  // binary data
  }
  delay(3000);

  // Receive buffer, check for and confirm ID
  if (XBee.available() && (identifier == "")) {
    String msg = "";
    char r = XBee.read();

/*
    // Error checking for first-only numeric ID (testing)
    msg = msg + r;
    String intString = "";
    int intStart = 0;
    int i = 0;
    while (intStart != 2 && i < msg.length()) {
      if (intStart == 0) {
        if (isDigit(msg[i])) {
              intString += msg[i];
              intStart = 1;
           }
      }
      else if (intStart == 1) {
        if (isDigit(msg[i])) {
              intString += msg[i];
              intStart = 1;
           }
      }
      else if (!isDigit(msg[i])) {
        intStart = 2;
      }
      i++;
    }
    Serial.print("testing: ");
    Serial.println(intString);
    identifier = intString;
*/

    identifier = r;
  }

  // handshake established
  if ((identifier != "") && (receivedID == 0)) {
    Serial.println();
    Serial.print("RECEIVED IDENTIFIER: ");
    Serial.println(identifier);
    Serial.println();
    receivedID = 1;
  }

  // Calculate and send temperature along with identifier
  while (receivedID == 1) {
        // ADC and V_therm values
    /* Good to get two or more analog readings and discard the first or take the average
    apparently analog pins are multiplexed so this gives it time to settle */
    float RawADC_1 = analogRead(AnalogPin); // toss 1
    float RawADC_2 = analogRead(AnalogPin); // average 2,3
    float RawADC_3 = analogRead(AnalogPin);
    float RawADC_avg = (RawADC_2 + RawADC_3) / 2.00;
    Serial.print("Raw ADC value: ");
    Serial.println(RawADC_avg);
    float V_therm = Voltage(RawADC_avg);
    Serial.print("Voltage across thermistor: ");
    Serial.println(V_therm);

    // Thermistor resistance
    float R_therm = Thermistor(V_therm);
    Serial.print("Resistance of thermistor: ");
    Serial.println(R_therm);

    // Temperature in Kelvin, Celsius, Fahrenheit
    float temp_K = Temperature(R_therm);
    Serial.print(temp_K);
    Serial.print("K   ");
    float temp_C = ConvertTemp(temp_K, 'C');
    float temp_F = ConvertTemp(temp_K, 'F');
    Serial.print(temp_C);
    Serial.print("C   ");
    Serial.print(temp_F);
    Serial.println("F   ");

    // XBee
    String mytemp = String(temp_F);
    String msg = String(identifier + " " + mytemp);
    XBee.print(msg); // ascii text
    XBee.write("\n");  // binary data
    Serial.print("Message sent to XBee: ");
    Serial.println(msg);
    Serial.println();

    delay(2000);
  }

}

You can put that idea out of your head right now! Do you think that the compiler inserts some "jump to random location" code? Of course it starts at the start. The problem is somewhere else.

They already think they have their identifier number if another node is running - how do you know that?

@NickGammon because they start sending temp data as if they have already received their identifier which is the same as the currently running node. If I hit the reset button as I plug them in, this problem goes away. Is there any capacitance on the board or something? Also if I have one node running on battery and plug the other node into my computer then upload the sketch it works properly. For some reason if I plug the second to battery, it uses the same identifier as the first.

My guess is that the problem is with the XBee. Variables don't keep their values between power cycles or resets.

Yeah so my pre-connected nodes were broadcasting to everything and sending their identifier to the new nodes. I still don't know exactly why using the reset/upload buttons made it work properly, but I fixed the issue with correct addressing.


text:
Interrupt and delay problems on Attiny 85
I wrote this code and uploaded it to attiny85:
 int hours = 2;
 int minutes = 4;
 static int MINUTES_COUNT_BIT = 5;
 static int HOURS_COUNT_BIT = 3;
 #define button 2
void setup() {
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(button,INPUT);

  attachInterrupt(0,pin_ISR,CHANGE);

}

void loop() {

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

}

void pin_ISR(){
    if(digitalRead(button)==LOW){
      for(int i = HOURS_COUNT_BIT;i>=0;i--){
      byte act_bit = bitRead(hours,i);

      switch(act_bit){
        case 0:
          digitalWrite(3,HIGH);
          delay(1000);
          digitalWrite(3,LOW);
          delay(1000);
          break;
        case 1:
          digitalWrite(4,HIGH);
          delay(1000);
          digitalWrite(4,LOW);
          delay(1000);

          break;
        }

    }
  }

  }

When I click button it lights up LEDs but it is so much faster than 500 milliseconds it looks like that:
https://drive.google.com/open?id=0ByeWvrEgy2gRNUp3MDNxQTAxd2c
Please help

Maybe you did not Burn Bootloader with the same MHz setting as you uploaded the Sketch.

Delay in an ISR?

In short:

Arduino delay() is relying on millis().
The millis() function is  updated by timer ISR.
ISR handler blocks all other ISRs by disabling global interrupts.
No update for millis results into deadlock in delay if you use it in another ISR

And recommendation for ISRs? Do it as short as possible! Set some volatile flag and do the action later outside of ISR.


text:
ATTiny85 I2C LCD
My setup is as follows:

Arduino IDE 1.6.11
Arduino Pro Mini as ISP
ATTiny85 1602A LCD with I2C board

The libraries I use are:

TinyWireM (source: https://github.com/adafruit/TinyWireM)
LiquidCrystal_I2C (modified for ATTiny) (source: http://playground.arduino.cc/Code/USIi2c)

The Sketch I use to test with:
#include <TinyWireM.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F,16,2);  // set address & 16 chars / 2 lines

void setup()
{

  TinyWireM.begin();                    // initialize I2C lib
  lcd.init();                           // initialize the lcd
  lcd.backlight();
  lcd.clear();  // Print a message to the LCD.
}

void loop()
{
  lcd.setCursor(0, 0);
  lcd.print("Hello World on Attiny85");
  delay(2000);
}

The address is 0x3F, I found this using the scanner sketch, I also tested the LCD using the Arduino Pro Mini directly, it works fine.
The result of this setup is a single line of black blocks. My guess is that the initialization failed in some way. I have tried some things to make it work:

Pull-ups on SDA and SCL
Isolated from Arduino with regulated power supply
Setting contract with the pot meter on the back
reinstall of PC
reinstall of Arduino IDE
1MHz, 8Mhz, TinyCore default and High-Low Tech
Replaced FTDI
Replaced Tiny85
Replaced LCD
Replaced Arduino Pro Mini

Some pictures:

[EDIT]
Final sketch:
#include <TinyWireM.h>                  // I2C Master lib for ATTinys which use USI
// #include <LiquidCrystal_I2C.h>
#include "LiquidCrystal_attiny.h"
LiquidCrystal_I2C lcd(0x27,16,2);

void setup() {

  // Now set up the LCD
  //lcd.begin(16,2);               // initialize the lcd
  pinMode(4, OUTPUT);
  lcd.init();
  lcd.backlight();
  lcd.home ();                   // go home
  lcd.print("Weatherstation");
  lcd.setCursor ( 0, 1 ); // go to position
  lcd.print("BMP180");
  delay(2000);
}
void loop() {
  digitalWrite(4, HIGH);
  delay(100);
  digitalWrite(4, LOW);
  delay(100);
}

Comments are not for extended discussion; this conversation has been moved to chat.

It looks like you did not connect the SCL line.....
Make sure you're using the correct pins! they default to pin0 for SDA and pin2 for SCL.

Please post further comments in the chat room above. Comments posted here are likely to be deleted.

Just a question, why do you want to use and ATtiny when you can just program any I2C with your Arduino??? P.S. Just trying to learn so no hate for this question please.

no problem, I will skip my usual hate-reply :) Nick may hate-reply for not using the chat box though, haha. I choose the ATTiny over the Arduino because my project will sleep a lot and use a battery 3.7V power source. ATTiny will run for weeks/months vs Arduino for days.

wasted too much time on these devices, trying to get them working, use an earlier ide, caps, pullups, reinstall usb drivers, modified libs yada yada yada.
don't waste your life on these attiny's, use 328Ps with bootloader pre installed for your pcbs.

these days maybe a Pi Pico W running Micropython is the best bang for the buck, if the high power consumption is not an issue

After hours of Googling, I found a blog post by Dimitris Platis where he describes using an ATTiny85 with I2C LCD. I emailed the guy and he replied with a link to his LCD I2C ATTiny library on GitHub. Using this library with the TinyWireM and the right core, it instantly worked.
My final setup is with a 4.7K resistor on SDA and SCL, I will add the final sketch in the original post under [EDIT]. This adventure took me two weeks so I hope it helps someone else some day.
LCD library used: https://github.com/platisd/ATtiny85-LCD-library
TinyWireM used: https://github.com/adafruit/TinyWireM
Core used: https://github.com/vprimachenko/ArduinoTiny

It doesn't look like you have an Arduino Pro Mini. I2C lines on a Pro Mini are on pins A4 for SDA and A5 for SCL and those 2 pins are placed at an odd location - check picture.
Hope I was helpful :)

He is using an ATtiny85 to talk to the LCD. The other Arduino is just for programming - as far as I can tell.

Well his Arduino seems still not like a Pro Mini so I don't know if it makes a difference.

you are right :) but it does not matter, as Nick said it is just a programmer

I own a few of those, they are cheap Chinese clones, pins are located slightly differently.

I've spent an hour doing this problem and searched a lot. If you still didn't find the solution by doing this. Pls try to reduce the clock speed from Internal 8 MHz to Internal 1MHz. That way it works mine.

authors: สมพล กริ่งกรับ


text:
Arduino toggles on multiplexer not working
I am currently working on an Arduino project that needs alot of on/off toggles. Because my Arduino Mega does not have enough pins I connected 5 multiplexers to it (the MuxShield 2's). The problem is that only one of them functions correctly at any given moment.
Each multiplexer has 3 rows and they each have their _shiftReg1, _shiftReg2 and _shiftReg3 array in the library. I think there's something up with this, when I loop over the rows of each multiplexers only the first first, second and third row of any given multiplexer work as expected. The outputs on each row light up one by one as they should. But when I loop over a row number which is already looped over all the outputs turn on at once. I have no idea why this is happening and really need some help figuring this out.
This is my main project file, I commented which loops work and which ones don't:
#include <Arduino.h>

#include <MuxShield.h>
#include <ToggleMux.h>

// Initialize the Mux Shields
MuxShield muxShield1 = MuxShield(31, 29, 27, 25, 23, 10, 11, 12, A0, A1, A2);
MuxShield muxShield2 = MuxShield(41, 39, 37, 35, 33, 10, 11, 12, A3, A4, A5);
MuxShield muxShield3 = MuxShield(2, 4, 6, 7, 8, 10, 11, 12, A6, A7, A8);
MuxShield muxShield4 = MuxShield(51, 49, 47, 45, 43, 10, 11, 12, A9, A10, A11);
MuxShield muxShield5 = MuxShield(22, 24, 26, 28, 30, 10, 11, 12, A12, A13, A14);
// ToggleMux
ToggleMux t1 = ToggleMux(muxShield1, 1, 0, muxShield3, 3, 0);
ToggleMux t2 = ToggleMux(muxShield1, 1, 1, muxShield3, 3, 1);
ToggleMux t3 = ToggleMux(muxShield1, 1, 2, muxShield3, 3, 2);
ToggleMux t4 = ToggleMux(muxShield1, 1, 3, muxShield3, 3, 3);
...

void setup()
{
    muxShield1.setMode(1, DIGITAL_IN);
    muxShield1.setMode(2, DIGITAL_IN);
    muxShield1.setMode(3, DIGITAL_IN);

    muxShield2.setMode(1, DIGITAL_IN);
    muxShield2.setMode(2, DIGITAL_IN);
    muxShield2.setMode(3, DIGITAL_IN);

    muxShield3.setMode(1, DIGITAL_IN);
    muxShield3.setMode(2, ANALOG_IN);
    muxShield3.setMode(3, DIGITAL_OUT);

    muxShield4.setMode(1, DIGITAL_OUT);
    muxShield4.setMode(2, DIGITAL_OUT);
    muxShield4.setMode(3, DIGITAL_OUT);

    muxShield5.setMode(1, DIGITAL_OUT);
    muxShield5.setMode(2, DIGITAL_OUT);
    muxShield5.setMode(3, DIGITAL_OUT);
}

boolean hilo = true;

void loop()
{
    for (int i = 0; i < 16; i++) {     // works as expected
      muxShield3.digitalWriteMS(3, i, hilo ? 1 : 0);
      delay(10);
    }

    for (int i = 0; i < 16; i++) {     // turns them all on at once because row 3 has already been looped over
      muxShield4.digitalWriteMS(3, i, hilo ? 1 : 0);
      delay(10);
    }

    for (int i = 0; i < 16; i++) {     // works as expected
      muxShield4.digitalWriteMS(1, i, hilo ? 1 : 0);
      delay(10);
    }

    for (int i = 0; i < 16; i++) {     // works as expected
      muxShield4.digitalWriteMS(2, i, hilo ? 1 : 0);
      delay(10);
    }

    // for (int i = 0; i < 16; i++) {
    //   muxShield4.digitalWriteMS(3, i, hilo ? 1 : 0);
    //   delay(10);
    // }

    for (int i = 0; i < 16; i++) {    // turns them all on at once because row 1 has already been looped over
       muxShield5.digitalWriteMS(1, i, hilo ? 1 : 0);
       delay(10);
     }

     for (int i = 0; i < 16; i++) {    // turns them all on at once because row 2 has already been looped over
       muxShield5.digitalWriteMS(2, i, hilo ? 1 : 0);
       delay(10);
     }

     for (int i = 0; i < 16; i++) {    // turns them all on at once because row 3 has already been looped over
       muxShield5.digitalWriteMS(3, i, hilo ? 1 : 0);
       delay(10);
     }
     hilo = !hilo;

  // t1.listen();
  // t2.listen();
  // t3.listen();
  // t4.listen();
    ...
}

This is my toggle library:
#include "Arduino.h"
#include "ToggleMux.h"
#include "MuxShield.h"

ToggleMux::ToggleMux(MuxShield muxShieldIn, int inRow, int inBit, MuxShield muxShieldOut, int outRow, int outBit) :
_muxShieldIn(muxShieldIn),
_muxShieldOut(muxShieldOut),
_inRow(inRow),
_inBit(inBit),
_outRow(outRow),
_outBit(outBit)
{
    _state = 0;
    _previous = 0;
    _reading;

    _time = 0;
    _debounce = 100;
}

void ToggleMux::listen() {
    _reading = _muxShieldIn.digitalReadMS(_inRow, _inBit);
    _state = _muxShieldOut.digitalReadMS(_outRow, _outBit);

    if (_reading == 1 && _previous == 0 && millis() - _time > _debounce) {
        if (_state == 1) {
            _state = 0;
        } else {
            _state = 1;
        }

        _muxShieldOut.digitalWriteMS(_outRow, _outBit, _state);
        _time = millis();
    }

    _previous = _reading;
}

void ToggleMux::on() {
  _state = 1;
  _muxShieldOut.digitalWriteMS(_outRow, _outBit, 1);
}

void ToggleMux::off() {
  _state = 0;
  _muxShieldOut.digitalWriteMS(_outRow, _outBit, 0);
}

And this is the MuxShield 2 library:
/*
 MuxShield.cpp - Library for using Mayhew Labs' Mux Shield.
 Created by Mark Mayhew, December 29, 2012.
 Released into the public domain.
 */

#include "Arduino.h"
#include "MuxShield.h"
#include "BitBool.h"

int _shiftReg1[16] = {0};
int _shiftReg2[16] = {0};
int _shiftReg3[16] = {0};

MuxShield::MuxShield(int S0, int S1, int S2, int S3, int OUTMD,int IOS1, int IOS2, int IOS3, int IO1, int IO2, int IO3)
{
    _S0 = S0;
    _S1 = S1;
    _S2 = S2;
    _S3 = S3;
    _OUTMD = OUTMD;
    _IOS1 = IOS1;
    _IOS2 = IOS2;
    _IOS3 = IOS3;
    _IO1 = IO1;
    _IO2 = IO2;
    _IO3 = IO3;

    pinMode(_S0,OUTPUT);
    pinMode(_S1,OUTPUT);
    pinMode(_S2,OUTPUT);
    pinMode(_S3,OUTPUT);
    pinMode(_OUTMD,OUTPUT);
    digitalWrite(_OUTMD,LOW);
    pinMode(_IOS1,OUTPUT);
    pinMode(_IOS2,OUTPUT);
    pinMode(_IOS3,OUTPUT);
}

MuxShield::MuxShield()
{
    _S0 = 2;
    _S1 = 4;
    _S2 = 6;
    _S3 = 7;
    _OUTMD = 8;
    _IOS1 = 10;
    _IOS2 = 11;
    _IOS3 = 12;
    _IO1 = A0;
    _IO2 = A1;
    _IO3 = A2;

    pinMode(_S0,OUTPUT);
    pinMode(_S1,OUTPUT);
    pinMode(_S2,OUTPUT);
    pinMode(_S3,OUTPUT);
    pinMode(_OUTMD,OUTPUT);
    digitalWrite(_OUTMD,LOW);
    pinMode(_IOS1,OUTPUT);
    pinMode(_IOS2,OUTPUT);
    pinMode(_IOS3,OUTPUT);
}

void MuxShield::setMode(int mux, int mode)
{
    switch (mux) {
        case 1:
            switch (mode) {
                case DIGITAL_IN:
                    pinMode(_IO1,INPUT);
                    digitalWrite(_IOS1,LOW);
                    break;
                case DIGITAL_IN_PULLUP:
                    pinMode(_IO1,INPUT_PULLUP);
                    digitalWrite(_IOS1,LOW);
                    break;
                case DIGITAL_OUT:
                    pinMode(_IO1,OUTPUT);
                    digitalWrite(_IOS1,HIGH);
                    break;
                case ANALOG_IN:
                    digitalWrite(_IOS1,LOW);
                    break;
                default:
                    break;
            }
            break;
        case 2:
            switch (mode) {
                case DIGITAL_IN:
                    pinMode(_IO2,INPUT);
                    digitalWrite(_IOS2,LOW);
                    break;
                case DIGITAL_IN_PULLUP:
                    pinMode(_IO2,INPUT_PULLUP);
                    digitalWrite(_IOS2,LOW);
                    break;
                case DIGITAL_OUT:
                    pinMode(_IO2,OUTPUT);
                    digitalWrite(_IOS2,HIGH);
                    break;
                case ANALOG_IN:
                    digitalWrite(_IOS2,LOW);
                    break;
                default:
                    break;
            }
            break;
        case 3:
            switch (mode) {
                case DIGITAL_IN:
                    pinMode(_IO3,INPUT);
                    digitalWrite(_IOS3,LOW);
                    break;
                case DIGITAL_IN_PULLUP:
                    pinMode(_IO3,INPUT_PULLUP);
                    digitalWrite(_IOS3,LOW);
                    break;
                case DIGITAL_OUT:
                    pinMode(_IO3,OUTPUT);
                    digitalWrite(_IOS3,HIGH);
                    break;
                case ANALOG_IN:
                    digitalWrite(_IOS3,LOW);
                    break;
                default:
                    break;
            }
            break;
        default:
            break;
    }

}

void MuxShield::digitalWriteMS(int mux, int chan, int val)
{
    int i;

    digitalWrite(_S3,LOW);                              //S3 here is LCLK
    digitalWrite(_OUTMD,HIGH);                          //set to output mode
    switch (mux) {
        case 1:
            _shiftReg1[chan] = val;                     //store value until updated again

            for (i=15; i>=0; i--) {
                digitalWrite(_S0,LOW);                  //S0 here is i/o1 _sclk
                digitalWrite(_IO1,_shiftReg1[i]);       //put value
                digitalWrite(_S0,HIGH);                 //lactch in value
            }
            break;
        case 2:
            _shiftReg2[chan] = val;                     //store value until updated again

            for (i=15; i>=0; i--) {
                digitalWrite(_S1,LOW);                  //S1 here is i/o2 _sclk
                digitalWrite(_IO2,_shiftReg2[i]);       //put value
                digitalWrite(_S1,HIGH);                 //lactch in value
            }
            break;
        case 3:
            _shiftReg3[chan] = val;                     //store value until updated again

            for (i=15; i>=0; i--) {
                digitalWrite(_S2,LOW);                  //S2 here is i/o3 _sclk
                digitalWrite(_IO3,_shiftReg3[i]);       //put value
                digitalWrite(_S2,HIGH);                 //lactch in value
            }
            break;
        default:
            break;
    }
    digitalWrite(_S3,HIGH);                     //latch in ALL values
    digitalWrite(_OUTMD,LOW);                   //Exit output mode

}

int MuxShield::digitalReadMS(int mux, int chan)
{
    digitalWrite(_OUTMD,LOW);   //Set outmode off (i.e. set as input mode)
    int val;
    switch (mux) {
        case 1:
            digitalWrite(_S0, (chan&1));
            digitalWrite(_S1, (chan&3)>>1);
            digitalWrite(_S2, (chan&7)>>2);
            digitalWrite(_S3, (chan&15)>>3);

            val = digitalRead(_IO1);
            break;
        case 2:
            digitalWrite(_S0, (chan&1));
            digitalWrite(_S1, (chan&3)>>1);
            digitalWrite(_S2, (chan&7)>>2);
            digitalWrite(_S3, (chan&15)>>3);

            val = digitalRead(_IO2);
            break;
        case 3:
            digitalWrite(_S0, (chan&1));
            digitalWrite(_S1, (chan&3)>>1);
            digitalWrite(_S2, (chan&7)>>2);
            digitalWrite(_S3, (chan&15)>>3);

            val = digitalRead(_IO3);
            break;
        default:
            break;
    }
    return val;
}

int MuxShield::analogReadMS(int mux, int chan)
{
    digitalWrite(_OUTMD,LOW);
    int val;

    digitalWrite(_S0, (chan&1));
    digitalWrite(_S1, (chan&3)>>1);
    digitalWrite(_S2, (chan&7)>>2);
    digitalWrite(_S3, (chan&15)>>3);

    switch (mux) {
        case 1:
            val = analogRead(_IO1);
            break;
        case 2:
            val = analogRead(_IO2);
            break;
        case 3:
            val = analogRead(_IO3);
            break;
        default:
            break;
    }
    return val;
}


text:
Bug read an image from SD card and draw it on TFT
I have developed a code to read an image stored on my SD Card and display it on a TFT. I can read the image from the SD Card successfully but I cannot draw it on the TFT. I dunno where is the bug.
Could you please guys help me figure it out?
Board: Arduino DUE

#include <Arduino.h>
#include <SPI.h>
#include <SD.h>
#include <string.h>

#include "ascii_data.h"

#define SERIAL_PORT     9600

#define PIN_SCE         10
#define PIN_RESET       6
#define PIN_DC          5
// #define PIN_SDIN
// #define PIN_SCLK
#define PIN_LED         2

#define LCD_COMMAND     LOW
#define LCD_DATA        HIGH
#define CHAR_WIDTH      6
#define CHAR_HEIGHT     8
#define LCD_WIDTH       84
#define LCD_HEIGHT      48
#define CHARS_PER_ROW   (LCD_WIDTH / CHAR_WIDTH)
#define CHARS_PER_COL   (LCD_HEIGHT / CHAR_HEIGHT)

#define PIN_SCSD        4

void draw();
void reset();
void cls();
void lcdMode(int mode);
void lcdInitialize();
void printString(int y, const char *value);
void printString(int x, int y, const char *value);
int printChar(int x, int y, char value);
void setPixel(int x, int y, int value);
void lcdWrite(int value);

byte data[84][6] = {0};

String input = "";
bool complete = false;

// ----------------------------------------------------------------------------

void setup()
{
  // Enable I/O stream
  Serial.begin(SERIAL_PORT);
  Serial.println("Serial Init..");

  // pin modes
  pinMode(PIN_SCE, OUTPUT);
  pinMode(PIN_RESET, OUTPUT);
  pinMode(PIN_DC, OUTPUT);
  pinMode(PIN_LED, OUTPUT);
  pinMode(PIN_SCSD, OUTPUT);

  // SD stuff
  SD.begin(PIN_SCSD);

  // display stuff
  reset();

  SPI.begin(PIN_SCE);
  SPI.setClockDivider(PIN_SCE, SPI_CLOCK_DIV16);

  lcdInitialize();

  input.reserve(200);

  printChar(0, 0, 'a');
}

void loop()
{
  while (Serial.available() > 0) {
    char ch = (char)Serial.read();
    //Serial.print(ch);
    if (isprint(ch) && ch != '\n') {
      input += ch;
      //Serial.println(input);
    }
    else {
      complete = true;
    }
  }

  if (complete) {
    Serial.print("Command: ");
    Serial.println(input);

    //Serial.println(input.startsWith("exists(") && input.endsWith(")"));

    if (input.startsWith("exists(") && input.endsWith(")")) {
      String file = input.substring(7, input.length() - 1);

      Serial.print("File: ");
      Serial.println(file);

      File f = SD.open(file);
      if (f) {
        Serial.println("File does exists");
        f.close();
      } else {
        Serial.println("File does not exist");
      }

    } else if (input.startsWith("print(") && input.endsWith(".img)")) {
      String file = input.substring(6, input.length() - 1);
      File f = SD.open(file);
      if (f) {
        cls();

        Serial.print("Printing image: ");
        // Dimensionen auslesen
        int width = 0;
        int height = 0;

        char ch = '\0';
        String dim = "";

        while (f.available()) {
          ch = (char)f.read();

          if (ch != ',' && ch != '\n')
            dim += ch;
          else {
            if (width == 0) {
              width = dim.toInt();
              dim = "";
            } else if (height == 0) {
              height = dim.toInt();
            }

            if (ch == '\n') {
              break;
            }
          }
        }

        Serial.print("Dimensions of image: ");
        Serial.print(width);
        Serial.print(" x ");
        Serial.println(height);

        for (int i = 0; i < height; ++i) {
          for (int x = 0; x < width; ++x){
            char ch = '\0';
            while (ch != '\n') {
              ch = f.read();
              if (ch == ','){
                continue;
              }else (ch == '0' || ch == '1') {
                int pix = ch - '0';
                setPixel(x, i, pix);
              }
            }
          }
        }
      }

    } else if (input.startsWith("print(") && input.endsWith(")")) {
      String file = input.substring(6, input.length() - 1);
      File f = SD.open(file);
      if (f) {
        cls();

        int x = 0;
        int y = 0;
        Serial.print("Printing: ");
        while (f.available()) {
          char ch = (char)f.read();
          Serial.print(ch);
          if (-1 == printChar(x, y, ch));

          draw();

          x = (x + 6) % 84;
          if (x == 0) {
            y = (y + 8) % 48;
          }
        }
        Serial.println();

      } else {
        Serial.println("Error: File does not exist");
      }

    } else {
      Serial.println("Unknown command");
    }

    complete = false;
    input = "";
  }

  draw();

  delay(10);

}

// ----------------------------------------------------------------------------

void draw()
{
  lcdMode(LCD_DATA);

  for (int b = 0; b < 6; ++b) {
    for (int x = 0; x < 84; ++x) {
      lcdWrite(data[x][b]);
    }
  }
}

void reset()
{
  digitalWrite(PIN_RESET, LOW);
  delay(500);
  digitalWrite(PIN_RESET, HIGH);
}

void cls()
{
  for (int x = 0; x < LCD_WIDTH; ++x) {
    for (int y = 0; y < LCD_HEIGHT; ++y) {
      setPixel(x, y, 0);
    }
  }
}

void lcdMode(int mode)
{
  digitalWrite(PIN_DC, mode);
}

void lcdInitialize()
{
  lcdMode(LCD_COMMAND);

  // FUNCTION SET (extended instruction set)
  lcdWrite(0x21);

  // SET BIAS
  lcdWrite(0x14);

  // SET TEMP COEFFICIENT
  lcdWrite(0x04);

  // SET CONTRAST
  lcdWrite(0xBF);

  // FUNCTION SET (normal instruction set)
  lcdWrite(0x20);

  // SET DISPLAY MODE (normal)
  lcdWrite(0x0C);

  // reset display
  lcdWrite(0x40);
  lcdWrite(0x80);
}

void printString(int y, const char *value)
{
  printString((84 - strlen(value) * 6) / 2, y, value);
}

void printString(int x, int y, const char *value)
{
  do
  {
    printChar(x, y, *value);
    x += 6;
  } while (*++value != '\0');
}

int printChar(int x, int y, char value)
{
  lcdMode(LCD_DATA);

  if (value < ' ') {
    return -1;
  }

  for (int dx = 0; dx < 6; ++dx) {
    for (int dy = 0; dy < 8; ++dy) {
      setPixel(x + dx, y + dy, !!(font[value - ' '][dx] & (1 << dy)));
    }
  }

  return 0;
}

void setPixel(int x, int y, int value)
{
  if (x >= 0 && x < 84 && y >= 0 && y < 48) {
    if (value) {
      data[x][y / 8] |= (1 << (y % 8));
    } else {
      data[x][y / 8] &= ~(1 << (y % 8));
    }
  }
}

void lcdWrite(int value)
{
  digitalWrite(PIN_SCE, LOW);
  SPI.transfer(PIN_SCE, value, SPI_CONTINUE);
  digitalWrite(PIN_SCE, HIGH);
}

There seems to be a slightly vital part of your program missing - the part that actually writes the data[] array out to the screen...

@Majenko It seems to be in draw().

Ah so it does, didn't see that.

@Nsmit What do you see in the serial monitor? Did your code get so far as printing the dimensions correctly? Have you tried printing the contents of data to see if the image was written to it correctly? Have you successfully drawn or printed anything to the screen?

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Prevent 5V output on Arduino Nano 5V pin
I just made an addressable RGB LED strip controller but im concerned about if I'm going to break the thing.
I know it sounds vague so let me elaborate: there is an external power supply connected to my 5V pin and the LED strips positive so it powers both the strip and Arduino, but I also have my Arduino connected to my PC at all times. So I'm concerned about IF my power supply is for some reason not connected the Arduino will supply power on its own.
Is there a way to prevent 5V pin from outputting 5V, so it only accepts 5V
EDIT:
There are cases when the USB isn't connected so I need the 5V to be connected at all times, if its still vague then is there a way to only use data on USB and disregard the power?

If it's always connected to the PC why not just disconnect the 5V pin?

@Majenko the current drwa is around 4 amps and i forgot to mention that its only connected when pc is on

So you want it to operate when the PC is off?

@Majenko when its onn and off but when the pc is on the arduino will listen to the pc for commands

Sorry, you're not making any sense now.

A simple diode is all you need. The USB power already goes through a diode, so another diode the same will create a "highest voltage wins" situation.
That is, if the voltage provided by the USB port is higher than the voltage you provide on the +5V pin (after the diode's forward voltage drop) then the USB port will power the nano. If the voltage on the +5V pin is higher (after the diode's voltage drop) than the USB then the voltage on the +5V pin will power the nano.
No power will flow out of the 5V pin to your LED strip because the diode is in the way.
Connect the 5V external power to the anode of the diode, and the 5V pin of the Arduino to the cathode of the diode. The cathode is generally the end of the diode with the stripe.  Make sure the diode can pass enough current to power the Arduino when the USB is un-powered. The 1N4001 is a popular choice and very easy to get hold of.
That choice of diode also has a higher forward voltage drop than the on-board USB diode (0.7V as opposed to about 0.4V), so the USB will generally be chosen by default when connected and powered up, which is as it should be for a bus-powered device.


text:
Connect an Arduino directly to RGB LED strip
I am totally new in this area. I have an Arduino mega 2560 and I have this LED RGB Strips. I would like to know if there is any way of connecting the Strips directly to the arduino. The strip has already solded 4 cables:

one cable on 12V
one cable on G
one cable or R
one cable on B

I don't have additional equipment. Also, I can't find anything online which uses the same type of strips as mine. Many thanks.

https://learn.adafruit.com/rgb-led-strips/usage

+1 for the Adafruit tutorial, it will cover much more than is possible to explain in a SO answer. I've found this other source http://www.engineerathome.com/elektronica/how+to+build+an+rgb+led+strip+controller/33 to be useful for making my RGB controller.

if you want guidance shopping for a LED driver , just say so or ask for details, it's not hard https://www.amazon.com/Channels-DMX-512-Decoder-Converter-Light/dp/B0083RBGJG or 3 power FETs and https://www.amazon.com/Power-Adapter-Transformers-Supply-Output/dp/B00DKSI0S8/ref=pd_lpo_328_bs_t_2?ie=UTF8&psc=1&refRID=SF0CXGBQYRBBRAQT2FN1

Those LED strips are multiple parallel chains of 3 LEDs in series, with a 150Ω resistor for each chain.  The chains are arranged as common anode, and the chains are grouped into the three colours for the cathodes.
You require a power supply with enough current to supply all the LEDs (such as the 3A one supplied in the package).
Further, you require a method of switching each of the three channels, such as n-channel MOSFETs, which can handle enough current for each channel (one MOSFET per channel) - that is, 1A per channel if the whole strip takes 3A (but you can "derate" it by providing capacity for more current which helps alleviate some heat dissipation problems).
As long as the MOSFETs are logic level (such as the IRLxxx series) you can then switch them directly using the PWM outputs of the Arduino.

Daymn, IRLxxxx is always logic level? I keep buying the wrong stuff (since I'm more of a programmer than an ee). However, my rgb-driver is working, and it's using IRF3205’s

Yes, the L is for Logic level FET. The IRF's are often also usable, depending on specs. The IRF3205 has a threshold of 2.0-4.0V, so is just about OK for a 5V chip like the Arduino. Not for a 3.3V chip like on a Due or chipKIT board. It's not really fully on till around 7V_GS though, so you'll be suffering some losses from it.

https://www.amazon.com/Channels-DMX-512-Decoder-Converter-Light/dp/B0083RBGJG or 3 power FETs and https://www.amazon.com/Power-Adapter-Transformers-Supply-Output/dp/B00DKSI0S8/ref=pd_lpo_328_bs_t_2?ie=UTF8&psc=1&refRID=SF0CXGBQYRBBRAQT2FN1
You can use the logic level ports to drive Logic level power MoSFET switches or use a RS85 IC to communicate to a DMX-512 interface special effects driver to RGB.
Other options include
Use 5A PWM 3channel dimmer purchased on line with 12V- 14.5Vmax PSU >40W per 5m reel string .
e.g. Laptop universal 65W charger ($30) with 14V -16V setting. and long AWG18 wire with 1-2V drop
(comments)

You start by improving your question with details on what you want to do with the interface.
if you want guidance shopping for a LED driver , just say so or ask for details, it's not hard

The RS485 thing is smart, since that's how "the professional LED strip installations" work. But those strips/controllers may be more expensive.

"if you want guidance shopping for a LED driver , just say so or ask for details" please note that that isn't really the aim of stackexchange (http://meta.stackexchange.com/questions/158809/why-are-shopping-list-questions-bad). Given the fact that you can control them with logic level MOSFET's or DMX ledstrip controller, he should be able to figuren out what fits his needs/budget.

yes i posted link for <$30 ** 3 Channels DMX-512 Decoder Converter for RGB LED Lamp Light - Multi-functional Full-color LED Decoder Controller **

That's okay indeed (:

ok I'll do that next time.

No. Two reasons:

The Arduino can only supply about 40 mA per pin max. Your LEDs will require about 1000 mA or so per channel (based on the 3 A PSU supplied with the unit).
The LEDs are individually addressed and codes have to be transmitted to them. This requires code to be written for the micro and an interface to the data line.

Figure 1. The IR controller.
The IR controller supplied with the kit interfaces the power and provides the data signal to the strip.
The simplest way to control from your micro is to fit it with an IR (infra-red) LED and transmit the codes to the IR controller. This method also makes it almost impossible for you to damage your micro or the LED strip as the only connection between them will be by infra-red light.
Someone has probably figured this out already and you may find the complete code for an Arduino in a web search.

Are you arguing that these are individually addressed and also have a distinct supply for each color?  Not saying that is impossible, just that it seems odd.  Typically I'd expect individually addressed LEDs to use a common supply, and those with distinct supplies to be only controllable per color, by current modulating the three power supplies.

I'm not arguing! ;^) Of course, you're right. I should probably have said "Your LEDs will require about 1000 mA or so per R, G and B colour." The advert is typically vague about the LED specs.

I don't really think this is the simplest way ;p

@Paul actually re-using the existing drive box is simpler than engineering your own.

@Chris ah! I didn't check the link, but yeah, if that drivebox is included, it may be worth it. But i was thinking of "reverse engineering" the IR protocol and making your Arduino send it out. Adding a few mosfets to the RGB lines, and controlling them with analogWrite should be easier (in terms of coding). It just seemed like a work-around rather than a fix. (Though, with the IR receiver supplied, it makes sense)

But yeah, if you can find example code that works with this, then it's only a matter of connecting the IR transmitter.

No. there is no way to connect those directly.
You can use Solid state relays (SSR) for this.
I did it before and was able to make different colors.
Connect an external 12v directly 12V pin in srips.
Use SSR to connect from GPIO to LED R G and B pins

They already include a driver, so that's not really true - you can inject remote signals into the driver, or directly drive its FETs.

You can use a couple of relays on the arduino outputs, and control it from there.

Using MOSFET's, you can actually dim the R/G/B channels. (Mechanical) relays will wear out and are often too slow.

Please improve your answer giving specifics of how to solve the question asked.

+1 There's no dimming requirement in the question, so this is a reasonable answer for on/off control.  There really aren't specifics to give, beyond the connection details of whatever relay board is chosen.


text:
Code Optimisation
I have tried fading the RGB Led with different colour format and sequence.
Working of Code :-

When value of number is 1, the Red LED fades gradually and glow up with the delay interval of 10ms with fade amount 5.
When value of number is 2, the Green LED works as above.
The change of state from Red to green takes 4 seconds.

Blue Led Code can also be added to this and various other colour combinations can be made, which will complex the code and add up difficulty is debugging and finding errors because every combination should have different name for fading so that it doesn't conflict with other combinations.
Here is my code. However, I need some suggestions regarding quality of my code. Is it the efficient way to do code. How can I improve the code. Any constructive suggestions would be of great help.
int RED_LED = 12;           // the PWM pin the LED is attached to
int BLUE_LED = 14;
int GREEN_LED = 15;

int RedLedBrightness = 0;    // how bright the LED is
int GreenLedBrightness = 0;    // how bright the LED is

int RedFadeAmount = 5;
int GreenFadeAmount = 5;

unsigned long previousMillis = 0;
const long interval = 10;

unsigned long previousMillis2 = 0;
const long interval2 = 4000;

int j = 0;

void setup()
{
  pinMode(RED_LED, OUTPUT);
  pinMode(BLUE_LED, OUTPUT);
  pinMode(GREEN_LED, OUTPUT);

  Serial.begin(115200)
}

void loop()
{
    if (millis() - previousMillis2 >= interval2)
    {
     previousMillis2 = millis();

    j += 1;
    if (j > 2)
    {
        j = 1;
    }
    Serial.print("\n");
    Serial.println(j);
   }
    SpecialFunction(j);
}

void SpecialFunction(int Number)
{
  if (millis() - previousMillis >= interval)
  {
    previousMillis = millis();

    if (Number == 1)
    {
      RedGradualChange();
    }

    else if (Number == 2)
    {
      GreenGradualChange();
    }
  }
}

void RedGradualChange(void)
{
  analogWrite(GREEN_LED, 0);

  GreenLedBrightness = 0;    // how bright the LED
  GreenFadeAmount = 5;

  analogWrite(RED_LED, RedLedBrightness);
  RedLedBrightness = RedLedBrightness + RedFadeAmount;

  if (RedLedBrightness <= 0 || RedLedBrightness >= 1020)
  {
    RedFadeAmount = -RedFadeAmount;
  }
}

void GreenGradualChange(void)
{
  analogWrite(RED_LED, 0);

  RedLedBrightness = 0;
  RedFadeAmount = 5;

  analogWrite(GREEN_LED, GreenLedBrightness);
  GreenLedBrightness = GreenLedBrightness + GreenFadeAmount;

  if (GreenLedBrightness <= 0 || GreenLedBrightness >= 1020)
  {
    GreenFadeAmount = -GreenFadeAmount;
  }
}

Perhaps if you were to write out, in plain English, what you want your program to achieve it may help.

@Majenko Please review my question again and my code as well,

I have updated my answer.

How can I improve the code - this is not a reasonable question for this site. It is too broad. With all due respect to Majenko who is trying to help you, this is a very broad question. Plus, you keep editing the code so that answers don't make any sense. Please read How do I ask a good question?.

Without deciphering what all those functions are supposed to do, I can see a few fundamental flaws and inefficiencies:

Don't use string - especially if you're only then using it to convert into a char array. Just use the char array.
You're storing a number in a char array then comparing it to string constants. What is wrong with dealing with just numbers in the first place...?
This bit is wrong: if (incomingByte = '#') - you have an assignment (=) instead of a comparison (==) so it will always be true.
If you fix point 3 the rest of the code won't work, since your string will now always have # at the end (3# for instance) and the comparison against 3 (for example) will fail.

You should learn more about how to input values through serial:

https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

For your fading code there is a lot of redundancy in there. Personally I would use a bitfield indicating which LEDs are to fade and which aren't.
Basically you have a single value and OR together bits within it to indicate the enabled LEDs.  For instance, assign the value 1 to red, 2 to green and 4 to blue. These correspond to 0b001, 0b010 and 0b100 respectively.
When the state is changed, either by your loop or by an external serial signal, you reset all three colour brightnesses to 0 (to keep them synchronised) and set the right bits in the bitfield for the colours you want fading. For instance, for red you set the bitfield to 1. For cyan you set it to 6 (0b110).  Then in your processing loop you just fade the colours that are enabled, and write all three values (the colour that isn't enabled will already be 0).  This also has a side-effect that you now already have numbers assigned to the colours:
0 = 0b000 = All off
1 = 0b001 = Red
2 = 0b010 = Green
3 = 0b011 = Yellow
4 = 0b100 = Blue
5 = 0b101 = Magenta
6 = 0b110 = Cyan
7 = 0b111 = White

In fact, since all the colours are fading together, you don't even need separate values for each colour - just one global brightness value.
Some code (untested) for you:
#define RED   0b001
#define GREEN 0b010
#define BLUE  0b100

int brightness = 0;
uint8_t enabled = 1;
int fadeAmount = 5;

const uint8_t RED_LED = 12;
const uint8_t BLUE_LED = 14;
const uint8_t GREEN_LED = 15;

unsigned long previousMillis = 0;
const long interval = 10;

unsigned long previousMillis2 = 0;
const long interval2 = 4000;

void setup() {
  pinMode(RED_LED, OUTPUT);
  pinMode(BLUE_LED, OUTPUT);
  pinMode(GREEN_LED, OUTPUT);

  Serial.begin(115200);
}

void loop()
{
    if (millis() - previousMillis2 >= interval2) {
        previousMillis2 = millis();
        enabled ++;
        if (enabled >= 8) enabled = 1;
        Serial.println(enabled);
    }

    if (millis() - previousMillis >= interval) {
        previousMillis = millis();
        if (enabled & RED) {
            analogWrite(RED_LED, brightness);
        } else {
            analogWrite(RED_LED, 0);
        }
        if (enabled & GREEN) {
            analogWrite(GREEN_LED, brightness);
        } else {
            analogWrite(GREEN_LED, 0);
        }
        if (enabled & BLUE) {
            analogWrite(BLUE_LED, brightness);
        } else {
            analogWrite(BLUE_LED, 0);
        }
        brightness += fadeAmount;
        if (brightness > 1023) {
            brightness = 1023;
            fadeAmount = -fadeAmount;
        } else if (brightness < 0) {
            brightness = 0;
            fadeAmount = -fadeAmount;
        }
    }
}

I removed the serial part and I just want you to focus on rest of the code, which is necessary. I now used a loop to fill values into j after every 4 seconds.


text:
ESP8266 12e Arduino IDE outputs garbage values on serial monitor
I recently started using the ESP8266 12E (Amazon link) and hooked the board up to the Arduino IDE.
When trying to run any of the example sketches, all sketches compile and upload correctly. The blink sketch correctly causes the LED to blink, however, in the serial monitor a varying and large quantity of junk characters appear:

The first thing I investigated was of course the baud rate. Online, documentation for the ESP8266 indicate 115200 as the correct baud rate, but on the bottom of the device, the baud rate is listed as 9600.
The junk characters, of course, appear whether the baud rate is 9600 or 115200. Using trial-and-error, I tried each other option. I've also tried several USB to micro-USB (c) cables. They're the same ones I use to charge my phone - is that the issue?
Am I missing something simple here? I searched each of the other Stack Exchange questions about garbage serial monitor values and they all seemed to indicate that the baud rate was the culprit, or that the CL / NR values needed to be changed. Experimentation with these did not result in removing the characters.

The baud rate you specify in your program and the baud rate in the serial monitor must match. The ESP8266 outputs a boot message at its own baud rate (varies from model to model - try 57600) before it executes your sketch.
For example:

You can choose any (within reason) baud rate in your program as long as you also choose the same baud rate in whatever is communicating with it (such as the serial monitor in the IDE). If you want to see the boot messages then the serial monitor will have to be set to the right baud rate.

Thank you for your response -- I am unsure how to view this boot message. I am currently using Windows 10, and don't have (readily accessible) a working Linux installation. I can access one in a few hours, however.
The baud rates appear to match - in the Arduino IDE Tools > Baud Rate menu + the serial monitor menu & the code itself, they all read 115200.
I changed them do 57600 and did not notice a change yet

... "If you want to see the boot messages then the serial monitor will have to be set to the right baud rate." ... What isn't clear about that? Where does your host OS come into it?

I hit the enter key pre-maturely -- see the edit to the comment above

I am doing that all the time ;) The baud rate in the tools menu is purely for performing the upload of the code. The baud rate in your code is purely for your own communication from within your code. The only baud rate that has any bearing at all on the boot messages is the one in the serial monitor's drop-down list. Try different values in there. Or just ignore the boot messages as they aren't that interesting.

Experimenting more with the Baud Rates -- I learned that 74880 produces an accurate boot message (see link below):
link
I still get a funky "y" character (y with umlaut)  ÿ
Is the EOL / CR / NL values for my serial monitor incorrect?
Phew, this has been quite an educational process. I very much appreciate your help, Majenko!

The ÿ is usually associated with the line being dropped or otherwise going dead, usually at the end of transmission, or just as transmission starts. It's basically corruption and is pretty much normal.

I had what I think is the same problem you did.  I posted my solution to it here:
Link to my solution
It seems that the ESP can upload code at 115200, but it can't talk to the serial monitor at that baud rate.  The solution is to programatically change the baud rate within your sketch.  The change in baud rate doesn't 'stick'.  You have to include it in your sketch so it is set every time the sketch is run.
Hope that helps.


text:
Getting the highest value from analog reading?
I am doing a project using an FSR (Force Sensitive Resistor), I'm currently reading values with no problem every 100milis. I want to output via Serial.print the highest value, I've read.
I am having a hard time doing so. The project is use to "measure" the strength some projectiles hit the sensor. I want to get the highest value.
This is the code I have until now.
int fsrPin = 0;     // the FSR and 10K pulldown are connected to a0
int fsrReading;     // the analog reading from the FSR resistor divider
void setup(void) {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);
}

void loop(void) {
  fsrReading = analogRead(fsrPin);

  Serial.print("Analog reading = ");
  Serial.println(fsrReading);     // the raw analog reading

  delay(100);
}

You need to learn about if and > (Greater-Than).

Majenko, thanks... I dont know how to use it when using the delay, since.... I want to have a fast rate reading, and once I output it, reset it so the next measure will compare again, as to output multiple impacts.

Ah, so you want the maximum value within the 100ms time frame then?

Majenk, 10ms, can be changed just used it for testing. (For this problem, I know I have to compare "last value" against "current value" and save the greater, but I am having trouble with, how fast should I "sample", and how to reset the "last value" variable, in order to be ready for the next impact.

You reset the "last value" by setting it to 0. As to when that happens, that is entirely up to you and is only something you can decide. How fast to sample? Well, I'd say as fast as you possibly can. There is no use for delay() in your code at all.

mmm I think it does... since lets say for the sake of an example: on time (lets call it t) t=0 measure=0, t=1 measure=10, t=2 measure=12, t=3 measure=30, t=4 measure=25, so on.... so, I want to output, this impact was 30, now I need to reset? so I start doing the same for the next impacts?

No, what you want is "Until t == 4 keep reading the analog and comparing it.". Once T has exceeded 4 (or whatever time you decide on) you print the maximum and reset. I will knock up a brief code to demonstrate:

You don't want to delay ever. Instead you want to change your thinking to "X miliseconds have passed, time to print and reset":
int maxval = 0;
uint32_t lastSample = 0;

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

void loop() {
    if (millis() - lastSample > 100) { // Every 100ms:
        lastSample = millis();
        Serial.println(maxVal);
        maxVal = 0;
    }
    int reading = analogRead(0);
    if (reading > maxVal) {
        maxVal = reading;
    }
}

Every 100ms it will print the maximum analog value read during the past 100ms.
You can replace the 100ms with any other value you choose, or even with a check to see if a button has been pressed, in which case you get the maximum reading since the last time the button was pressed:
// global
bool lastButtonValue = HIGH;

// in loop()
if (digitalRead(3) != lastButtonValue) {
    lastButtonValue = digitalRead(3);
    if (lastButtonValue == LOW) {
        // ... do the print and reset
    }
}

how short an event (<1ms) and rate of sampling determine chance of missing an impulse force peak.  software peak detection by a loop is a poor way for projectile peak force or g readings.

@TonyStewart What choice do you have though on an Arduino? All you can do is sample as fast as you can - theoretically at a frequency at least twice the reciprocal of the duration of an impact. Using free-running mode and an interrupt to read the values would give access to faster sampling rates, but that is beyond the ability of the OP I feel.

@Majenko Thank, man, you approach was what I was looking for, you are right the approach should be delay-less, and should be "X time has passed need to print and reset" I am getting good data now.... THANKS!

You add a small transistor emitter  follower and output to a small plastic cap to peak fast and hold as long as the interval between sampless. driving the input low after a slow decaying reading, resets the cap voltage to zero, momentarily, from a bidirectional port, then waiting for the next projectile.  This can be improved greatly but far better than trying to sample a detector.

@TonyStewart Maybe on the electronics.SE site that would be a good idea, but this is the Arduino site. Here it's done (for better or worse) using an Arduino.

ok but the design is flawed, I am pointing out why and how to fix that

@TonyStewart Whatever. Better would be to use a proper op-amp based peak detector circuit or you'll be losing voltage from your sample cap, no matter how huge you make it.

it is a matter of how large the impact voltage is created and yes I know it can be greatly improved as stated. (if any interest in making it work at all.) for example a PNP followed by an NPN has no offset with a storage cap in between for peak and hold or a Comparator and cap to charge if Vin>Vstored then a switch to dump after reading or....


text:
From Wiring to pure C
I'm using the Teensy 2.0 (atmega32u4) and decided to switch from Arduino IDE with Wiring to pure C. I think it's much more useful to master programming microcontrollers on that level. Wiring seems to be quite limited at some point.
It was really easy to use some basic libraries such as avr/io, or util/delay and write simple programs like "arduino hello world".
My problem comes with more complex tasks such as acting as usb mouse. On http://pjrc.com are references just to use with arduino ide/wiring. I couldn't find anything useful on google. Is there any good reference for pure C programming tennsy/arduino and/or using libraries such as "usb_mouse.h" (from pjrc.com) with pure C?

EDIT 1
Let me add some details (based of @st2000 answer).. Yes, Tennsy (and Arduino) are microcontrollers, not microprocessors. Programming avr chips in pure C doesn't require so much work as programming microprocessors. This is the simplest avr C program I could come with (typical blinky):
#include <avr/io.h>
#include <util/delay.h>

int main(void) {
        (CLKPR = 0x80, CLKPR = 0x00);
        DDRD |= (1<<6);
        PORTD &= ~(1<<6);

        int sviti = 0;

        while (1) {
                if (sviti)
                        PORTD |= (1<<6);
                else
                        PORTD &= ~(1<<6);
                sviti ^= 1;
                _delay_ms(40000);
        }
}

As you can see (@st2000), there are no dozens of setting up registers. It does not require any expensive equipment to upload resultant .HEX file - for teensy the only thing you need is a USB cable.
If you want a concrete example, I want to use this library with pure C, but it's obviously meant for wiring and arduino IDE primary. So how to use this library with pure C? And back to my main question, how to generally use libraries of this kind with pure C avr programming?

Datasheets? Atmel application notes? Anyway, USB programming is not an easy task - which is why people use libraries.

You can use pure C with libraries. Just search "atmega32u4 HID Mouse" that should pop up some githubs/forums/resources/blogs.

Please try make your question more specific. Are you actually after a library so that your Teensy behaves like a mouse? What do you plan to do with it? That will help the community determine what answers to give. http://arduino.stackexchange.com/tour

If you want to do USB on an AVR with USB hardware capability outside of the Arduino realm, you might look at LUFA.

The library you are referring to is meant to work in plain C. It does not depend on any Arduino libraries, nor does it require C++. Look at the provided example to see how to use it. To compile the example, just type make at the command line. With one caveat: all PROGMEM arrays should be made const in order to be compatible with recent releases of gcc. You can of course tune the Makefile to your taste.

Oh my god.. You're right, I am sorry. Sometimes I can't believe how dumb I am...

If even Majenko scoffs at the notion of doing it in C....

Refer to the actual processors used on the platforms to find reference material for ordinary C or C++ programming.  There are different processors used on various Arduino boards.  Be aware that this approach normally requires programming hardware which range from a few dollars to hundreds of dollars.  Also be aware that "bare metal programming" requires the programmer to setup the processor's resources of interest.  This normally involves setting dozens (as in the Arduino Uno AVR processors) if not thousands (as in Arduino Zero's ARM processors) of registers which can deal with everything from the processor's clock to interrupt vectors.
USB programming is very complex.  Consider the complete description of RS232 could be contained in a white paper.  The equivalent for USB would be at least a book.  To simplify your efforts, we can eliminate all USB Host features as a mouse is a peripheral or USB Device.  Further, you will probably want to limit your USB Device to a USB HID or Human Interface Device.  This allows most OSs to easily recognize and use the mouse as the HID definition is more complete / restrictive. Also note, embedded processors which happen to have a USB port usually only support USB Devices as USB Host requires additional features & resources.  Now that the scope of USB support has been narrowed, you can start searching through the different processor's libraries for what you need to create a USB HID Mouse.

You seem to be confusing microcontrollers and processors (literally in your text). But also, "bare metal programming" really doesn't take that much registers on Arduino/AVR, you'll only have to set up what you need, and you can use libraries or the datasheet.

I will gladly change "processor" to "micro-controllers" in the answer if you explain why.  Now that I think about it, I believe "embedded processor" is the more commonly used term.  As for initializing the embedded processor's registers, I agree, if you do not rely on the feature you do not need to initialize the register. Regardless, the point of the answer was to make the OP realize that he / she was giving up a key feature of the Arduino platform.  The abstraction from the embedded processor's own hardware.

Getting a "bare metal" program into this sort of chip requires no tools different from those used to get an Arduino sketch in.  The same compiler can be used (even literally as installed by the Arduino IDE), and the chip can't tell the difference.

I had assumed the OP wanted to remove the Arduino boot program and do all his / her own C programming.  In such a case, at minimum, you would need a 2nd Arduino to act like a programmer.  Or, perhaps, pick up this or that AVR programmer.

And back to my main question, how to generally use libraries of this kind with pure C avr programming?

just as how you would write under arduino ide -> arduino ide is nothing but pure c/c++ plus a set of canned libraries. so what you are trying to do is no different from what you are doing with arduino right now, maybe with your own libraries or libraries from folks other than the arduino folks.
nothing magic about going in "pure c".


text:
Arduino or XBee unique identifier?
Is there anything built into the Arduino Uno or the XBee Pro 2 radio module that I can poll within my Arduino script to act as a unique identifier? Mac address or otherwise? If anyone has a code snippet that can do this it'd be extremely appreciated.
Currently my Arduino nodes are broadcasting only to my node.js server, but my server is broadcasting to all the nodes, so if they're all waiting to be assigned an identifier number through the handshake function I wrote, they all receive the same one. If I stagger powering them up this is avoided and they each get a unique ID, but I hope there exists a cleaner solution.

I guess I can make a random number work.

When programming the Uno's, you could write identifying values into particular EEPROM bytes.  To automate the process, write a development-system program to produce serial-numbered HEX files, with the serial number counting up each time the program runs.
For example, if you store IDs into byte 0x1E of EEPROM, the serial number file would look as follows when the serial number is 0x23:
:01001E0023BE
:00000001FF

The first line in the above file says 01 bytes of payload, stored at address 001E, record type 00 (data), payload byte 23, checksum BE.   See wikipedia's Intel HEX article for further explanation of HEX file format.  In brief, each time the serial number byte goes up by one, the checksum byte goes down by one.
To program a serial number byte into EEPROM from a file called SNfile.hex, issue a command like the following.
avrdude -p atmega328p -c arduino -P /dev/ttyUSB1 -b57600 -U eeprom:w:SNfile.hex:i

See the avrdude manpage for explanation.
In your sketch, use EEPROM.read(address) to read a unit's serial number.  For example:
#include <EEPROM.h>
byte mySN = EEPROM.read(0x1E);

[Note, regarding your question about  “anything built in... to act as a unique identifier”, I once spent quite a while looking for such a thing on Uno, Nano, and Mega2560 Arduinos, and found nothing.  I haven't looked at XBee radio modules for such data.]


text:
Generating analog signals
is there a way to make the Arduino act as a voltage source, by generating sinusoidal, triangular and other kinds of signals? If so, can it be done using LabVIEW? (I've already managed reading analog signals using VISA)
Thank you!

The Due (and similar SAM based boards) have a DAC built in which can be set to different voltages (I forget the range off hand, maybe 0-Vcc at 12-bit resolution). Change that voltage fast enough, and you have a waveform.
Other Arduinos have PWM outputs which, when filtered through a low-pass filter, give a voltage proportional to the duty cycle of the PWM. Again, change the duty cycle fast enough and you have a waveform (limited by the carrier frequency of the PWM).
Can you do it from LabVIEW? Who knows? I have never used it.


text:
OnKeyPress in a arduino
So, I have 3 buttons to a arduino.
I want to detect the button press on the 3 of them.
For that, i've created a function:
int OnKeyPress (int port) {

  int  LastState, BeginState, r;
  r = 0;

  BeginState = digitalRead(port);

  if (BeginState != LastState) {
      if (BeginState == 1) r = 1 ;
  }

  delay(5);
  LastState = BeginState;
  return r;
}

I want to instantiate 3 instances of this code, separately and they have to retain this variables int  LastState, BeginState, r; for each button, and the next time the function runs on the loop, the variables are the same of when they ran last time.
Just, how?

What you are looking for is called a class.  https://www.tutorialspoint.com/cplusplus/cpp_classes_objects.htm

Another relevant tutorial from the Arduino website: https://www.arduino.cc/en/Hacking/LibraryTutorial

This is an ordinary method (function) which can not be instantiated. It is necessary to write a class with 1 or more methods in it in order to instantiate multiple copies of that class and the method(s) with in that class.
The integers "LastState", "BeginState" and "r" only have scope within the method and will not survive after returning from the method.  There are several approaches to preserve these variables from one call to the next.  They can be declared as static integers.  Or they can be defined globally.
It appears you are recreating the existing Bounce library.  I encourage you to continue if you are learning.  However, you may want to look at the Bounce library's code for guidance.


text:
Reading Serial Data Using readBytes() and Use of Serial.read()
I'm trying to mix Serial.read() and Serial.readBytes() when reading over one of the Serial ports on my Arduino Due.
I thought that using Serial.read() would clear what is on the serial, and then subsequent reads by readBytes() would not pick up what has already been read by the Serial.
The main reason I'm trying this approach is because large Serial reads can be unstable using the Arduino supplied Serial.read() - I've checked the Serial buffer with a logic analyzer, so I know that the data is on the Serial line, but Serial.read() drops some bytes.
Hence why I want to use Serial.readBytes().
Here's what I'm doing:

#define FIXED_LENGTH 10
char * buffer, * bp;
int index, i, bufSize;
while(1)
  {
  if(Serial3.available())
  {
    data = Serial3.read();
    Serial.print(data,HEX); //Check the data received
    buffer[index]=data;
    index++;

    if(index == FIXED_LENGTH){
       //...code to calculate bufSize from buffer...//
       bp = (char*)calloc(1,bufSize); //calloc bp size
       Serial3.readBytes(bp,bufSize); //read the rest of what's on the serial
       break;
    }
  }
  }

I get the correct output from the first part of the code - that is, it correctly calculates bufSize from buffer. But when I try to store the following length into bp, it gives me more or less the first output that I have already read on the first few passes!
Example:
Data coming in over Serial3.read() [10]: 0123456789
The next characters in Serial3 are [6]: ABCDEF
Stored into bp using Serial3.readBytes() [6]: 000045
Do I need to flush Serial3 before attempting to read the next set of bytes off of it? Do I need to wait/set a timeout before advancing to the next operation?

You did not initialize buffer: you are going to corrupt your memory.

Sorry but your code is full of bugs, its going to blow up in you face.  index needs initialising, you don't check to see if the calloc fails, you don't free the calloc.  I would approach it a different way, use readByte into a static buffer of fixed size, process the data, read again.

You're right, this code would be full of bugs, but it's just a snippet as part of a larger portion of code. Please assume that I am properly initializing buffer and setting up the rest of the variables correctly. My question is dealing with readBytes and reading from the Serial line.

You should probably check out create a minimal working example to enable people to help you.