Visual Studio 2010 Arduino serial communication - winapi

I am using OpenCV in Visual Studio 2010 to track an object, and I am trying to send a value to the Arduino to rotate servos attached to the camera. I am using an Arduino Uno. I have completed the C++ code that tracks the object and determines which direction the camera needs to be rotated, but I am having trouble sending this data to the Arduino. I am currently trying to use an RS-232 cable for this. I am using a Type-B USB cable to program my Arduino and an RS-232 to try to send the data from Visual Studio to the Arduino. Here is my code for the Visual Studio serial communication:
int portspeed(int centerpix, int xmid)
{HANDLE hDevice = CreateFile(L"COM5",GENERIC_READ | GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,NULL,OPEN_EXISTING,0,0);
DCB lpTest;
GetCommState(hDevice,&lpTest);
lpTest.BaudRate = CBR_9600;
lpTest.ByteSize = 8;
lpTest.Parity = NOPARITY;
lpTest.StopBits = ONESTOPBIT;
SetCommState(hDevice,&lpTest);
DWORD btsIO;
if (centerpix<xmid)
{
char test[] = "2";
WriteFile(hDevice,test,strlen(test),&btsIO,NULL);
cout << "Turn right " << test << endl;
}
else
{
char test[] = "3";
WriteFile(hDevice,test,strlen(test),&btsIO,NULL);
cout << "Turn left " << test << endl;
}
return 0;
}
On the Arduino code side I have this, which I am using to attempt to light two different LEDS to see if the program is able to correctly communicate which direction it needs to rotate:
int incomingByte = 0; // For incoming serial data
void setup()
{
Serial.begin(9600); // Opens serial port, sets data rate to 9600 bit/s
}
void loop()
{
// Send data only when you receive data:
if (Serial.available() > 0)
{
incomingByte = Serial.read();
if (incomingByte==50) //if =2
analogWrite(9,100);
else
analogWrite(9,0);
if (incomingByte==51) //if =3
analogWrite(10,50);
else analogWrite(10,0);
delay(3000);
}
else
analogWrite(9,255);
}
My interpretation is that I need to start the C++ program (which continuously sends the data over the serial communication), and then attach the TX pin from the RS-232 into the RX pin (digital 0) on the Arduino. When I try to upload the program to the Arduino I am given an error,
avrdude: stk500_getsync(): not in sync: resp=0x00
This only occurs when I have a wire going into the RX pin, even if this wire is not connected to anything. I believe that this error occurs because the RX is looking for an input with a baud rate of 9600, but it still gives me this error when the C++ program is running and sending the data with a rate of 9600.
How can I send a value from a Visual Studio project doing real time image processing on a laptop to an Arduino via serial communication?

Speaking as someone with limited Win32 experience (more of a .NET guy, really), I think your problem may be in write buffering.
By default, writes to a file or port are buffered in memory. Perhaps the write is never getting sent to the port as you are never closing the file handle nor calling [FlushFileBuffers][3].
Try adding this prior to return 0;:
//After a time, sensitive write
FlushFileBuffers(hDevice);
//or, more properly for the end of the program.
CloseHandle(hDevice);

Related

How to send AT commands to ESP32 LilyGo-T-Call-SIM800?

I've been working with a LilyGo-TCall-SIM800 module for several days, trying to get out of a dead end.
I have tried an example from "random nerd tutorials" which works correctly. The module connects to the internet and can send data to the cloud.
I have the problem to send AT commands to the SIM800L chip integrated in the module. I can't get the chip to react back.
I have tried using Serial1 and Serial2. I have also tried configuring the RX and TX transmission pins, and I have tried with different baudrates. Always with negative results... when sending the "AT\r" command to the SIM800L, it should return "OK". But it never does.
I have simplified the code as much as possible to minimize errors:
/*
Name: TestAT.ino
Created: 08/12/2022 23:15:28
Author: user
*/
// Set serial for debug console (to the Serial Monitor, speed 115200)
#define SerialMon Serial
// Comunications between ESP32 and SIM800L
#define SerialAT Serial1
//Comunications between ESP32 ans SIM800L go thought TX and RX pins on Serial1 Port
#define MODEM_RX1 16
#define MODEM_TX1 17
void setup() {
// Set console baud rate
SerialMon.begin(115200);
delay(1000);
//Set SerialAT baud rate
SerialAT.begin(38400, SERIAL_8N1, MODEM_RX1, MODEM_TX1);
//Set timeLimit for SerialAT reads
SerialAT.setTimeout(2000);
}
void loop() {
String returned = "";
char ATcommand[] = { 'A','T','\r' };
SerialAT.print(ATcommand);
delay(1000);
returned = SerialAT.readString();
SerialMon.print(millis());
SerialMon.print(" - ");
SerialMon.print(ATcommand);
SerialMon.print(" - SerialAT returned:");
SerialMon.println(returned);
}
Anybody can help me out on this? Any idea or sugestion?
Thanks in advance

UART program for PIC18f65k40

I'm trying to program my MCU in mickroc still I do not get a output.
Is there any difference between PIC18f65k40 and PIC18f65k22 in terms of initiating uart transmission? Whether there is any need to initiate or disable any special registers in PIC18f65k40?
In mikroc software there present a library for uart so I just copied the program from mickroe website and add my transmitter and receiver pins(RX4PPS = 0x11; and TX4PPS = 0x10;)in program by configuring portc as output but my circuit does not work.
char i ;
void main()
{
TRISC = 0b00000000;// making port as output
RX4PPS = 0x11;
TX4PPS = 0x10;
UART4_Init(9600); // Initialize USART module
// (8 bit, 9600 baud rate, no parity bit...)
delay_ms(500);
UART4_Write_Text("Hello world!");
UART4_Write(13); // Start a new line
UART4_Write(10);
UART4_Write_Text("PIC18F65K40 UART example");
UART4_Write(13); // Start a new line
UART4_Write(10);
while (1) {
if (UART4_Data_Ready()) { // If data has been received
i = UART4_Read(); // read it
UART4_Write(i); // and send it back
}
}
}
The PIC18F65k22 has only 2 UARTs and you are working with UART4. I guess the library don't support the controller. Better write the code on your own. There are some examples in the datasheet.

Using Ultrasonic sensor HC-SR04 and Gps (neogps 6m) together on arduino uno

I am trying to read data from both the sensor and the gps (one by one is ok). The sensors work well individually but the Ultrasonic sensor does not give any output. I am new to arduino so i just mixed the codes from the two examples using NewPing Library and TinyGPS libraries. Here is the code. Please suggest what additions need to be made to the code to make both devices work together.
/*********************
*10 to GPS Module TX*
*09 to GPS Module RX*
*********************/
// 1.TESTED USING LED
// 2. added ultrasound libraries
#include <NewPing.h>
#define TRIGGER_PIN 5 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 4 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 400 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
#include <SoftwareSerial.h>
#include <TinyGPS.h>
SoftwareSerial mySerial(10, 11);
TinyGPS gps;
float gpsdump(TinyGPS &gps);
void setup()
{
// Oploen serial communications and wait for port to open:
Serial.begin(9600);
// set the data rate for the SoftwareSerial port
mySerial.begin(9600);
delay(1000);
}
void loop() // run over and over
{
bool newdata = false;
unsigned long start = millis();
// Every 5 seconds we print an update
while (millis() - start < 5000)
{
if (mySerial.available())
{
char c = mySerial.read();
//Serial.print(c); // uncomment to see raw GPS data
if (gps.encode(c))
{
newdata = true;
break; // uncomment to print new data immediately!
}
}
}
if (newdata)
{
Serial.println("Acquired Data");
Serial.println("-------------");
gpsdump(gps);
Serial.println("-------------");
Serial.println();
}
}
float gpsdump(TinyGPS &gps)
{
// On Arduino, GPS characters may be lost during lengthy Serial.print()
// On Teensy, Serial prints to USB, which has large output buffering and
// runs very fast, so it's not necessary to worry about missing 4800
// baud GPS characters.
Serial.println("speed");
Serial.println(gps.f_speed_kmph()) ;
Serial.print(sonar.ping_cm());
;
}
The main problems:
You cannot wait 5 seconds without processing the characters. The Arduino receive buffer only has room for 64 characters. The GPS device could have sent 5000 characters during that time, so most of them will get dropped. This prevents the GPS library from ever parsing a complete sentence.
A ping will interfere with software serial ports. You will have to wait for the GPS quiet time to do the ping. Otherwise, the ping process will cause characters to be lost.
Other problems:
You are printing the speed value even though it may not be valid. If you are not moving, or you do not have good satellite reception, the GPS device may not provide a speed.
The Arduino millis() clock will not be synchronized with the GPS clock. You could use the GPS updates as an exact 1-second clock. Simply count 5 fixes as they arrive, and this will mean that 5 seconds have elapsed.
You should use a different serial port and/or library.
This answer describes the various choices: HardwareSerial (i.e. Serial on pins 0 & 1), AltSoftSerial (8 & 9 on an UNO) or NeoSWSerial (any two pins).
Here is a NeoGPS version of your sketch that addresses these issues:
/*********************
*10 to GPS Module TX*
*09 to GPS Module RX*
*********************/
// 1.TESTED USING LED
// 2. added ultrasound libraries
#include <NewPing.h>
#define TRIGGER_PIN 5 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 4 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 400 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
#include <NeoSWSerial.h>
#include <NMEAGPS.h>
NeoSWSerial gpsPort(10, 11);
NMEAGPS gps; // the parser
gps_fix fix; // all the parsed values from GPS
uint8_t fixCount = 0; // a one-second "clock"
float gpsdump();
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(9600);
// set the data rate for the SoftwareSerial port
gpsPort.begin(9600);
delay(1000);
}
void loop() // run over and over
{
// Check for available GPS characters and parse them
if (gps.available( gpsPort ))
{
// Once per second, a complete fix structure is ready.
fix = gps.read();
fixCount++;
// The GPS device is going to be quiet for a while,
// *now* is a good time to do a ping.
Serial.print( "ping " );
Serial.println( sonar.ping_cm() );
// Every 5 seconds we print an update
if (fixCount >= 5)
{
fixCount = 0; // reset counter
Serial.println("Acquired Data");
Serial.println("-------------");
gpsdump();
Serial.println("-------------");
Serial.println();
}
}
}
float gpsdump()
{
// On Arduino, GPS characters may be lost during lengthy Serial.print()
// On Teensy, Serial prints to USB, which has large output buffering and
// runs very fast, so it's not necessary to worry about missing 4800
// baud GPS characters.
Serial.println("speed ");
if (fix.valid.speed)
Serial.println( fix.speed_kph() );
}
If you want to try it, NeoGPS, AltSoftSerial and NeoSWSerial are available from the IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries. NeoGPS is smaller, faster, more reliable and more accurate than all other libraries.
Even if you don't use it, there are many suggestions on the Installation and Troubleshooting pages.

can't pair mac and arduino fio with bluetooth bee

I can't get my arduino fio with bluetooth bee paired with my mac. I got my application working with a different board (arduino uno) and USB connection. The code I'm uploading to my arduino fio is below:
#include <SoftwareSerial.h>
SoftwareSerial softSerial(2, 3); // RX, TX
void setup() {
// bluetooth bee setup
softSerial.print("\r\n+STWMOD=0\r\n"); // set to slave
delay(1000);
softSerial.print("\r\n+STNA=MYAPP\r\n"); // set name
delay(1000);
// Serial.print("\r\n+STAUTO=1\r\n"); // permit auto-connect of paired devices
softSerial.print("\r\n+STOAUT=1\r\n");
delay(1000);
//Serial.print("\r\n +STPIN=0000\r\n"); // set PIN
//delay(1000);
softSerial.print("\r\n+STBD=9600\r\n"); // set baud
delay(2000); // required
// initiate BTBee connection
softSerial.print("\r\n+INQ=1\r\n");
delay(20000); // wait for pairing
// Start the software serial.
softSerial.begin(9600);
// Start the hardware serial.
Serial.begin(9600);
}
I think the pins are right -- 2 and 3 seem to be the pins that connect to the bluetooth bee. I've been googling for 2 days straight, and people don't seem to have problems pairing. What am I doing wrong?
Thanks,
Ok -- this took me nearly three solid days of Google-fu, and I stumbled across this page. Apparently that guy, also, had an immense amount of trouble finding a solution, so hopefully having the solution posted on StackOverflow will help future inquirers.
Really, two things are necessary. First, for whatever reason, I have no idea why, you don't worry about the "software serial". Just address the "Serial". Secondly, it will not work if you don't have the baud for the Serial at 38400. I'm actually using a "software serial" to talk to another device, and that baud is at 9600, but for the bluetooth Serial, you want it at 38400.
If you define "setup" as follows, the BluetoothBee should blink red and green, and pair (mac has nothing to do with it):
long DATARATE = 38400; // default data rate for BT Bee
char inChar = 0;
int LED = 13; // Pin 13 is connected to a LED on many Arduinos
void setup() {
Serial.begin(DATARATE);
// bluetooth bee setup
Serial.print("\r\n+STWMOD=0\r\n"); // set to slave
delay(1000);
Serial.print("\r\n+STNA=myDeviceName\r\n"); // set the device name
delay(1000);
Serial.print("\r\n+STAUTO=0\r\n"); // don't permit auto-connect
delay(1000);
Serial.print("\r\n+STOAUT=1\r\n"); // existing default
delay(1000);
Serial.print("\r\n +STPIN=0000\r\n"); // existing default
delay(2000); // required
// initiate BTBee connection
Serial.print("\r\n+INQ=1\r\n");
delay(2000); // wait for pairing
pinMode(LED, OUTPUT);
}
Then, after pairing you should see another serial port under 'tools -> serial port' in your Arduino IDE. If you select that and define the "loop" function as follows, you should be able to send those commands and get verification that you are, in fact, talking to the bluetooth bee:
void loop() {
// test app:
// wait for character,
// a returns message, h=led on, l=led off
if (Serial.available()) {
inChar = Serial.read();
if (inChar == 'a') {
Serial.print("connected"); // test return connection
}
if (inChar == 'h') {
digitalWrite(LED, HIGH); // on
}
if (inChar == 'l') {
digitalWrite(LED, LOW); // off
}
}
}

Events/Interrupts in Serial Communication

I want to read and write from serial using events/interrupts.
Currently, I have it in a while loop and it continuously reads and writes through the serial. I want it to only read when something comes from the serial port. How do I implement this in C++?
This is my current code:
while(true)
{
//read
if(!ReadFile(hSerial, szBuff, n, &dwBytesRead, NULL)){
//error occurred. Report to user.
}
//write
if(!WriteFile(hSerial, szBuff, n, &dwBytesRead, NULL)){
//error occurred. Report to user.
}
//print what you are reading
printf("%s\n", szBuff);
}
Use a select statement, which will check the read and write buffers without blocking and return their status, so you only need to read when you know the port has data, or write when you know there's room in the output buffer.
The third example at http://www.developerweb.net/forum/showthread.php?t=2933 and the associated comments may be helpful.
Edit: The man page for select has a simpler and more complete example near the end. You can find it at http://linux.die.net/man/2/select if man 2 select doesn't work on your system.
Note: Mastering select() will allow you to work with both serial ports and sockets; it's at the heart of many network clients and servers.
For a Windows environment the more native approach would be to use asynchronous I/O. In this mode you still use calls to ReadFile and WriteFile, but instead of blocking you pass in a callback function that will be invoked when the operation completes.
It is fairly tricky to get all the details right though.
Here is a copy of an article that was published in the c/C++ users journal a few years ago. It goes into detail on the Win32 API.
here a code that read serial incomming data using interruption on windows
you can see the time elapsed during the waiting interruption time
int pollComport(int comport_number, LPBYTE buffer, int size)
{
BYTE Byte;
DWORD dwBytesTransferred;
DWORD dwCommModemStatus;
int n;
double TimeA,TimeB;
// Specify a set of events to be monitored for the port.
SetCommMask (m_comPortHandle[comport_number], EV_RXCHAR );
while (m_comPortHandle[comport_number] != INVALID_HANDLE_VALUE)
{
// Wait for an event to occur for the port.
TimeA = clock();
WaitCommEvent (m_comPortHandle[comport_number], &dwCommModemStatus, 0);
TimeB = clock();
if(TimeB-TimeA>0)
cout <<" ok "<<TimeB-TimeA<<endl;
// Re-specify the set of events to be monitored for the port.
SetCommMask (m_comPortHandle[comport_number], EV_RXCHAR);
if (dwCommModemStatus & EV_RXCHAR)
{
// Loop for waiting for the data.
do
{
ReadFile(m_comPortHandle[comport_number], buffer, size, (LPDWORD)((void *)&n), NULL);
// Display the data read.
if (n>0)
cout << buffer <<endl;
} while (n > 0);
}
return(0);
}
}

Resources