text:
Is there an easy way to turn integer values to pixels?
I'm working with a black & white camera and it gives me integer values to represent the amount of light hitting the sensor. Very bright is 1023 and totally dark is 0. The values are printed through serial and everything works fine but now I want to recreate the image based on the values.
Does anyone know if there is a simple way of doing this? I'm assuming the process would consist of looking up the value and giving a specific colored pixel in return, but I have no idea how to do this.

Simplest thing may be to write down your image in plain Portable Gray
Map format. This is a very
simple (and inefficient) ASCII format consisting of a signature (the
string "P2"), followed by the width and height of the image, followed by
the maximum possible gray level (1023 in your case), followed by the
pixel values. It's a free form format, meaning you can mix spaces and
newlines at your convenience.
Here is an example image: two rows of pixels, five columns, and
brightness increasing left to right and top to bottom:
P2
5 2
1023
  0 111 222 333 444
555 666 777 888 999

Then, any image conversion software should be able to convert that into
the format of your choice (PNG, JPEG, whatever...).

That kind of what I'm looking for, I just want to actually see the image and don't care much about efficiency. However, I did not get from the documentation how you would go about making of the these PGMs. Is it a file I make based on the numbers? Like do I take the values and past them into this PGM file?

@CrystalPritzker: It's just a text file. How would you write a text file on your computer?

@CrystalPritzker, your sketch could write PGM-formatted data, which you pipe to a .pgm file on the host, or you could write a program that receives data organized however you like and writes it to a .pgm file.  See eg tutorialspoint....c_file_io or cprogramming...cfileio re opening a file and writing to it.  With a .pgm file, use a pgm-to-jpg (or whatever) program.  (Search google for "pgm to jpg" and find eg pgm-to-jpg converters

@EdgarBonet So are you saying that it's really as simple as writing the number in a text file and then ending it with .pgm? Then convert that file to an image?

@CrystalPritzker: In essence yes, except that 1) you have to write "P2" before the numbers, c.f. my example 2) You don't “convert that file to an image”: it's already an image, you just convert it to a more common image format.


text:
How can you speed up the ADC on an ATtiny85?
I'm reading input from a camera and trying to reach a fast frame rate. Problem is my ATtiny85 has a pretty slow conversion time (65 - 260 µs Conversion Time). Is there any way to make this faster? I heard that you can set-up a prescaler for the analogRead() method by doing the following:
#define FASTADC 1

// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

void setup()
{
  #if FASTADC
   // set prescale to 16
   sbi(ADCSRA,ADPS2) ;
   cbi(ADCSRA,ADPS1) ;
   cbi(ADCSRA,ADPS0) ;
  #endif

  /*Rest of the code goes here.*/
}

I can't really make sense of the code and I found it on a less then reliable website so I was wondering if any of the gurus on here could let me know if what I'm attempting is possible and if this is the proper way of achieving my goal.
Also, would this also work for the Arduino Mega? I'm currently using it to test and debug my project since the ATtiny84 doesn't have serial output.
Datasheet: http://www.atmel.com/Images/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf

How many bits of precision do you need? You can speed up the conversion at the cost of loosing precision in the lower bits down to 1us/conversion.

Can you explain what bits of precision is? This is my first Arduino Project and first time working with a camera so I'm a little confused on the lingo.

The ATTINY ADC normally gives 10 bits of precision- so you get a value between 0 and 2^10 (1024) and each number is different, so (say) 787 (1100010011) is always bigger than 786 (1100010010) even though 787 and 786 only differ by the lowest bit. You can make the ADC go faster, but the bottom bits start to not matter so you can only care about the topmost bits - so in our case if you only had 9 bits of precision then 786 and 787 would be the same (both would be (110001001x where the x means don't know or care). Make sense?

Makes a lot of sense. So when you set a prescaler you are reducing the number of bits used we can get the ADC to be faster but we will have less accuracy.

The prescaler just divides the clock that goes into the ADC. So if you start with a 1MHz clock and a prescaler of /2, then the lock that goes into the ADC will be 500Khz. The ADC clock (after the prescaller) needs to be 50-200Khz to get all 10 bits of precision, but you can run it up to 1mhz but more of the bottom bits will start being wrong the faster you go.  How much precision do you need and how fast you do need samples?

I'd be fine with 4 bits of precision eventually and for me the faster the better. I'm also trying to understand what the code above is doing. Since it's setting a prescaler of 16 does that mean that it's actually making my program slower?

If you only need 4 bits, then I'd ditch the ADC and just use 2 op amps - or even just a resistor ladder connected to input pins so that you get the voltage window you want. Very very simple (at most 4 resistors) and very fast (as fast as the ATTINY can read the input PINs).

Sorry again I'm kind of lost with the lingo. What are 2 op amps? And how can I just ditch the ADC if the signal coming in from the clock are in analog?

What is the camera?

@bigjosh The TSL1401R-LF linescan module. It reads in a 1 X 128 array of pixels.

Besides lowering the ADC clock prescaler, you can also do the conversions asynchronously. Arduino's analogRead for example, starts a AD conversion, waits till it's finished, and then returns the value. However during this waiting you could be doing something useful. So you could e.g. do something like; start conversion, do some calculations on the previous conversion value, wait till conversion is done, and start all over again.

The ADCs in the ATtiny85 and ATmega2560 (the chip powering the Arduino
Mega 2560) are pretty similar, except for the Mega having more inputs.
In particular, the way you set the clock prescaler is the same, namely
the bits ADPS2:0 in the register ADCSRA. You could use the same code to
set the prescaler on both chips, but you probably don't want to unless
your ATtiny is clocked at 16 MHz, like your Mega. I would normally
just set the control register to the value I want, rather than
touching only a few bits, but that is a matter of personal preference.
So, to set the ADC clock of the Mega to 1 MHz, I would
ADCSRA = _BV(ADEN)    // enable the ADC
       | _BV(ADPS2);  // clock at F_CPU / 16 = 1 MHz

The same code would do the same thing on an ATtiny clocked at
16 MHz. If the ATtiny runs at 8 MHz, I would instead
ADCSRA = _BV(ADEN)    // enable the ADC
       | _BV(ADPS1)   // clock at
       | _BV(ADPS0);  //     F_CPU / 8 = 1 MHz

If you want to be generic:
#if F_CPU >= 12000000
# define ADPS_SETTING _BV(ADPS2)                 // F_CPU / 16
#else
# define ADPS_SETTING (_BV(ADPS1) | _BV(ADPS0))  // F_CPU / 8
#endif

ADCSRA = _BV(ADEN)      // enable the ADC
       | ADPS_SETTING;  // clock somewhere near 1 MHz

As bigjosh explained in comments, the prescaler setting is a trade-off
between speed and accuracy. I recommend you read the article on the
Arduino ADC by Nick Gammon. He did some tests at various speeds
which showed that you can get decent results with clock speeds up to
1 MHz, then it becomes pretty bad at 2 MHz and mostly
useless beyond. You may want to run the same tests with your particular
setup.
Except for the very first conversion, which takes longer, an ADC
conversion takes 13 cycles of the ADC clock. If you run that clock
at 1 MHz, that is 13 µs per reading. If you get the readings
with analogRead(), you won't get one reading every 13 µs, because
the CPU needs extra time to execute the code you have between successive
calls of analogRead(). You can save time by having the CPU and the ADC
work in parallel, maybe along these lines:
ADCSRA |= ADSC;     // start the first conversion
for (int i = 0; i < NB_READINGS; i++) {
    loop_until_bit_is_clear(ADCSRA, ADSC);  // wait for the ADC
    uint16_t reading = ADC;     // get the reading
    ADCSRA |= ADSC;             // start the next conversion
    process(reading);           // process the reading we have
}

This way you process one reading while the ADC is taking the next one.
Or you can set the ADC to “free running mode” (where it takes one
reading after another without ever stopping) and get the readings in an
interrupt service routine. Whichever method works best depends on your
particular application: the amount of works your CPU has to do while
reading the ADC and whether you can afford to do the whole series of
readings with interrupts disabled.

If that's how you make the ADC faster then what does the code I posted do?

It sets the prescaler to 16, just like my first code snippet.

Okay, then I might be understanding the concept behind a prescaler. I thought prescalers made things slower because they divided the speed at which things happen. Meaning if my ADC is operating at a 1MHz speed and I set a prescaler of 2 then it would run at half the speed.

@CrystalPritzker: No. The prescaler sits between the CPU clock and the ADC clock. C.f. section 17.5 of the datasheet. If your CPU runs at 16 MHz (which is the case on the Mega), setting the prescaler to 2 would clock your ADC at 8 MHz, way too fast. The Arduino core sets it to 128, which clocks the ADC at 125 kHz, which is fine but too slow for your needs. I suggest you clock your ADC at 1 MHz, which means setting the prescaler to 16 on the Mega (I do not know F_CPU on your Tiny).

I see, but what happens if I just don't set a prescaler? Is their a default speed at which the ADC runs?

@CrystalPritzker: The hardware defaults to prescaler = 2 (see the datasheet). If you use an Arduino core, it will be set to 128 (c.f. my previous comment).

source: Stack Exchange

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

sort: votes


text:
What is using up all the RAM in my program?
I am running a program on the ATtiny and for some reason I am way over the 512 bytes of RAM that are available to me. This is confusing because when I did the math by hand I should have 432 bytes. Here is my code:
#include <SoftwareSerial.h>

#define FASTADC 1

// defines for setting and clearing register bits
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

SoftwareSerial mySerial(0,1);    //This uses 47 bytes of RAM

byte i = 0;      This uses 1 byte of RAM

byte pixelsArray1[128];   //Arrays use 128 bytes of RAM each
byte pixelsArray2[128];
byte pixelsArray3[128];

void setup()
{
#if FASTADC
// set prescale to 16
sbi(ADCSRA,ADPS2);
cbi(ADCSRA,ADPS1);
cbi(ADCSRA,ADPS0);
#endif

pinMode(1,OUTPUT);        //Setting the 1 pin to be used for output
pinMode(0,OUTPUT);        //Setting the 0 pin to be used for output
pinMode(A3,INPUT);         //Input for Camera 3
pinMode(A2,INPUT);         //Input for Camera 2
pinMode(A1,INPUT);         //Input for Camera 1

mySerial.begin(9600);     //Setting the data transfer rate
}

It's telling me that I am using 510 Bytes of memory but my math gave me 432 bytes of RAM. Does anyone see what I'm missing?

You should ask avr-objdump.

Out of interest how did you come up with your 432?

3*128 Arrays + 47 SoftwareSerial + 1 byte variable = 432

Which ATtiny are you using? Are you using SoftwareSerial for sending, receiving or both?

I'm using the ATtiny85 which has 512 bytes of RAM. Also I'm using the ATtiny to program a camera so I'm assuming that SoftwareSerial is used for both. Sorry, but this is my first Arduino Project ever.

What are you going to store in those pixel arrays? Since they already use 384 of the 512 bytes, it's the best candidate to save memory. If e.g. you pixels are only the values 0-16, you could compress to pixels into a single byte.

The pixels are the most important part of this entire program. The program is basically working a camera and storing the output.

There is a lot you are missing.  Such as:

SoftwareSerial is using RAM.
The system stack is using RAM.
The Arduino core software is using RAM.

There's plenty more going on than just your sketch. For instance, where do you think it stores the current millis() and micros() counts? Where do you think incoming serial data gets buffered? Where do you think your registers, PC, etc, get stashed when a function (such as setup()) is called? All that takes RAM.

She already counted SoftwareSerial, and the stack is not in the 510 bytes reported by the compiler. So this leaves only the Arduino core.

So is there any way I can reduce the amount of memory being used without scrapping my Arrays? For example, is there a way to NOT store the current millis() and micros() or is there an alternative to SoftwareSerial?

You should use avr-objdump to examine all the section sizes and determine what can be removed - then remove it. That means manual editing of core code.

How can I edit the avr-objdump? It's a .exe file and how do I know what I can remove. Again, I'm sorry but this is my first ever Arduino project.

You don't edit avr-objdump - you use it to examine your .elf file. That will allow you, if used right, to list all the variables in your .elf file. You can then look to see what there is. You can then match those up to variables in the core software and determine if you need the functionality associated with those variables - and if not then delete it wholesale.

@CrystalPritzker: Did you miss the link in my first comment?

@EdgarBonet No I found the avr-objdump file but couldn't execute the command he gave. It's probably because I'm using Windows.

@Majenko Does avr-objdump work on Windows? If so can you please tell me how?

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


text:
Why does this not put my Arduino Mega to sleep?
I have the following program which is supposed to print the words "Program is on" once and then go to sleep. However it doesn't go to sleep and continues to print "Program is on" over and over again.
#include <avr/sleep.h>

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

void loop()
{
  Serial.println("Program is on");
  sleepNow();
}

void sleepNow()
{
  // Choose our preferred sleep mode:
  set_sleep_mode(SLEEP_MODE_IDLE);
  // Set sleep enable (SE) bit:
  sleep_enable();
  // Put the device to sleep:
  sleep_mode();
  // Upon waking up, sketch continues from this point.
  sleep_disable();
}

Because any interrupt will wake it up from Idle, including those used by the Arduino libraries.

So what is waking up my Arduino in the code I have above? I don't have anything there besides the the sleepNow() function.

What is waking it up is what you don't see in the code above nonetheless exists.

In idle sleep, the timer interrupts will wake the processor, as  Ignacio Vazquez-Abrams said in his comment.
A "higher" sleep mode works, however I had to add Serial.flush () otherwise it only printed "P" because the processor goes to sleep before the serial output buffer has been emptied.
#include <avr/sleep.h>

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

void loop()
{
  Serial.println("Program is on");
  Serial.flush ();
  sleepNow();
}

void sleepNow()
{
  // Choose our preferred sleep mode:
  set_sleep_mode(SLEEP_MODE_PWR_SAVE);
  // Set sleep enable (SE) bit:
  sleep_enable();
  // Put the device to sleep:
  sleep_mode();
  // Upon waking up, sketch continues from this point.
  sleep_disable();
}

See my page about power savings.

Do you know if there is anyway to wake it up with you are using the SLEEP_MODE_PWR_SAVE mode?

@CrystalPritzker: There are a few. See the "Power-save" row in the "Sleep Modes" section of the datasheet.

See my page about power savings. Pin-change and external interrupts wake the processor from any sleep state. I think a serial interrupt will too. Also a watchdog timer interrupt can be used.


text:
Understanding Digital IMU 6DOF sketch
I am looking at the following code and getting confused by a few elements in it:
1) Why is there a writeto function being performed to the memory locations x053,0x31,x09 for accelerometer and 0x68,0x16 and 0x1A for gyro? We are only reading incoming values so what is the purpose of these functions?
2) the bitwise operation being performed in the getGyrscopeReadings and getAccelerometerReadings... are these operations to define how many bits data we will be reading?
    #include <Wire.h> //The I2C library

int gyroResult[3], accelResult[3];

//Function for writing a byte to an address on an I2C device
void writeTo(byte device, byte toAddress, byte val) {
  Wire.beginTransmission(device);
  Wire.write(toAddress);
  Wire.write(val);
  Wire.endTransmission();
}

//Function for reading num bytes from addresses on an I2C device
void readFrom(byte device, byte fromAddress, int num, byte result[]) {
  Wire.beginTransmission(device);
  Wire.write(fromAddress);
  Wire.endTransmission();
  Wire.requestFrom((int)device, num);
  int i = 0;
  while(Wire.available()) {
    result[i] = Wire.read();
    i++;
  }
}

//Function for reading the gyros.
void getGyroscopeReadings(int gyroResult[]) {
  byte buffer[6];
  readFrom(0x68,0x1D,6,buffer);
  gyroResult[0] = (((int)buffer[0]) << 8 ) | buffer[1]; //Combine two bytes into one int
  gyroResult[1] = (((int)buffer[2]) << 8 ) | buffer[3];
  gyroResult[2] = (((int)buffer[4]) << 8 ) | buffer[5];
}

//Function for reading the accelerometers
void getAccelerometerReadings(int accelResult[]) {
  byte buffer[6];
  readFrom(0x53,0x32,6,buffer);
  accelResult[0] = (((int)buffer[1]) << 8 ) | buffer[0]; //Yes, byte order different from gyros'
  accelResult[1] = (((int)buffer[3]) << 8 ) | buffer[2];
  accelResult[2] = (((int)buffer[5]) << 8 ) | buffer[4];
}

void setup() {
  Wire.begin();            //Open I2C communications as master
  Serial.begin(9600);    //Open serial communications to the PC to see what's happening

  writeTo(0x53,0x31,0x09); //Set accelerometer to 11bit, +/-4g
  writeTo(0x53,0x2D,0x08); //Set accelerometer to measure mode
  writeTo(0x68,0x16,0x1A); //Set gyro to +/-2000deg/sec and 98Hz low pass filter
  writeTo(0x68,0x15,0x09); //Set gyro to 100Hz sample rate
}

void loop() {
  getGyroscopeReadings(gyroResult);
  getAccelerometerReadings(accelResult);

  Serial.print(gyroResult[0]);
  Serial.print("\t");
  Serial.print(gyroResult[1]);
  Serial.print("\t");
  Serial.print(gyroResult[2]);
  Serial.print("\t\t");
  Serial.print(accelResult[0]);
  Serial.print("\t");
  Serial.print(accelResult[1]);
  Serial.print("\t");
  Serial.print(accelResult[2]);
  Serial.print("\n");

  delay(50);
}

any help would be greatly appreciated!

The writeTo functions
The accelerometer and gyro both have some memory inside that is used to store the configuration. The specific locations and values can be read from the datasheet, but for now I'll trust the comments. These writeTo functions seem to set the device modes and configure the scale used for the sensors.
Notice that they only happen once, right when the program starts. Maybe the devices have a way of storing persistent settings onboard, but setting them once at each startup is safe and easy.
The Bitwise ops
These don't set the number of bits we are reading per se, They reconstruct larger than 8-bit values. The I2C serial protocol is set up to use 8-bit data segments, so to send any value larger than 8-bits they must be broken down, sent, and then "stitched" back together in chucks.
(((int)buffer[0]) << 8 ) | buffer[1];
Whats happening here is that buffer[0] is converted to int (a 16 bit value), then shifted over by 8 bits. This means the 8 bits in the original buffer[0] are now located in the top 8-bits of the integer, and the lower 8 bits are zeros. Finally the lower 8 bits are set by the bitwise-or operator |, which will turn on any bits that were set in buffer[1] in the result. Since the bottom 8-bits were 0's from the shift, this just copies buffer[1] in exactly.
The net effect is a 16 bit value that contains the bits of both 8-bit buffer values and can be interpreted as a single number.


text:
Comparing orientation data obtained using gyroscope and accelerometer
Recently, I have been playing around with a gyroscope and accelerometer in the hopes of building a quadcopter. I have plotted some of the data the two sensors and I am noticing that the pitch from the accelerator lags significantly behind the gyroscopic pitch.
From some research, I understand that these two are not going to equivalent values due to the mechanisms of measurement, however is it common to have such large discrepancies (i.e a difference of 20 degrees or higher) between the two sensors or is this an issue with my conversion?
I have listed the graph and source code here. Any help would be appreciated!
Sincerely,
Anand

Normally the values from gyroscope will drift overtime. It is natural and depends on the parameters of your code. It could drift a few degrees per seconds and the data will be far way from the accelerometer in a few seconds.
I have seen that you have applied the complementary filter, so you don't need to worry about the single value from the gyros since you combine them with the acceleromter and everything seems fine.
The gyros are good for short time response, in long time response the values get pretty bad as they drift a lot.
On the other hand, accelerometers are good for long time response, since short time response is noisy because of gravitational influence.
That's why you need a filter to combine them.
Wrapping up, it is normal to have this behavior in gyros. If you want to know more about the effect behind this sensor, try this reading.


text:
getting simple socketIO server to work with MRAA library on Edison
I spent the last week working with the CylonJS framework on my edison using a Maxbotix sensor.
Everyting works with a web client on the front end.
However at the last moment I can't get the edison to talk to an existing AIR client which I must use.
Something to do with how socketIO is implemented in Cylon.
The following simple socketIO server works for me. What I need to do is incorporate support for the mraa library and get analogue input from the Maxbotix sensor.
Can anyone please help? I'm up against a deadline!!!
var express = require('express');
    var app = express();
    var server = require('http').createServer(app);
    var io = require('socket.io').listen(server,{transports:['flashsocket', 'websocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']});
     var port = Number(8080);
    server.listen(port);
     app.use(express.static(__dirname + '/'));
     var temp;
     var _this = this;
     io.on('connection', function (socket) {
      console.log('connection '+socket)
     socket.on("data",function(d){console.log('data from flash: ',d);});
      socket.emit("message","wtfwtwftwftwf hello from server");
      socket.on('disconnect', function (socket) {
      console.log("disconnect");
  });

  console.log('_this ='+_this);
  _this.socket=socket;

});


text:
Timeout error uploading code to Arduino Mega 2560
I am new to Arduino programming, and my first sketch (from a tutorial) failed to upload. I am having trouble trying to figure out what is causing it (have tried to upload the sketch using different COM ports on my Mac).
Here's my setup:

USB COM Port -> Arduino Mega 2560 -> Grove Mega Shield -> Grove Temperature Sensor
  v1.2 connected to Mega Shield UART0.

Here's the code from the tutorial:
// Demo code for Grove - Temperature Sensor V1.1/1.2
// Loovee @ 2015-8-26

#include <math.h>

//R0 = 100000 results in 'overflow in implicit constant conversion'

const int B=4275;                 // B value of the thermistor
const int R0 = 100000;            // R0 = 100k
const int pinTempSensor = A5;     // Grove - Temperature Sensor connect to A5

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

void loop()
{
    int a = analogRead(pinTempSensor );

    float R = 1023.0/((float)a)-1.0;
    R = 100000.0*R;

    float temperature=1.0/(log(R/100000.0)/B+1/298.15)-273.15;//convert to temperature via datasheet ;

    Serial.print("temperature = ");
    Serial.println(temperature);

    delay(100);
}

And here's the error output:
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_cmd(): short reply, len = 0
avr_read(): error reading address 0x0000
    read operation not supported for memory "signature"
avrdude: error reading signature data for part "ATmega2560", rc=-2
avrdude: error reading signature data, rc=-1
avrdude: stk500v2_ReceiveMessage(): timeout

What I have done so far:
1) Disconnect and reconnect USB Cable
2) Restart Arduino IDE (1.6.9)
3) Changed COM Ports
4) Press the reset button
Could someone please explain to me what the error output means?

Connect Mega 2560 in one of your port, select the right com port, and try to load the white sketch, look if you obtain the same error..
//white sketch
void setup(){}
void loop(){}

Have you tried to upload your sketch without the shields? I had a similar problem once where I couldn't upload while a connection was plugged into UART0. Unplugging the sensor worked for me.

I unplugged the sensor but it didn't work. What I did to finally get it to work was, to plug it into a different UART port and reset the board. Glad it works now.

With an arduino Mega I usually use UART1 for sensors and so on and I keep UART0 free fror communication with the PC. Sorry, I should have mentioned that in my answer...


text:
RF receiver for integer only, how to cast uint8_t to int?
I'm using the RadioHead library with ASK Driver to transmit/receive data with generic RF modules. It works fine, but I'm lacking some knowledge in programming the code to use the data received. Most examples I could find show how to send a string, but I only need to send and receive an integer.
I'm sending the decimal value '1' through the transmitter:
    uint8_t *data;
    uint8_t value;

    void loop() {
    value = 1;
    data = &value;
    driver.send(data, sizeof(value));
    driver.waitPacketSent();
    delay(200);
    }

And I have in the receiver:
void loop() {
  uint8_t buf[RH_ASK_MAX_MESSAGE_LEN];
  uint8_t buflen = sizeof(buf);
  int value;

  if (driver.recv(buf, &buflen)) {
    driver.printBuffer("Received:", buf, buflen); //prints 1.
    value = (int) buf; //my attempt to cast
    Serial.println(value); // the output is 2233, so this is wrong.
  }
  if (value == 1){ //example
  Serial.println("good");
  }
}

So what I think it is, I'm receiving bytes from the transmitter, which the library function 'driver.printBuffer' reinterprets as decimals and prints the value '1'. But how do I interpret (or cast) this as an integer so I can use it for other things like in the example (If condition) at the end? Any help is very much appreciated. Thanks.

buf is a pointer to the received bytes. Try value = buf[0]; instead.

that makes sense, it worked perfectly thanks!

This of course only works for small positive values that fit in an 8-bit type.  For larger values you will need to be more sophisticated.


text:
How to map integer values and round to a count of tens/thousands?
I'm mapping a potentiometer from 0-1023 to 1000-120000 (1 sec to 2 minutes) for a timer, like:
maxDelay = map (pot2, 0, 1023, 1000, 120000);

Both variables are integers. Now I would like to convert/round values to counts of 10 seconds (a count of thousands), so if I have anything from 1001-5000 this would be rounded to 1000 (1sec), and if I have 5001-10000 it would be rounded to 10000 (10 secs), then 20sec, 30sec, etc...until it reaches 120secs. I know I could have a few "if" statements but I'm trying to figure out the right way of doing these maths. Thanks.

I didn't yet compiled it, but something like this should work:
#include <Math.h>

int converter(int x)
{
    if(x <= 5000)
        return 1000;
    else
        return (int)(round(x / 10000.0) * 10000.0);
}

I'm not sure that's what I'm looking for....for example, if the value (x) is 2500, dividing by 1000 is 2.5...the result I'm expecting is 1000. How is this going to round the values?

In the wonderful world if integers dividing 2500 by 1000 gives us 2. I thing I misunderstood your question. You want the system to show only values 1,10,20,30... Right?

right, but still I need it to be 1000 when smaller than 5000...but in this case I can just have an IF. But when higher than 5000, for example 8000, it should result in 10000...(rounds up 8 to 10, etc)..17000 to 20000...

Yes, 1, 10, 20, 30..that's it.

that's great! it looks good now, I will have a go and let you know. Thanks.

Sorry it's still not working for 17000 rounding to 20000 give me a minute.

yes, I noticed this way it will always round numbers down...which is not what I expected but it's OK, it should do the job. Although if you want to improve the answer I appreciate too. thanks! :)

Instead of using properties of integer unfortunately I had to use round method. It's not as elegant (it requires cast to double and then back to integer to work correctly) but this approach should do exactly what you want.

Just a note for future reference (if anyone is looking for a similar solution), on an Arduino Due this should work fine, but on Atmega boards I used an unsigned long instead of an integer since these values are over 32,767.

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


text:
serial.write() five sensors and Processing
To all of this, hope to formulate the question right.
In my project I have 5 sensors connected to Arduino, which I want to interpret via Seria.write() --> Processing.
Arduino:
firstSens = 100 + (155 * digitalRead(8));
secondSens = analogRead(A1)/4;
thirdSens = analogRead(A2)/4;
fourthSens = humData;
fifthSens = tempData;
int sensData[6] = {firstSens, secondSens, thirdSens, fourthSens, fifthSens};

int i;
for (i = 0; i < 5; i = i + 1) {
  Serial.write(sensData[i]);
}

Processing:
serialInArray[serialCount] = inByte;
    serialCount++;

if (serialCount > 4 ) {
  firstSens = serialInArray[0];
  secondSens = serialInArray[1];
  thirdSens = serialInArray[2];
  fourthSens = serialInArray[3];
  fifthSens = serialInArray[4];

  // print the values (for debugging purposes only):
  println(firstSens + "\t" + secondSens + "\t" + thirdSens + "\t" + fourthSens + "\t" + fifthSens);

  // Send a capital A to request new sensor readings:
  myPort.write('A');
  // Reset serialCount:
  serialCount = 0;

My problem is that sensors find their place in Processing's array randomly, so for example arduino's firstSens could be Processing's secondSens or fifthSens
Why is this happening and how can I control it?

What is happening is you are just spewing out a list of numbers:
4132
132
1928
3240
1239
238
3048
391
... etc ...

There is nothing anywhere to say what anything is.
You need to add that kind of information. Either as a "start of data" tag before each block, or with each line.  For instance:
---START OF DATA---
4132
132
1928
3240
1239
---START OF DATA---
238
3048
391
... etc ...

Or:
0:4132
1:132
2:1928
3:3240
4:1239
0:238
1:3048
2:391

It is then up to your processing application to interpret the data and work out what is what.
Personally I like using the second method since it means you don't have to send all the data every time - you can send different values at different speeds of update and maintain a "current value" at the Processing end. For instance if you have one value that updates frequently and others that don't:
3:4132
1:132
3:1928
3:3240
3:1239
2:238
3:3048
0:391

You don't even have to use numbers, you could use words:
pressure:4132
temperature:132
pressure:1928
pressure:3240
pressure:1239
humidity:238
pressure:3048
rainfall:391

I have done similar code for our car project dash display
you're looking for something like this on your Arduino side:
  Serial.print("U*"); //A header
  Serial.print("A");  //a token to indicate the message payload
  Serial.print(avgRPM);
  Serial.println("");

  Serial.print("U*"); //A header
  Serial.print("B");  //a token to indicate the message payload
  Serial.print(avgVoltage);
  Serial.println("");

  Serial.print("U*"); //A header
  Serial.print("C");  //a token to indicate the message payload
  Serial.print(avgCurrent);
  Serial.println("");

  Serial.print("U*"); //A header
  Serial.print("D");  //a token to indicate the message payload
  Serial.print(avgThrottle);
  Serial.println("");

  Serial.print("U*"); //A header
  Serial.print("E");  //a token to indicate the message payload
  Serial.print(avgBrake);
  Serial.println("");

and something like this on processing side:
 if (port.available() > 0) {
    data = port.readStringUntil('\n');
  }
  String payload = "";
  if (data != ""){
    int offset = data.indexOf("U*"); //this is our Header (0x552A)
    if(offset>=0){
      payload = data.substring(offset+3, data.indexOf('\n'));
      switch(data.substring(offset+2, offset+3)){
        case "A":
          RPM = payload;
          break;
        case "B":
          voltage = payload;
          break;
        case "C":
          current = payload;
          break;
        case "D":
          throttle = payload;
          break;
        case "E":
          brake = payload;
          break;
        case "F":
          telemBits = payload;
          break;
        default:
          //packet not recognised
      }
    }
}


text:
Arduino LCD Screen
I am newer to arduinos, and could use some help. I have a LCD screen hooked up to an arduino uno. I can get it to display whatever I type in, which is great. But, what i want it to display is a value from an excel spreadsheet. So, it will change depending on what is in that field. Or even better yet, from access. Is this possible? is there code to have the arduino pull information from an existing table? (assuming it is connected via USB, or, eventually, wifi). thanks!

Assuming your Excel spreadsheet or Access table is stored on your PC, you can write a PC program to read the file and send the data serially over the USB connection to the connected Arduino, which can display it on the LCD.
If the file is stored on an SD card instead, and you want the Arduino to access the file directly by reading said SD card (through an Ethernet shield perhaps), you need to make the file format a lot simpler than XLS to ease parsing; CSV is quite simple and suitable for a lot of tasks. The built-in SD library can be employed to read the data from the card, the Arduino parses the data and displays it on the LCD.
In general, I suggest you do more research.

Why I came here =) I have been digging around, and found that exporting data is easy, but importing it is a whole new monster. Would it be easier to code the arduino in a way that it always reads from the same file location, same lines, same file, in lets say txt format. then access or excel just exports to the same place every time in txt format?

@niva5171 Where will the file be located?

It can be anywhere really. I can have access export the file to any location

@niva5171 What I mean is, will the file be on an SD card connected to the Arduino or on your PC? The former will remove the need for a connection to the PC while the latter will remove the burden of storing the files and parsing them.

Sorry, it is on the network drive (So the PC). Right now any computer can access it. Right now through USB, eventually through WIFI

@niva5171 In that case, you should understand that your Arduino sketch has no control over your PC, at least not without some cooperation from your PC's side. You need to write a program for your PC, in some language, that will open the file, parse it and ultimately send the data to be displayed to the Arduino over the serial connection or WiFi. The only task for the Arduino is to listen for data and print whatever it receives to the LCD. The rest is left for your PC program.

@niva5171 Sure. I suggest you explore the CSV format, which is very straightforward and can be used with Excel. Also try Python for the PC program; its easy to get started with a few lines of code and there are a lot of tutorials on using "pySerial".

Great! I will give that a look into, thanks again!

It is not the easiest thing to do especially if you are newer to arduinos but Roberto Valgolio has made an Arduino Excel interface: http://www.robertovalgolio.com/sistemi-programmi/arduino-excel
I have not worked with it yet but it's worth looking into it.

Yeah, ive noticed that really quickly unfortunately, but if I can figure out how to do it, it could be a really cool advancement for my company. thanks for the link!


text:
Distance finder technology 0-24inches
Can anyone point me towards whats best for relatively low cost distance measuring in the 0-36" range (or 0 - 1m range) with 1/16"/1mm accuracy.  My initial approach was going to be to hack a laser tape measure, but wanted to know if that was the best in cost vs accuracy.
Essentially looking to measure how close I am to a stationary metal plate.
Thanks for any help.

Most "laser" tape measures are merely a laser pointer strapped to an ultrasound range finder. Ultrasound is by far the simplest and cheapest option though its accuracy can sometimes be a little "iffy".

Your suggestion regarding "most" is an invalid generalization and inaccurate as well. Laser rangefinders use lasers, ultrasonic rangefinders use ultrasound, with perhaps a laser indicator for aiming, but it is necessary only to read the product specifications to determine the method of use.

@fred_dot_u If a "laser tape measure" is cheap enough to be destined for hacking then it's using ultrasound. All the "laser tape measures" I have ever seen at DIY stores, or have ever owned, or have ever used, have been ultrasound. Yes, there are laser based range finders, but they are considerably more expensive and outside the "hackable" price bracket.

http://www.dx.com/p/uni-t-ut390b-45m-laser-distance-meter-178482#.V2q--6IiXQo
Granted, it's out of stock, but fifty-one american dollars is low enough cost to be hacked and it's laser. Fully optical, zero ultrasound. My point was that "most" are not. Some are laser, some are ultrasound. You've added an interesting ambiguity to the equation as well. "Cheap enough" is difficult to pin down. Fifty or one hundred dollars is cheap enough if someone has enough motivation and can make a project work. Two hundred dollars is cheap enough if success is a certainty. All this is opinion, of course.

You will likely find the best accuracy is derived from a laser-based measurement. My Bosch is laser only, no ultrasound component and has 1/16" resolution. For your application, the six inch minimum distance limitation of the Bosch is outside your specifications.
Because laser measurement devices use time versus distance, it's possible you could construct a mirror chamber with front-surface mirrors that would cause the laser to travel six inches before exiting the chamber, overcoming that limitation. The calibration should be straight-forward, as you'd place the chamber flush and adjust your mirror placement until you read the exact expected compensation distance.
You would need only small mirror panes, which would not "break the bank," but if you find a discarded large-screen projection television, the mirror within is front surface and quite large. Front surface mirrors should not have contamination from touching and should be cleaned with care, as you can erode or otherwise degrade the reflective surface.
I found this site:
http://blog.qartis.com/arduino-laser-distance-meter/
which looks promising for a different model of laser rangefinder, although the creator has run into a stumbling block or two.
It would appear that the key is to overcome the minimum distance limitation, perhaps as I suggested above, and interfacing with serial communications of the arduino.
One of the links I pursued involved the creator contacting the technical support of the manufacturer. The support ticket was closed as "resolved," in the manner of advising the user that the warranty was void by opening the case. Yeah, like that matters to makers and hackers!

Thank you very much for this.  I really like the idea of overcoming the limitation by using a mirror chamber. I wonder why most manufacturer's do not.

Consider how much labor you might put into building a mirror chamber, as well as the effort in calibrating/tuning the light path. A manufacturer may not be able to design and build something that works for Joe Consumer, but we maker-folk are pretty resourceful. What cost is your labor when you are creating? For some of the stuff I build, for the fun and experience, it appears that I'm paying people to do this kind of work. But then again, what price is fun?

If you have a 3d printer or access to one, you could design a mirror chamber in which to glue or slide the mirror segments as well as include a compartment for the Arduino, although the image in my alleged mind may not match yours, as I do not know the precise application.


text:
Issue while connecting ESP8266 with Arduino Mega. It always says “Module have no response.”
I am having Issue while connecting ESP8266 with Arduino Mega. It always says "Module have no response."
Please check and correct me if I am wrong anywhere.
I am using below code and and wiring diagram is

My Code:
//#include <SoftwareSerial.h>
   //use mega Serial 2 for serial monitor; Serial 1 on pins 19 (RX) and 18 (TX);// Serial2 on pins 17 (RX) and 16 (TX), Serial3 on pins 15 (RX) and 14 (TX).
   #define SSID "SopraSteria"
   #define PASS "1234567890"
   #define DST_IP "220.181.111.85" //baidu.com
   //SoftwareSerial dbgSerial(10, 11); // RX, TX
   void setup()
   {
     // Open serial communications and wait for port to open:
     //serial 2 is to esp8266
     Serial2.begin(115200);//9600 (mine), 57600, 115200
     Serial2.setTimeout(2000);

     //serial 0 is to usb
     Serial.begin(115200);

     while(!Serial);
     while(!Serial2);

     //dbgSerial.begin(9600); //can't be faster than 19200 for softserial
     //dbgSerial.println("ESP8266 Demo");
     Serial.println("ESP8266 Demo on Mega2560");

    while(Serial2.available()>0)
    Serial2.read();

     delay(1000);
       //test if the module is ready
     Serial2.println("AT+RST");
     //delay(1000);
     //delay(1000);
     Serial.println("Resetting module");
     Serial2.flush();
     //Serial.println(Serial2.read());
     //if(Serial2.find("ready"))
     if(Serial2.find("Ready")||Serial2.find("ready"))
     {
       //dbgSerial.println("Module is ready");
       Serial.println("Module is ready");
     }
     else
     {
       //dbgSerial.println("Module have no response.");
       Serial.println("Module have no response.");
       //while(1);
     }
     delay(1000);
     //connect to the wifi
     boolean connected=false;
     for(int i=0;i<5;i++)
     {
       if(connectWiFi())
       {
         connected = true;
         break;
       }
     }
     if (!connected){
      //while(1);
      Serial.println("Not Connected.");
     }
     delay(1000);
     //print the ip addr

   Serial2.println("AT+CIFSR");
     Serial.println("ip address:");
     while (Serial2.available())
     Serial.write(Serial2.read());

     //set the single connection mode
     Serial2.println("AT+CIPMUX=0");
   }
   void loop()
   {
    //connectWiFi();
     String cmd = "AT+CIPSTART=\"TCP\",\"";
     cmd += DST_IP;
     cmd += "\",80";
     Serial2.println(cmd);
     Serial.println(cmd);
     Serial.println(cmd);
     if(Serial2.find("Error")) return;
     cmd = "GET / HTTP/1.0\r\n\r\n";
     Serial2.print("AT+CIPSEND=");
     Serial2.println(cmd.length());
     if(Serial2.find(">"))
     {
       //dbgSerial.print(">");
       Serial.print(">");
       }else
       {
         Serial2.println("AT+CIPCLOSE");
         //dbgSerial.println("connect timeout");
         Serial.println("connect timeout");
         delay(1000);
         return;
       }
       Serial2.print(cmd);
       delay(2000);
       //Serial.find("+IPD");
       while (Serial2.available())
       {
         char c = Serial2.read();
         //dbgSerial.write(c);
         Serial.write(c);
         //if(c=='\r') dbgSerial.print('\n');
         if(c=='\r') Serial.print('\n');
       }
       //dbgSerial.println("====");
       Serial.println("====");
       delay(1000);
     }
     boolean connectWiFi()
     {
       Serial2.println("AT+CWMODE=1");
       String cmd="AT+CWJAP=\"";
       cmd+=SSID;
       cmd+="\",\"";
       cmd+=PASS;
       cmd+="\"";
       //dbgSerial.println(cmd);
       Serial2.println(cmd);
       Serial.println(cmd);
       delay(2000);
       if(Serial2.find("OK"))
       {
         //dbgSerial.println("OK, Connected to WiFi.");
         Serial.println("OK, Connected to WiFi.");
         return true;
         }else
         {
           //dbgSerial.println("Can not connect to the WiFi.");
           Serial.println("Can not connect to the WiFi.");
           return false;
         }
       }

Well, you seem to be wired into Serial1 yet you're using Serial2 to communicate...

I am using Serial2 with pin 16, 17. this diagram is my reference but using serial2

And are you using the same ESP module? There's lots of different ones.  The one pictured there is the ESP-01

Yes Majenko I am using the same one.

Have you tried different baud rates? Different versions of the AT firmware have different baud rates set as default. You need to make sure you match them up.

if(Serial2.find("Ready")||Serial2.find("ready")) cannot match the second possibility until is has either matched the first, or the first has timed out, because this method consumes characters while seeking a match.  It might be better to grab whole lines and then test them, though you could also "cheat" by doing a find for "eady" which would match either.

Your transmitter and receiver pins need to be crossed, rx->tx and tx->rx. As a mnemonic, the two ends of the antenna point to the board edge with the receiver pin and it is that pin that needs the voltage divider. While you're at it, it would be a good idea to tie the RST pin high, as well as the CH_PD. I use one 10K pullup for both.
Recent versions of these boards are shipped with their baud rates set to 115200. Since you're using a hardware UART on the Mega board, you can send/receive to it at that rate.
Note to readers using a software UART (SoftwareSerial): First thing, change the board's baud rate to 9600 and communicate with it at that rate. You can use SoftwareSerial to make the change as it sends at 115200 reasonably reliably, but its receive function can't keep up at that rate).
You can confirm your connections and baud rate with:
EspSerial.println("AT");
You should receive `OK' in reply.

I took your code as a starting point and got it to work with some small modifications. I am providing my version below for your review. I had to add a bunch of delays. I am also communicating with the ESP8266 at 19200 baud.
I have not optimized the timing yet but I was able to run this code for 24 hours straight with no issues. I am using Pins 6 and 7 on the Arduino for COMM to the ESP8266.
#include <SoftwareSerial.h>
#define SSID "YOURSSID"
#define PASS "YOURPW"
#define DST_IP "220.181.111.85"

SoftwareSerial Serial2(6, 7); // RX, TX

void setup() {

// Open serial communications w ESP8266
Serial2.begin(19200);
Serial2.setTimeout(5000);

// serial 0 is to usb
Serial.begin(115200);
while(!Serial);
while(!Serial2);

Serial.println("ESP8266 Demo on Mega2560");

while (Serial2.available() > 0)
Serial2.read();
delay(1000);
while (Serial2.available() > 0)
Serial2.read();

//test if the module is ready
Serial.println("RESETTING ESP8266 WIFI CHIP");
Serial2.write("AT+RST\r\n");
delay(2500);
while (Serial2.available() > 0)
Serial.write(Serial2.read());

delay(2500);
while (Serial2.available() > 0)
Serial.write(Serial2.read());
Serial.println("");

//  connect to the wifi
boolean connected=false;
for(int i=0;i<5;i++) {
if(connectWiFi())
{
connected = true;
break;
}
}

if (!connected){
Serial.println("Not Connected.");
}

Serial2.println("AT+CIFSR");
delay(2000);
while (Serial2.available())
Serial.write(Serial2.read());
delay(2000);
while (Serial2.available())
Serial.write(Serial2.read());

//  set the single connection mode
Serial2.println("AT+CIPMUX=0");
delay(2000);
while (Serial2.available())
Serial.write(Serial2.read());
delay(2000);
while (Serial2.available())
Serial.write(Serial2.read());
}

void loop() {

String cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += DST_IP;
cmd += "\",80";
Serial2.println(cmd);
Serial.println(cmd);
delay(5000);

if(Serial2.find("Error")) return;

cmd="GET / HTTP/1.0\r\n\r\n";
Serial2.print("AT+CIPSEND=");
Serial2.println(cmd.length());
delay(2000);

if(Serial2.find(">"))      {
Serial.print(">");
}
else {
Serial2.println("AT+CIPCLOSE");
Serial.println("connect timeout");
delay(2000);
return;
}
Serial2.print(cmd);
delay(2500);

while (Serial2.available()) {
char c = Serial2.read();
Serial.write(c);;
if(c=='\r') Serial.print('\n');
delay(5);
}

Serial.println("");
Serial.println("====");
delay(2000);
}

boolean connectWiFi() {

String cmd;
int iIP;

iIP = 0;
Serial2.println("AT+CWMODE=1");
delay(5000);
while (Serial2.available())
Serial.write(Serial2.read());

cmd="AT+CWJAP=\"";
cmd+=SSID;
cmd+="\",\"";
cmd+=PASS;
cmd+="\"";

Serial2.println(cmd);

delay(2000);
Serial.println("Line 1");
while (Serial2.available() > 0)
Serial.write(Serial2.read());

delay(2000);
Serial.println("Line 2");
while (Serial2.available() > 0)
Serial.write(Serial2.read());
if (Serial2.find("OK")) {
Serial.println("WIFI OK was received!");
iIP = 1;
}

if( iIP == 1 ) {
Serial.println("OK, Connected to WiFi.");
return true;
}
else  {
Serial.println("Can not connect to the WiFi.");
return false;
}

}

As shown in the Fritzing diagram, you have connected the ESP8266 to the Mega's Serial1 pins (18 and 19), but in the program, you try to interact with Serial2 (pins 16 an 17). For this to work, your wiring and your program must match.

@ChrisStratton - I think that, prior to your edit, the answer was somewhat short and seemed more appropriate as a comment, hence my comment. Now, with the expanded and "explicit" edit, my comment is no longer valid. :-) well done for spotting it (as Majenko also did) and I shall give the answer a vote up

Good point, it's only repeating something already observed in comments long before.  Upvote removed.

@ChrisStratton - Also... it seems (after re-reading the reply to Majenko's comment) that the Fritzing diagram is not totally accurate, and that pins 16 and 17 are actually being used, rather than 18 and 19 as shown in the diagram: I am using Serial2 with pin 16, 17. this diagram is my reference but using Serial2. So... that renders this answer as being invalid. I shall attempt to remove my upvote as well.


text:
compare uint8_t to char array
I am not actually using ad arduino but an atmel chip. but my question is c microprocessor related
I am reading an uart which returns data in the form uint8_t [100]
I can print the  return just fine, the return is "OK"
but when I try to use strcmp(read, "OK")
I do not get the expected value, I get a mismatch ( strcmp returns 13, not 0)
uint8_t  sigfox_rd_buf[100] = {0};
uint8_t sig_rd = 0;

io_sigfox->read(io_sigfox,&sig_rd, 1);
while(sig_rd != 10) // read until end char
 {
     sigfox_rd_buf[i] = sig_rd;
     i++;
     io_sigfox->read(io_sigfox,&sig_rd, 1);
 }
 if(strcmp((char *)sigfox_rd_buf,"OK") == 0 )
 {
  do_something()
 }
 else
{
complain();
}

and I always end up in complain for some reason.. please help!! :)

Does 13 not give it away?

An unexpected carriage return could indeed be an issue, though it's an implementation quirk if an actual character is returned by strcmp().  But the code also fails to terminate the string in the receive buffer - it may work if the startup code zero initializes memory and it has not been touched since but subsequently it may run away comparing residual garbage until finally finding a zero byte.

Bahh stupid copy paste error... was taken for another uart read sequence where the message ends with a line feed and a carriage return!
somehow I stared my self blind..

When using strcmp(), strings should be terminated with a NULL character.  Which, by the way, is a zero. Your code should work as is if you replace the Line Feed character (10 or 0x0a) with a NULL (0 or 0x00). That is assuming the string you are getting back is 0x4f, 0x4b & 0x0a.  Or you could play it safe and replace strcmp with strncmp.  Then explicitly state the number of characters to compare:
if(strncmp((char *)sigfox_rd_buf,"OK",2) == 0 )

In general, yes, but we don't actually know that the data providing function will return nulls at this point, or if how much data we over or under read will leave the next run in a bad starting condition.  Sigfox perhaps implies packets more than streams, but the interface being used looks at least momentarily stream-like.

Ok, I change the wording so as to explicitly state strcmp() string arguments should be terminated by NULL.


text:
Access method from main sketch inside class
I am lost at this one. In Java, I would do it this way:
Inside the main sketch, I would instantiate the object from the class:
do = new DoClass(this);

I would also include a method inside the main sketch:
public void doSomething(){}

Then, inside the DoClass, I would have the following constructor:
    public class DoClass{
       Sketch sketch;
       public DoClass(Sketch skt){
          this.sketch = stk;
       }
 }

Then, at some point, I would call, from DoClass:
stk.doSomething():

which should be the same as calling:
doSomething();

from the main sketch. Any ideas how to achieve that? If yes, could you please show an example of how to achive the above example in Arduino?

So... just like a callback then?

Unlike Java, which insists on everything being inside a class, C++
allows “plain” functions which do not belong to any class. In fact,
main() in standard C++, as well setup() and loop() in Arduino
code, are all plain functions. Then, the main program (or “sketch” if
you wish) is not an object, you cannot give it to the constructor of
your class. Instead, you would give it a pointer to the particular
function it needs. This is called a callback, because the library is
calling back something from your main program.
Here is how I would write it in C++:
/*
 * Class definition.
 */

class DoClass {

    // Define a callback type: a pointer to a function taking no
    // arguments and returning void.
    typedef void (*callback_t)();

public:
    // Constructor.
    DoClass(callback_t _callback)
        // Initialize internal callback with the one given as parameter.
        : callback(_callback)
        // empty function body
        {}

    // This class method invokes the callback.
    void doIt() { callback(); }

private:
    // The callback is kept as private internal data.
    callback_t callback;
};

/*
 * Main program.
 */

// This is the function we are going to provide as a callback.
void doSomething()
{
    Serial.println(F("Doing some work..."));
}

// Instantiate the class statically.
DoClass doObject(doSomething);

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

void loop()
{
    doObject.doIt();  // <- this will invoke our callback.
    delay(1000);
}

The class could be instantiated dynamically
(DoClass *doObject = new DoClass(doSomething);).
I prefer to do it statically when possible, because dynamic memory
allocation can easily led to memory fragmentation problems in such small
platforms.

Precisely what I was looking for. Thanks!

The great thing about Java is that it was designed to have a similar syntax as C++ and Arduino will gladly compile C++. So if you're familiar with Java this should be pretty easy for you.
check out This Tutorial
As for your example...
Much like Java, it is best practice to put C++ classes in their own files, but it is not required. If you use Java you are used to "importing" modules and classes into the class you are creating. Similarly C++ imports header files (behind the scenes it is much different, but functionally the same).
To do this first you would create a header file. This is just a text file with the extension ".h" or ".hpp" intead of ".txt" - traditionally .h is used only for c files and .hpp would be for c++. The header file will include the class and method prototypes.
Before I get to your example, as a side note:
Your example using the "sketch" variable is somewhat confusing because a sketch is just what the world of Arduino calls a program and it would not be used as variable.
"DoClass.hpp"
class DoClass {
  int var;
public:
  DoClass(int var);
  int getVar();
};

"DoClass.cpp"
#include "DoClass.hpp"

DoClass::DoClass(int variable){
  var = variable
}

int DoClass::getVar(){
  return var;
}

The "::" means "member of" so the getVar() is a method of DoClass.
These files should be saved in your sketch folder. If you are creating a class that will be reused you can place it in ../sketches/libraries/.
#include "DoClass.hpp"
setup(){
  ...
}

DoClass myClass(5);  // creates class
int testVal;

loop(){
  ...
  testVal = myClass.getVar();

}

This worked wonderfully when the callback is to a function in the sketch. Where I am having problems is when the callback is in a class. See here for more: https://arduino.stackexchange.com/questions/68299/parent-class-callback-from-child-class

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


text:
Use LDR with 220 ohm resistor
I have read many tutorials on LDR(Light dependent resistor) with Arduino which includes a 10 kilo ohm resistor but can i use it with 220 ohm resistor or even without resistor.

Do the math. If you know what you're doing, sure. However, the fact that you're asking suggests that you're not quite sure what you're doing, so if you try, you'll likely have problems making it work, or even damage your micro.

You can use it with no external resistor: connect it between an analog input and GDN, then activate the internal pullup resistor. This pullup has a value somewhere between 10 and 50 kΩ, typically around 30 kΩ. The large uncertainty in the pullup value means you will not be able to compute the resistance of the LDR but, given some calibration, it should be OK for telling light and shadows apart.

can you post an answer with example

It can't hurt to use the 220Ohm. Though with most typical LDRs you won't get the range of different values. I.e. the values get from analogRead in the light, and in the dark will be closer to each other. Giving you a worst "resolution".

Unless properly filtered, an LDR has a spectral sensitivity very
different from the human eye, which makes it unsuitable for any kind of
photometric measurement. It is also typically very loosely specified,
so you won't know the illuminance it receives better than a factor two
even if you measure its resistance very accurately. Thus, if you really
need accurate illuminance measurements like, e.g., for complying with
legal requirements, then forget the LDR and get a real luxmeter with a
calibration traceable to the SI lux standard.
Now, if you only want to tell apart substantially different illuminance
levels, like sunny and cloudy, then the LDR is fine. And don't let
Majenko scare you into believing you really need to know the resistance
of your pullup: it doesn't really matter.
That being said, you will get the best sensitivity if your pullup has a
resistance in the same range as the resistance of the LDR in the typical
conditions you will use it. Thus, if your LDR is nominally 10 kΩ, I
would avoid pulling up with 220 Ω, as the sensitivity would be very
poor. A 10 kΩ pullup resistor would be ideal, but the internal
pullup of the I/O pin (20 – 50 kΩ, 30 kΩ typical) should
be fine.
Many tutorials on LDRs use the ADC reading to compute a resistance, for
which you need to know the resistance of the pullup. If you want to
follow this path, just assume a 30 kΩ pullup. All your numbers will
be somewhat off, but that makes absolutely no difference, because you
don't know how to relate the resistance to the illuminance anyway.
I would suggest you forget about computing the resistance. Just look at
the raw ADC readings instead. Take some test readings in the typical
conditions that are of interest to you: now you have a baseline to which
you can compare further readings against. Keep in mind, though, that the
ADC readings get lower as the illuminance gets higher. And beware
that the resistance of the pullup, and probably that of the LDR also,
can be sensitive to temperature variations. You may do a hairdryer test
to check whether it gets really bad.
Example code? This one is pretty trivial:
/* Connect an LDR between A0 and GND. */

void setup() {
    pinMode(A0, INPUT_PULLUP);  // enable pullup for the LDR
    Serial.begin(9600);
}

void loop() {
    Serial.println(analogRead(A0));  // print out a reading
    delay(1000);                     // delay for one second
}

Thank you The code worked with LDR. But as you said that it does not fit the legal requirements what specefic luxmeter shall i buy

Would BH1759 be fine?

@Yash: That's another question, and one I do not have the answer to.

The simple fact is: you need a resistor with it. There's no getting away from that fact (short of building and using a constant-current source, but that's beyond the scope of this answer).
What value should the resistor be? Well, that depends on how sensitive or insensitive you want the LDR to be.
Yes, it will work with 220Ω, but will it give suitable results? Probably not. Ideally you want the resistor to be somewhere in the vicinity of the nominal resistance of the LDR - and that usually means 10s of KΩ.
As Edgar has mentioned, you can, at a pinch, use the internal pullup resistor of an IO pin instead of an external one (pinMode(A0, INPUT_PULLUP)), but the variability in the possible resistances that it might be make it pretty useless for anything more than "is it light or dark".
So you are best off getting a 10KΩ resistor where you then know that it is 10KΩ (or within a small percentage) and can calculate the LDR's resistance properly.

The variability in the possible resistances may not be an issue if he is only building one single setup.

@EdgarBonet Yes, but without knowing what the pullup resistor value is, even on just a single setup, the returned ADC values are pretty meaningless, other than "light" and "dark". Yes, you could experimentally work out the resistance of the pullup if you really wanted, but the simple fact that the OP has had to ask this question means that such experimentation will be beyond him.

Typical LDRs are so loosely specified that, even with a 10.000 kΩ pullup, the ADC values are meaningless without prior experimentation.

@EdgarBonet At least with a known pullup you only have one unknown. That then allows you to calculate the actual LDR resistance. With two unknowns you have no hope at all.

@EdgarBonet Anyway, they're illegal in most civilised countries due to the use of cadmium.

Why would you want to ever calculate the LDR resistance? That is completely useless without a precisely know illuminance–resistance function. Instead, just compare the raw ADC readings with previously taken test readings.

@EdgarBonet I wouldn't. But then I wouldn't use an LDR full-stop. My latest project used the Lite-On LTR-329ALS-01 which gives you the actual Lux value of both visible and IR illumination over I2C. And it's in a 2mm² surface mount package.


text:
Arduino and a Web Server
I'm here because I couldn't find any answer anywhere and the problem seems pretty easy and hard in a same time.
I have a website, for exemple : My_website.host.fr
I have arduino's sensors at home, for exemple temperature sensor in my garage, servomotor in shutter, etc... with Wifi-module.
I want to, as a User, access the website, update some information on the website, for exemple : I want the shutter down, so I put it to 0 on the website, and the arduino will, for exemple each X seconds check if the value has changed, if it does then it updates itself and so lower the shutter.
So, by this, i'll never have to connect directly through an @ip to my arduino, without hosting a server at home which could be hacked or anything, the arduino update itself with the infos that are on the website,
So from my arduino I must ? I have no idea, get the source code of the web page and search for some value, or, from the web page, update a file with PHP variables and retrieve that file with my arduino then read it for the values ?
I don't know if it's clear tho and I have no idea how to manage it.
Sorry about the bad english sentence or words, not main language;
Thank for the help i'm kind of lost.

You will have to make a web API. Make it as simple as possible. E.g. "GET /shutter" would return just 0 or 1.

MQTT might be a good solution for this...

You're in luck! A lot of people are doing, or trying to do similar things. One way of doing it is using a provider like adafruit.io. I imagine there are many other providers out there. Or will be.

Could you please provide more information about the server? Is this a website you own? If so, does your hosting provider allow you to put scripts? If so, in what language(s)? You mentioned PHP, is it supported by your provider? If so, do you know some PHP? I'm asking all this because your discussion with st2000 is revolving around scrapping data from HTML, which would be a very bad idea if you can easily have the server deliver text/plain.

Another option is Blynk who offer a server, a smartphone app, and a set of libraries and example sketches for Arduino. Also an active and helpful online user community, where the developers participate.
The server does not make view-able web pages; its job is to enable the Arduino and the app to communicate with each other.
The app lets the user quickly and easily configure a custom control panel which can communicate both ways with your Arduino.
The Arduino Blynk libraries can be installed and an example program compiled and uploaded a few minutes, with support for I/O port reading and writing already built-in. Online documentation describes how to expand the example code to do more specific things. Blynk is still under active development, meaning the documentation isn't always as detailed as one might like, that bugs are being fixed and occasional new ones appear, and new features are being developed.
I use it myself and teach other people how to, and I find it a really quick and easy to use platform for interactive remote control of my Arduino-based gadgets.
For example, I am using it right now to develop a ventilation controller for room- and window-fans. It will mix the room air in winter when the heat rises to the ceiling, and ventilate or just mix the room in summer depending on the floor, ceiling, and outdoor temperatures. It will report back to the smartphone which fans are on and off; allow me to turn any of them on or off; and display a history of the temperatures and fan states.

I believe the term you want to search on is "web scraping".  Assuming you are fine with people knowing the state of "things" in your home, you can simply leave the states up on your public web page.  That is, you click on a button on your web page and change the text from "shutter up" to "shutter down".  Mean while, your Arduino is "web scraping" the same page looking for "shutter" and acting on the next word "up" or "down".
In this blog, someone has posted his Arduino "web scrapping" code.  I have not tried it, so do some research before considering this particular solution.

Indeed it's web scraping !
Well, public people can access the states of my arduino's sensors right, first they have to know the site used to, the reals pages used to it (according on the fact that the website will be a food website fake pages). Just thinking that it gives so much more security isn't ? Connecting to your home @IP seems so unsafe, that anyone can access and even open doors...

Web scraping is for the case when you do not control the server, and have to extract the desired information from unstructured HTML. In this instance the OP controls the server. He can return the needed data in whatever format is easiest to digest for the Arduino. It would be silly to embed that data into an HTML document, only to have the Arduino remove all that crap through pattern matching.

Agreed, but web scraping is an easy concept.  And he may not have access to features like CGI scripts and scripting languages like PERL, ect on the web server computer.  Also, he may not have a dedicated home IP address.  So the web server (assumed located else where) may not be able to send information home (yes, there are dns look up services he could subscribe to to get around this).  He can look into all these things and more if he needs to.  But for getting started, I still think scraping is the easiest concept to grasp.

So, If I understand well and to sum up all this, I must, with my arduino, get the SOURCE CODE of the page (can it be in php :V and so it retrieves the html output from server ?), then look for datas to seek and update itself considering the values of the datas ?
You saying, that the easiest to control things in my home, would be to ssh the main that control the nodes ? Despite all the weakness it can has about security this is the easiest way ?
Tho my apologies again about my bad spelling, and thank you for your help

I understood you wanted to control things in your home with an Arduino using a web page far removed from your home.  I suggested you write a web page of which had text that changed through button presses.  Then to have your Arduino periodically read the web page using HTTP.  I did not say anything about a Secure SHell layer (SSH).  After all, what's to keep secret?  Anybody can view this web page.  Keep in mind there are many ways to do this.  And if you are that interested in security, you may find an Arduino insufficient.

Well, If someone wants to know if the cat still have food or if it's hotter than 25° inside he could do such gr8 things... wait..
Why do you say text change w/ button ? Mean button with sql request and text in php ?
Talking about SSH to know if, FOR YOU, It was the easiest way to finally do this ... Coz nothing seems to exist about web scrapping arduino or w/e, knowing the fact I suck at arduino I won't be able to do it on my own and CREATE it ^^

I'm sorry, I though you only wanted to control things in your house. If you want to send information from your house ... maybe you could use tftp and copy a small file of data from your arduino to the web server. Then serve up that data by reading that file on the web server and rendering a web page. But this requires you to store a password on the arduino which is a security risk which was something I was trying to avoid.

Evertime you give a way to solve my question about 'how to control sensor at home and know what  their values are' you just put another problem in, security tho both time, I said it, and say it again : I just want the easiest way for a newbie to set up this : Control sensor at home and know their states / values from far (through internet).
Thank you :D

From your comment of Jul 1st, I understand that you can program your
server in PHP. Then, and to expand on my own comments, I am only
recommending that, whatever Web API you design, you keep it as simple as
possible. For example, for telling the Arduino whether it should keep
the shutter open or closed, you could write something like this in PHP:
header('Content-Type: text/plain');

if (user_wants_shutter_open())
    echo "open";
else
    echo "close";

In particular, it makes absolutely no sense to write a PHP program that
generates an HTML document. Consider that the Arduino is a very low
powered platform: there is no point in having it process more than a
handful of bytes when you only want to communicate a single bit of
information. And you should know that there is really nothing wrong with
using HTTP to transport plain text (but you should use the header
Content-Type: text/plain). If you want to send a more complex set of
data, you could use something like text/tab-separated-values, or maybe
even application/json.
Concerning web scrapping, it is a solution to a specific problem, the
problem being that the server returns the information in a format that
is not very well suited for machine consumption. You do not have this
problem. Obviously, you could create the problem by having your PHP
return an HTML document, and then you could apply the solution. My point
is that it is better to avoid creating the problem in the first place:
just return the information in a format that is as easy to parse as
possible.


text:
Multiple sensor connection help
How would you connect multiple HC-SRO4 ultrasonic sensors to one arduino uno? As of now, I have a bunch of jumper cables, 3 u.s sensors, and one arduino uno board. How would one hook up 3 sensors? A schematic would be excellent!

It depends on what you want to do overall.
Using the HC-SR04 works roughly like this:

you generate a strobe on a pin for a minimum amount of time, and this strobe is understood by the sensor as "emit the ultrasound signal"
then you somehow (more on this later) measure how much time passed between your strobe and a change of level on another pin from the sensor - this is how the sensor notifies you that there was an echo and it has returned.
finally, you convert the time measured into distance, using a conversion algo (typically multiplying by a certain factor) that is specific to the sensor.

Mostly the problem revolves around point #2: how to measure the time elapsed between command (strobe) and answer (change of level).
You have various options, each with pros and cons:

busy looping: it's easy to implement, very straightforward and works right away. The problem is that your arduino will do just that.
polling: it's a less aggressive version of polling, where you check the values every now and then. It lets you do more, but the drawback is that in the worst case the line changes level right after you have checked it, so it will be noticed only at the following iteration. The period used for checking is the maximum error you will get.
GPIO interrupt driven: this is harder but lets your arduino do many other things, while not loosing precision (I'll detail it separately)
HW backed: the AVR on UNO has the ability to capture events: basically there is a timer running that will stop when it gets triggered by a certain event (ex: the change of pin level cause by the echo). It is very precise, but you are limited by the number of HW blocks available on the AVR (3 iirc).

Now about the sub-cases of the GPIO interrupt-driven solution:

EXT based: the ATMega328p present on the UNO has what are called external interrupt sources, which is a fancy way to say that if you configure correctly a pin, the processor will notice when the pin voltage level changes and do something about it (in your case, take a time measurement) - this is quite generic solution, but unfortunately it works only on 2 pins, so you are out of lack with your 3 sensors, unless you implement some scheme where you multiplex 2 or more sensors on only one pin.
Pin-change-interrupt based: on AVR most of the PINS are grouped in ports. Each port contains maximum 8 pins and is labelled with a letter (A, B, C, ..). The way this interrupt works is roughly like the EXT type, but with a catch: you will get an interrupt whenever any of the pins that you have enabled on a certain port will change. In your case you could allocate only one sensor on a certain port, so that it would be obvious that if you get an interrupt for that port, it will be because of that sensor.

So now you can see why I said "it depends". If all you want to do is to get the information about proximity, you can go with busy-looping/polling.
But if you decide later on to do more on the same arduino, be aware that you might have to come back to the implementation of the ultrasonic sensor.
Finally, there is a library for this, but its implementation will fall into one of the cases i mentioned before, so be aware that the same catch applies: at some point you might want to do something that conflicts with the library.
Other points worth mentioning, that you should consider in your design (at least experiment with them):

orientation of the sensors: will they interfere with each other?
timing: do you need/want to activate them all simultaneously or do you prefer to have them activated in sequence?


text:
PWM help (input changing duty cycle)
Is there a way to adjust the duty cycle (PWM) based upon input gained by a sensor. For example, if the sensor picks up a really high value, it would increase the duty cycle for an LED making it brighter. Can we also do this task without a potentiometer? Can all of this be done "hands-free" by the Arduino?

Yes, yes, and yes. Totally possible.

There is a simple project that can be done with a photo-resistor for an analog input, a light levels sensor circuit, and an LED for an output.
The software requirement is to have a loop with a delay that reads from the analog pin the photo-resistor is attached and use that value to set the Duty Cycle for the PWM output pin driving the LED illumination level.
You can then test by shading the photo-resistor from the ambient light (I used a sheet of paper rolled up into a tube and placed over the photo-resistor on the breadboard), putting it into darkness, and by using a flashlight to provide more light than ambient in order to test the range and watch the LED dim and brighten.
I have done this project with a Raspberry Pi, which required an MCP3008 Analog to Digital Converter to interface to the photo-resistor circuit since the Pi has only digital pins. Arduino has analog pins so the ADC is not necessary.
The project that I did with my Raspberry Pi is at URL: https://github.com/RichardChambers/raspberrypi/tree/master/project08 with C source code and a link to the manufacturer of the experiment kit I am using which has the details for the actual circuit. What I did was to make the LED illumination level track to the inverse of the value reported by the photo-resistor circuit. So when the light level was low as reported by the photo-resistor then I made the LED brighter.

The example at the bottom of this Arduino reference page does exactly that. If you want to change the way the value varies, you can just modify the variables in a loop or in whatever approach you prefer instead of analogread'ing it.
https://www.arduino.cc/en/Reference/AnalogWrite


text:
How much power can the Teensy 3.2 deliver to external components?
Can a teensy 3.2 deliver enough power to properly activate multiple servos by chance?

it can provide system voltage of 3.3V to other devices at up to 100mA

Is there anyway to boost it up to 5v?

I would just go with a 5v power supply.

No.  You should provide your own regulator or supply for the servos specified voltage.
This might be an original design, or an off-the-shelf "battery eliminator" intended for an R/C vehicle of similar needs.
Note that the teensy regulator's maximum input voltage is fairly low, and may be in the range of what more powerful servos expect, ie, you might be able to run the teensy regulator off of the servo supply.
Be sure to consider the possibility of brownouts - multiple active or stalled servos can consume a lot of power, and if your upstream supply is not "stiff" enough this can result in the voltage dropping low enough that control electronics misoperate or reset - granted that is less likely with the teensy than with a 5v MCU using a regulator with a higher voltage dropout.

If you are running servos from the same supply as the Teensy and the supply is not decoupled enough you could also encounter noise related issues that might affect other parts of your build. In any case, use capacitors to stabilize your power inputs if you are dealing with actuators.

Capacitors only cover very temporary demands - a stalled servo is a demand which can easily last longer than any practical capacitor could cover for.


text:
RFID tag "location identification"
Can an RFID tag be used to identify a room? For example, I walk into a room, and the RFID receiver tells me that I am in say, the living room. Would it be possible for a tag to ping back the signal from a distance of 10ft? Or is there a similar technology like RFID that can extend to a much greater range?

You could attach them to the doors. 10ft is way to much. RFID only works within a few inches. Something like iBeacon/Eddystone (Bluetooth) would perhaps be an alternative.

There are newer long range RFID solutions. You can do a google search on "Ultra Long-Range UHF Wireless RFID Sensors" for more information, but almost all of these systems are still proprietary (i.e. I'm not aware of any hobbyist breakout-boards based around UHF tags yet).
The Disney MagicBands are an exact use-case of your question: Their magic bands use a combination of 13MHz RFID tags, and a new UHF active tag (it requires a small battery). They use them to collect data on how people flow through their Walt Disney World facility.  What bathrooms see the most activity, and when, for example.  There is actually a pretty decent amount of information available about the technology used in the Disney Magicbands if you're curious about the technology.


text:
PCA9685: how "unset" PWM signal?
I use my Arduino with Adafruit PCA9685 servo controller. To set PWM signals I use the provided library: https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library
It allows easily set PMM signal and works good. But how can I "unset" PWM signal for a certain pin?
If a PWM siganl is active, the servo stucks on the current position and can't be moved by hand, but only by setting other pulse length. So I need to move servo and then "free" it.

I'm not really into servos... do they "release" when just the duty cycle is 0% or 100% (this can easily be done with your PCA9685)? If not, the only way is switching off the power supply for that servo.

Did you find a solution? I'm having the same problem.

You can try to send no "ON" time to your output pin on the PCA9685.
So, you start the "ON" at 0 and stop the "OFF" at 0.
void freeServo(uint8_t servoIdx)
{
  pwm.setPWM(servoIdx, 0, 0 );
}

Are your servo's control pins active high or active low?
From the library code at https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library/blob/d265f74fc0e66632e6dafc787c95b008f3245550/Adafruit_PWMServoDriver.cpp#L242  it looks like there are special on&off values of setPWM(pin,on,off) that turn the servo fully on or fully off, and how they work they depends on whether the servo pin is active high or active low.
unsigned byte idle = CertainPin;

servoController01.setPWM(idle, 0, 4096); // fully off Active high
// servoController01.setPWM(idle, 4096, 0); // fully off Active low

or with the better documented setPin():
servoController01.setPin(idle,0,false); // Active high
//servoController01.setPin(idle,0,true); // Active low

You could try changing the corresponding pin from output to input.
To be sure not to disturb other comfigurations you could do direct port manipulation.
void servo_off() {
  DDRD &= ~(1<<PD5);
}

void servo_on() {
  DDRD |= (1<<PD5);
}

This assumes you use pin PD5 for the pwm signal. Adjust the "D" in DDRD and PD5 so it matches the port in use as well as the pin number.
Of course, you need some additional user input like a button to trigger calls to those functions.

PCA9685 is controlled over I2C and the question is about the Adafruit library for the PCA9685 module

I got same problem, searched around but found no answer, so I looked into the source code and found that you simply have to set the angle of the servo to 'None' to stop sending PWM pulses to the servo. For example, if your servo uses channel 14 on the PCA9685 board:
kit.servo[14].angle = None

It sounds like you're talking about python, or something like it, and maybe some other library and not anything to do with the question.

Unluckily, AFAIK, the servo powers the motor even when the PWM signal is not applied. So "removing" the PWM is useless.
You will have to "turn off" the servo by removing the power. To do this, use a transistor (usually servos are more current-hungry than arduino can bear). When you want to "free" the servo, remove the power and it will be "free".

you are wrong
if I connect servo to my assembly it is "free" until I havent PWM set
aslo I can free all servos by sending reset command to PCA9685
but my task is to "free" just one particular servo: there is the problem


text:
Why can only some digital ports output PWM and the others not?
If it matters, I'm talking about the arduino uno v3.

Six out of twenty ain't bad. Plus you can do PWM in software, to an extent, like the Tone library does.

Check out the ATMega328p datasheet: each of the 3 timer/counter blocks can generate PWM (2 PWM signals per timer) and on top of that, typically Timer1 (16 bits) is used by the OS/scheduler/whatever, unless you are really running on bare metal.
It's a limitation, but so is everything else.
If you do not like it, you can always choose a different microcontroller, either AVR or something else.
Certain models might  be designed to have more units of a specific type than you would find on generic microcontrollers.

on top of that, typically Timer1 (16 bits) is used by the OS/scheduler - what OS/scheduler are you referring to?

ChibiOS, for example, uses Timer1. Some time ago I went through various options available in terms of OS/RTOS/scheduler for ARduino/AVR and, as far as I can remember, Timer1 was the favourite choice.

That is one of the hardware features/functions of the microprocessor.  It is like a bag of candy when you eat the last piece there is no more left.  You can do software PWM but that can use a lot of compute power.  You can also get PWM peripheral devices you can connect to it.

After all, it's a cost issue.
Not only of the Arduino/Atmel, but any microcontroller.
The outputs of the PWM unit (which has a limited number of PWM channels) have to be routed to the output pins.
This routing is basically fix, because the silicon mask is fix.
However, to add some flexibility, most controllers allow a limited configuration of this routing by adding some internal switches which can be accessed by writing to the specific registers.
But any additional routing capabilities means more of those internal switches, which results in more size -> more silicon -> more expensive.
Therefore the micro designers say - for example - "OK, it's enough to be able to output x of the y available PWM channels at every edge of the micro", and the poor PCB designer has to cope with what he gets.
Using an FPGA instead of a microcontroller you are really free to setup your function to pin routing - but look at the price of an FPGA ;-)


text:
Looking for a game application oriented display for Arduino Mega
I was using displays with serial communication (SPI), but sending bytes to draw a tile-based picture was way too slow so I'd like find one with a parallel port, enough fast bandwidth to receive fast pictures at a speed at least 10FPS (but I'd like 50FPS or 60FPS) from Arduino Mega (ATMEGA2560) and which has a library compatible with the Arduino's C++ compiler.
I think I've seen somewhere how to connect a display onto the XMEM pins of the Mega and send bytes like this:
*(0x12)=0x34 // Sends 0x1234

However, I couldn't find where to buy that specific one.
I was searching on eBay, but only found displays of unsupported drivers or drivers with broken links that I couldn't download, and displays that are ridiculously large like a shovel!
The resolution it needs to have is minimum 128x64, aspect ratio must be X:Y where X is greater than Y (unless it's possible to send bytes sideways while the screen is physically placed in a different orientation on the PCB).
It must be a touch display sensitive on anything (like Nintendo DSi when drawing Flipnotes).
It should be either:

Monochrome
Color display with MS Paint colors if it has equal to or less than 256 colors
Color display with 16-bit color input mode if it has a lot of colors

It should be no bigger than 2.5" because this is for a little handheld console.
If anyone knows where to buy it, please comment.
Thank you for your time.

I'd suggest, if you haven't done it already, to take a look at what is supported by uGFX.
If you find any HW meeting your needs, you can at least be sure that it is supported.

I was using displays with serial communication (SPI)  ...

Personally I regards serial and SPI as different things:

Serial
SPI

SPI is somewhat faster than serial.

... sending bytes to draw a tile-based picture was way too slow ...

How slow was it? What was your target speed?

The resolution it needs to have is minimum 128x64 ... It should be no bigger than 2.5"

Something like 2.2" 18-bit color TFT LCD display ?

fast bandwidth to receive fast pictures at a speed at least 10FPS ...

See Toorum's Quest II - Retro video game and console
That guy made a sideways scrolling game outputting to video with a display resolution of 104x80 with 256 colors. He also had sound generation and managed input from a NES controller.
See video of it in operation on YouTube.

When I send bytes by a for loop to paint an 8x8 tile from top to bottom, the picture appears in a quarter of a second which isn't near 10FPS. Plus, the console would need to have enough speed to not just blit the image, but have some of its own processing like feeding VLSI chip with MP3 music, RTOS processes, game engine,...
I've seen many people do the NTSC blitting, but I'm more interested in LCDs where I'm not timely challenged and can respond to interrupts in the middle of blitting the image.

Also, that TFT LCD display you linked uses SPI and I need one with parallel communication like those character displays.

When I send bytes by a for loop to paint an 8x8 tile from top to bottom, the picture appears in a quarter of a second - with what device? And what code? Something is wrong if it takes 250 ms to draw 64 pixels.

Not 64 pixels. WHOLE screen! I don't have the code right now and I think I've deleted it. The code writes from top to bottom like if it was blitting a tile-based screen layout, but just that one tile. And that's how much it takes. Also, I've even used manual port register manipulation rather than using the PutPixel function in order to speed up, but it looks like it's still too slow.

Wow, I'm surprised at that game and how much effort was put (they could have done without a custom board and still call it a great use of an Arduino). It ended up so professional, really shows love for the craft.


text:
Need to power Arduino Mega 2560 with 3.3V
I found an LCD for my Arduino Mega 2560 that's parallel (I like that, I don't like SPI), but it works at 3.3V and isn't 5V tolerant. That's why I'd need to use level shifters, but that would use too much space and I'd like to power the microcontroller with 3.3V. But that would cause problems because the USART communication is set to be on 5V and that can't be changed.
Is there a way to power my Arduino at 3.3V? Is there an alternative Arduino for that?
Also, if there is, I'd need to have a 16MHz crystal on it. I know it's overclocking, but Gamebuino works at 16MHz on 3.3V and I would like to do the same.

Maybe a Due would be more suitable for you...?

You can use pro mini 3.3v and one shift register. It is not SPI :)

Some of the smaller boards may not have enough I/Os.  Typically the ARM-based boards are native 3.3v, with more memory and faster too.  Level shifting the serial shouldn't be too hard.

It must be ATMEGA2560 because of the pin count and XMEM for the display. My project is to make an 8-bit AVR game console with most RAM as possible and a fast LCD. It's something like those NTSC projects, but mine is a handheld console. If I have to, I can work in full ASM.

SPI into a shift-register is pretty fast. If space is a premium I would have thought that the Mega2560 board was a little large.

Have you considered maybe using the Iteaduino MEGA2560?
The Iteaduino MEGA2560
uses the same ATmega2560 processor as the Arduino Mega 2560,
but is physically much smaller, the size of a Arduino UNO.
It has a switch to run the ATmega2560 at 3.3 V, so its I/O pins can be directly connected to 3.3 V modules.
It breaks out all the GPIO pins of the ATmega2560,
so it actually has more I/O on its connectors than the Arduino Mega 2560.
If I'm reading this right, the Iteaduino schematics and a typical Iteaduino features list
seems to say it already has a 16 MHz crystal.

Can I connect an external 16MHz crystal there?

Have you considered maybe using the "Sparkfun Mega Pro 3.3V" plus a "SparkFun FTDI Basic Breakout - 3.3V" ?
It uses the same ATmega2560 processor and has the same I/O arrangement as the Arduino Mega 2560, but it runs off 3.3 V.
It doesn't have the 16 MHz crystal you wanted, but if you really insist on overclocking, perhaps you could replace its 8MHz resonator with a 16 MHz crystal?

I don't see where the resonator is. I don't see the pin to connect it to either. Can you show me?

Does that doodle on a photo answer your question?

I see. I hope that I won't damage it or the MCU while unsoldering. What kind of a soldering device should be used there?

Wide chisel tip soldering iron with a big blob of solder to take it off the board. Soldering braid to clean up the pads. Narrow fine-tip soldering iron to attach new parts to the pads. A better place to ask questions about soldering techniques: http://electronics.stackexchange.com/questions/tagged/soldering .

Have you considered maybe using the Inhaos Buono Mega 2560 (see a), also called the Inhaos Mega2560?
As far as I can tell, it is pretty much identical hardware as the Arduino Mega 2560 -- including the ATmega2560 processor -- except it has a selector to run the ATmega2560 at 3.3 V, so its I/O pins can be directly connected to 3.3 V modules.
Like many websites, every page on the Inhaos website http://www.inhaos.com/ has a "Contact Us" link at the top of each page. Click that link to get a list of several ways to contact the company.

This one is the best, but unfortunately, it's no longer for sale. Is there a way to buy it somewhere or to contact the company?

As far as I can tell, the "Inhaos Mega2560" is still for sale. I added more links to this answer; does that answer your question?

Have you considered maybe using the ElecFreaks Freaduino MEGA2560 ?
It has an identical I/O arrangement and dimensions as the Arduino Mega 2560 -- including the ATmega2560 processor. It has a selector to run the ATmega2560 at 3.3 V, so its I/O pins can be directly connected to 3.3 V modules.
The voltage regulators and reset switch position are better than the Arduino Mega 2560.

What about a 3.3v Arduino Pro Mini, you'll need to solder headers but that's not too onerous. See here Arduino pro Mini or even cheaper from eBay

Is there a 2560 version of that?

Not that I'm aware of. What's the 2560 specific functionality that you require?

XMEM access to external RAM and the display for super speed. It's for my 8-bit handheld console project with maximum RAM and fastest color display.


text:
Is there a simple (permissive license) Leonardo driver for a USB-to-USART bridge to substitute an FTDI chip?
I'm making an ESP32 development board and I'm thinking about putting an Arduino Leonardo chip between the USB port and the ESP32's USART pins to act as a USB/USART converter instead of the FTDI chip so that I can program the ESP32 through a USB serial port like any other Arduino board.
Is there a library/sketch licensed under a permissive license (MIT, BSD, Apache, etc.) which can make the Leonardo chip act as a HID Serial Port device which has a device name I want for easy identification in Device Manager and which requires no special driver installation in Windows and Linux once plugged into the computer?
Thank you for your time.

you should do a better research before asking. "Leonardo chip"? "HID Serial port"? why do you wan't to use a 32u4 as USB-to-TTL-Serial? only Uno and Mega use an Atmel MCU for USB. most boards have FTDI or CH340 USB chips

@Juraj I use a small PIC32MX chip as a USB interface on my boards. I like the flexibility that creating your own interface gives you. For example, activating DTR on my system automatically creates a reset pulse, instead of just holding the line low.

The reason I'm using 32U4 is because I'd also like to use it as a virtual HID CD drive with a virtual CD providing an exe application for the end user to be able to upload firmware, communicate with the existing firmware, etc.. And most importantly, it's programmable as I want and all the code I add upon it is mine.

Why not write your own?
First off, you'll want to create your own custom board definition. To do that, find the boards.txt file in the AVR core of your installation. Then find the block of entries that starts leonardo. and copy the whole block. Change the leonardo to a name of your choosing.
Then change the .name entry to give your board a new name in the IDE.
Finally look for the (renamed) entries:
leonardo.build.vid=0x2341
leonardo.build.pid=0x8036
leonardo.build.usb_product="Arduino Leonardo"

Of course the leonardo will be whatever you changed them to.  You can now give your board a new VID and PID to uniquely identify them - and also change the usb_product to name your board.
You can also add a myboard.build.usb_manufacturer="..." entry to change the manufacturer from the default of Arduino.
Now you have a board definition that identifies your board as what you want it to be.  So now just write a sketch that passes through the serial between USB and UART, and also handles the DTR and RTS signals to be able to enter flash mode on the ESP32 (hint: use Serial.dtr() and Serial.rts() to check the status of those signals).

That's quite a comprehensive response. Thank you! However, I still don't understand where's the HID Serial Port driver library (under a permissive license) for me to include in my C++ project and which functions/classes I need to use to talk to the USB side of things. I understand the Serial library, but that's for the USART between the Leonardo and the ESP32. I need the virtual USART part. Could you please append that to your answer?

It's already there. It's in the Arduino core. There is no library needed.

Oh, so there's Serial and Serial1? Is that correct?

Yes. Serial is the USB, and Serial1 is the TX/RX pins.