Arduino serial monitor gives question marks and boxes with my output - c++

I am writing a program to encrypt the given input and send the cipher text over LoRa waves, but I seem to be stuck in this step.
I am using a Heltec LoRa ESP32 and have included the mbedtls library for the AES functions.
#include "mbedtls/aes.h"
#include "heltec.h"
#include <SPI.h>
#define BAND 433E6 //setting the LoRa bands to 433 mhz
mbedtls_aes_context aes;
int counter = 0;
unsigned char key[32] = "key"; // 256 bit - AES = 32 bytes for key
unsigned char iv[16];
unsigned char input [128] = "given AES plain text";
unsigned char output[128];
size_t input_len = 40;
size_t output_len = 0;
void setup() {
Heltec.begin(true /*DisplayEnable Enable*/, true /*Heltec.Heltec.Heltec.LoRa Disable*/, true /*Serial Enable*/, true /*PABOOST Enable*/, BAND /*long BAND*/);
//setup code to enable LoRa
Serial.begin(115200); //establishing serial communication with esp32 and pc
mbedtls_aes_setkey_enc( &aes, key, 256 );
mbedtls_aes_crypt_cbc( &aes, MBEDTLS_AES_ENCRYPT, 48, iv, input, output ); // AES function from mbedtls library,
}
void loop() {
Serial.print("Sending packet: ");
Serial.println(counter);
Serial.println((char*)output); //here is the issue
// send packet
LoRa.beginPacket();
LoRa.print((char*)output);
LoRa.print(counter);
LoRa.endPacket();
counter++;
delay(5000);
}
the output gives a cipher text containing (Im assuming) special characters and when I look at the Arduino serial monitor it shows bunch of reverse question marks and boxes with normal characters.
Serial.println((char*)output);
Is there a print method that can show these special characters in the Arduino IDE?

Related

Arduino CANBUS MCP2515 Extended ID Receive Filter Problem

I would like to read CANBUS output of a device, but instead of reading every message, I need to filter out all messages except "0x18DAF938" message.
I am using Cory J. Fowler's library.
I changed Extended_MaskFilter example code as below but still no success:
#include <mcp_can.h>
#include <SPI.h>
long unsigned int rxId;
unsigned char len = 0;
unsigned char rxBuf[8];
MCP_CAN CAN0(53); // Set CS to pin 10
void setup()
{
Serial.begin(115200);
if(CAN0.begin(MCP_STDEXT, CAN_500KBPS, MCP_8MHZ) == CAN_OK) Serial.print("MCP2515 Init Okay!!\r\n");
else Serial.print("MCP2515 Init Failed!!\r\n");
pinMode(2, INPUT); // Setting pin 2 for /INT input
CAN0.init_Mask(0,1,0xFFFFFFFF); // Init first mask...
CAN0.init_Filt(0,1,0x18DAF938); // Init first filter...
Serial.println("MCP2515 Library Mask & Filter Example...");
CAN0.setMode(MCP_NORMAL); // Change to normal mode to allow messages to be transmitted
}
void loop()
{
if(!digitalRead(2)) // If pin 2 is low, read receive buffer
{
CAN0.readMsgBuf(&rxId, &len, rxBuf); // Read data: len = data length, buf = data byte(s)
Serial.print("ID: ");
Serial.print(rxId, HEX);
Serial.print(" Data: ");
for(int i = 0; i<len; i++) // Print each byte of the data
{
if(rxBuf[i] < 0x10) // If data byte is less than 0x10, add a leading zero
{
Serial.print("0");
}
Serial.print(rxBuf[i], HEX);
Serial.print(" ");
}
Serial.println();
}
}
I am using Arduino Mega2560 and NiRen MCP2515 module.
Help would be appreciated. Thanks.

communicating state of a potentiometer with a second arduino board

I am trying to get an arduino board to read the state of a potentiometer which is connected to a master arduino board, without connecting the potentiometer to the second board with physical cables
I have tried using Wire.write and Wire.read to just transfer the one value.
The master arduino code:
#include <Wire.h>
const int dial = A0;
int reading = 0;
void setup() {
pinMode(dial, INPUT);
Wire.begin();
}
void loop() {
reading = analogRead(dial);
Wire.beginTransmission(9);
Wire.write(reading);
Wire.endTransmission();
}
The slave arduino code:
#include <Wire.h>
int reading = 0;
void setup() {
Wire.begin(9);
Serial.begin(9600);
Wire.onReceive(receiveEvent);
}
void receiveEvent(int bytes) {
reading = Wire.read();
}
void loop() {
Serial.println(reading);
}
When I read the Serial Monitor, the potentiometer or "reading" in the slave arduino limits at 255 (I don't know why) in 6 intervals (goes from 0 to 255, then drops to 0 and does that 6 times). I expect it to do the full range of the potentiometer to cap out at 1023.
Your ADC is 10bit and won’t fit in a byte. (Wire.write(value) sends value as a single byte). You need to send reading in 2 bytes. Here is how to make 2 bytes.
byte data1 = highByte(reading);
byte data2 = lowByte(reading);
On receiving side, reconstruct an int this way.
byte data1 = Wire.read();
byte data2 = Wire.read();
reading = int(data1) << 8 | data2;

ser.write() function in pyserial

I am trying to send the byte array of an image file to the Arduino with the pyserial library. And I am receiving the data byte by byte in the Arduino. But it seems I am unable to retrieve the bytes on the Arduino. For example it sends a string of '255' Arduino receives the byte as '2'.
Python code:
import serial
ser = serial.Serial('/dev/ttyUSB0', 115200, bytesize=8, timeout=0, parity=serial.PARITY_EVEN, rtscts=1)
f = open('image.jpg','rb')
l = f.read()
b = bytearray(l)
for i in range(1,len(b)):
ser.write(str(b[i-1]))
ser.flush()
ser.close()
Arduino code:
char buffer ; // for incoming serial data
int length = 1;
void setup() {
Serial.begin(115200); // opens serial port, sets data rate to 9600 bps
}
void loop() {
Serial.readBytes(&buffer, length) ;
Serial.println(buffer);
}
Your Python code sends numbers as ASCII strings, instead of sending bytes (which is what your Arduino code is expecting...). Instead, do:
for i in range(1,len(b)):
ser.write(b[i-1])

Arduino does not support messages larger than 65535 characters using websocket protocol?

I'm using the following Arduino websocket library, I had a problem when trying to send messages over than 65535 characters, I got handshake fail error.
As long as the message doesn't exceeds this length, it worked perfectly
There's a note on the main web page of the library that states:
Because of limitations of the current Arduino platform (Uno at the time of this writing),
this library does not support messages larger than 65535 characters.
In addition, this library only supports single-frame text frames.
It currently does not recognize continuation frames, binary frames, or ping/pong frames.
In the client header file named WebSocketClient.h there's the following comment:
// Don't allow the client to send big frames of data. This will flood the arduino memory and might even crash it.
#ifndef MAX_FRAME_LENGTH
#define MAX_FRAME_LENGTH 256
#endif
I'm using this old library because it is the only one worked for me on my Arduino WIFI shield, I couldn't find other libraries that support WiFi shield since most of the webscket libraries are written for Arduino Eathernet Shield support, which I don't have.
My Arduino Code is
/*DS18 Libs*/
#include <dht.h>
#include <OneWire.h>
#include <DallasTemperature.h>
/*Websocket Libs*/
#include <WebSocketServer.h>
#include <WebSocketClient.h>
#include <sha1.h>
#include <MD5.h>
#include <global.h>
#include <Base64.h>
#include <SPI.h>
#include <WiFiUdp.h>
#include <WiFiServer.h>
#include <WiFiClient.h>
#include <WiFi.h>
#include <string.h>
char ssid[] = "AMM";
char pass[] = "027274792";
int status = WL_IDLE_STATUS;
IPAddress server(192, 168, 1, 3);
WiFiClient WiFiclient;
WebSocketClient WSclient;
// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
//Humidture
dht DHT;
#define DHT11_PIN 4
void setup()
{
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
//check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while (true);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
}
// you're connected now, so print out the data:
Serial.print("You're connected to the network");
/* Connect to the websocket server*/
if (WiFiclient.connect(server, 8080)) {
Serial.println("Connected");
}
else {
Serial.println("Connection failed.");
while (1) {
// Hang on failure
}
}
// Handshake with the server
WSclient.path = "/MyServer/endpoint/testtest/device/d6220ae7-caa9-48b5-92db-630c4c296ec4";
WSclient.host = "192.168.1.3:8080";
if (WSclient.handshake(WiFiclient)) {
Serial.println("Handshake successful");
}
else {
Serial.println("Handshake failed.");
while (1) {
// Hang on failure
}
}
/*DS18*/
sensors.begin();
}
void loop()
{
WSclient.sendData("{\"service_code\":\"89c4da72-a561-47db-bf62-8e63f8c4bbf0\",\"data\":[" + getHumidtureValue() + "],\"service_type\":\"TemperatureHumidityAnalysis\"}");
WSclient.sendData("{\"service_code\":\"bdc0f984-6550-4712-881f-b09071da5a73\",\"data\":" + getCBodyTempretureValue() + ",\"service_type\":\"TemperatureGaugeMonitor\"}");
//line-3 commented WSclient.sendData("{\"service_code\":\"8c212432-a86e-4c18-a956-9dc0dbb648d4\",\"data\":[" + getHumidtureValue() + "],\"service_type\":\"HumidityGaugeMonitor\"}");
}
String getCBodyTempretureValue()
{
sensors.requestTemperatures(); // Send the command to get temperatures
char charVal[10];
return dtostrf(sensors.getTempCByIndex(0), 4, 2, charVal);
}
String getHumidtureValue()
{
String str = "";
for (int i = 0; i < 2; i++)
{
int chk = DHT.read11(DHT11_PIN);
switch (chk)
{
case DHTLIB_OK:
Serial.println("OK,\t");
break;
case DHTLIB_ERROR_CHECKSUM:
Serial.println("Checksum error,\t");
break;
case DHTLIB_ERROR_TIMEOUT:
Serial.println("Time out error,\t");
break;
default:
Serial.println("Unknown error,\t");
break;
}
char charVal[10];
double tempF = (DHT.temperature * 9) / 5 + 32;
str = dtostrf(tempF, 3, 1, charVal);
str = str + "," + dtostrf(DHT.humidity, 3, 1, charVal);
Serial.println(str);
delay(200);
}
return str;
}
The code above works perfectly, when I uncomment the third send statement in the loop function, I got the handshake failed error.
-Is it safe to modify the value of MAX_FRAME_LENGTH for the new versions of Arduino board, considering this library is an old one?
-Is there any other libraries better than this one that can support websocket on WiFi shield?
Any solution or idea will appreciated.
Thanks in advance.
Without having looked at the code of the library it is likely not safe to change the max frame length, because the websocket protocol encodes the payload length differently depending on how long it is:
Payload length: 7 bits, 7+16 bits, or 7+64 bits.
The length of the "Payload data", in bytes: if 0-125, that is the payload length. If 126, the following 2 bytes interpreted as a 16-bit unsigned integer are the payload length. If 127, the following 8 bytes interpreted as a 64-bit unsigned integer (the most significant bit MUST be 0) are the payload length.
When the library says it doesn't support payload length above 65535 byte, it likely means that it has no implementation for the 64-bit length encoding.
After many trials and many times the program behaves very strangely, which drives me crazy, I found the problem is that I'm using too much strings in my program which makes the Arduino-Uno easily runs out of RAM.
The main reason I got handshake failed error is that the Arduino cannot read the "Sec-WebSocket-Accept" header of the handshake response message (as many other headers also) which I made sure that they are sent, by debugging code on the server.
Actually this problem and many other strange behaviors keep happening until I reduce the amount of the memory used during program run.

Programming serial port arduino with Visual C++

I want to read analog sensor from arduino to my pc.
Arduino program are:
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
}
void loop() {
char request[1];
if(Serial.available()){
request[0]=Serial.read();
Serial.print(analogRead(atoi(request)));
Serial.print("\n\r");
};
delay(2);
}
and my visual C++
#include <windows.h>
#include "stdafx.h"
#include "SerialClass.h"
char buffer[20];
char buf0[200];
int _tmain(int argc, _TCHAR* argv[])
{
Serial oSerial("COM6:");
while(1){
sprintf_s(buffer,"0");
oSerial.WriteData(buffer,1);
Sleep(1000);
oSerial.ReadData(buf0,4);
printf("Sensor 0: %s \n",buf0);
Sleep(1000); }
}
and result of my program is not stable, I put 5V in input0, so it must be 1023:
sensor 0 :
sensor 0 : 10230
sensor 0:
100
sensor 0: 23
0
sensor 0: 10230
I try in my arduino with serial monitor the program is working. so may be the problem is in the c++ program
any one have idea?
I believe the problem is caused because your PC is looking for 4 chars and the Arduino is sending 3-6 chars per request.
I would recommend you receive chars into your buffer until you receive the carriage return (\r) sent by the Arduino. Then you can output the complete string. You will need to handle the control characters.
Untested example:
Replace
oSerial.ReadData(buf0,4);
With
int x=0;
int char_rev;
while(buf0[x]!='\r') {
char_rev = oSerial.ReadData(buf0[x],1);
if (char_rev==1) {
x++;
}
}
buf0[x]=0;